Haskell - displaying a function over a rose tree

If I define a rose tree as

data RTree = Node a [RTree a]
    deriving(Show, Eq)


How do I define the definition of a map function? The map function should be defined as

map_rose_tree :: (a -> b) -> RTree a -> RTree b



source to share

1 answer

The easiest way is to enable the extension DeriveFunctor

and derive Functor


{-# LANGUAGE DeriveFunctor #-}

data RTree a
    = Node a [RTree a]
    deriving (Show, Eq, Functor)

map_rose_tree = fmap


But if you want to define the instance yourself, you need to match the pattern in the constructor RTree


instance Functor RTree where
    fmap f (Node a children) = Node _ _


You will need to complete two by _

yourself. If you have a reasonably newer version of GHC, you can compile this and get errors telling you the hole types ( _

) along with the appropriate links you can use to implement it. The first hole is rather simple, the second - a little more complicated, but I assure you that it can be solved only by using fmap

, f

, a

and children




All Articles