[Haskell-beginners] Functor on Tree data constructor

Gesh gesh at gesh.uni.cx
Wed Apr 2 11:37:03 UTC 2014


>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


More information about the Beginners mailing list