[Haskell-beginners] Functor on Tree data constructor
Tony Morris
tonymorris at gmail.com
Wed Apr 2 11:42:39 UTC 2014
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
--
Tony Morris
http://tmorris.net/
More information about the Beginners
mailing list