[Haskell-beginners] pattern matching on date type

Alexander Dunlap alexander.dunlap at gmail.com
Thu Jan 1 04:44:33 EST 2009


On Thu, Jan 1, 2009 at 12:36 AM, Max.cs <max.cs.2009 at googlemail.com> wrote:
> thanks!
>
> suppose we have
>
>> data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show
>
> and how I could define a function foo :: a -> Tree a that
>
> foo a = Leaf a         where a is not a type of Tree
> foo b = b                 where b is one of the type of Tree (Leaf or
> Branch) ?
>
> The following code seems not working......
>
> foo (Leaf a) = a
> foo a = Leaf a
>
> saying 'Couldn't match expected type `a' against inferred type `Btree a''
>
> any idea?
>
> Thanks,
> Max

You can't define such a function. foo :: a -> Tree a, but the
definition foo b = b has the type a -> a, which is why the compiler
says it can't match type "a" against "Tree a". In general, Haskell
functions can't "look" at the type of their arguments: they are either
monomorphic or are polymorphic, in which case you can only use
polymorphic functions that match the polymorphic type. For the problem
you are trying to solve, you probably need to encode this logic higher
up in the overall function (e.g. have one function to deal with "a"s
and another to deal with "Tree a"s).

Hope that helps,
Alex


More information about the Beginners mailing list