I'm trying to define an instance of Functor for my Tree datatype in Haskell
I'm learning about functors this afternoon and am trying to write one for a tree data type I just wrote up.
data GTree a = Node a [GTree a] deriving (Show, Read, Eq)
instance Functor GTree where
fmap f n [] = f n
fmap f n a = f n fmap a
I'm trying to write it so that if the list is empty, map over the single node. Otherwise, recursively map over the list. Here's the error I get.
The equation(s) for `fmap' have three arguments, but its type `(a -> b) -> GTree a -> GTree b' has only two In the instance declaration for `Functor GTree'
I understand that I have too many arguments for fmap, but I can't figure out how to write this out so that it reflects what I want it to do.
If anybody could help me out with this it would be much appreciated. Thank you!
EDIT: Here's one possible solution I found, I don't really und开发者_运维知识库erstand it though.
instance Functor GTree where
fmap f (Node a ts) = Node (f a) (map (fmap f) ts)
What fmap does is it takes a function with type a -> b
plus a box of a
and it'll return box of b
. Instead of n []
and n a
you should use (Node a [])
and (Node a xs)
, which will match against Node without any children and Node with children.
instance Functor GTree where
fmap f (Node a xs) = Node (f a) (fmap (fmap f) xs)
精彩评论