[Haskell-beginners] Functor on Tree data constructor
Gesh
gesh at gesh.uni.cx
Wed Apr 2 12:19:18 UTC 2014
On April 2, 2014 2:42:39 PM GMT+03:00, Tony Morris <tonymorris at gmail.com> wrote:
>On 03/04/14 00:37, Gesh wrote:
>>> On 2014-04-02 12:53, Nishant wrote:
>>>> Can some explain me the error and a possibly a fix :
>>>>
>>>> data Tree a = NULL | Node (Tree a ) a (Tree a)
>>>>
>>>> instance Functor Tree where
>>>> fmap f NULL = NULL
>>>> fmap f (Node left x right) | (left == NULL) && (right == NULL)
>=
>>>> Node left (f x) right
>>>> | (left /= NULL) = Node (fmap f
>left)
>>>> x right
>>>> | (right /= NULL) = Node left x
>(fmap
>>>> f right)
>> Note that you can simplify your instance declaration to:
>>> instance Functor Tree where
>>> fmap f NULL = NULL
>>> fmap f (Node left x right) = Node (f' left) (f x) (f' right)
>>> where f' x = if x == NULL then NULL else fmap f x
>> Also note that the NULL in the then clause differs from x. Let f :: a
>-> b, then x :: Tree a and the NULL in that clause :: Tree b. These
>values are as distinct as 2 :: Int and 2.0 :: Double.
>> HTH,
>> Gesh
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://www.haskell.org/mailman/listinfo/beginners
>
>instance Functor Tree where
> fmap f NULL = NULL
> fmap f (Node left x right) = Node (f' left) (f x) (f' right)
> where f' = fmap f
Oops. I should have noticed my case analysis was unnecessary. Still, the comments accompanying it are correct. NULL :: Tree a and NULL :: Tree b are distinct values of distinct types, and therefore using one where the other is expected will make GHC disappointed in you.
Gesh
More information about the Beginners
mailing list