Reputation: 13
I need to write a non-recursive function that transforms my tree. But I can't use my own map function for trees. Is there a standard map function for trees in Haskell?
data BTree a = Tip a | Bin (BTree a) (BTree a)
exapmeTree = Bin (Bin (Tip [1,2,3,4,5]) (Tip [3,9,7])) (Bin (Tip [6,7,8,9]) (Tip [8,2,1]))
myReverse list = foldl (\acc x -> x : acc) [] list
reverseTree tree = map myReverse tree
Upvotes: 0
Views: 169
Reputation: 4733
You can either write the fmap function yourself, as demonstrated by Rik.
Or you can use the fmap function provided by the automatically generated Functor instance.
Testing under ghci
:
$ ghci
GHCi, version 8.6.5: http://www.haskell.org/ghc/ :? for help
λ>
λ> :set -XDeriveFunctor
λ>
λ> data BTree a = Tip a | Bin (BTree a) (BTree a) deriving (Eq, Show, Functor)
λ>
λ> exampleTree = Bin (Bin (Tip [1,2,3,4,5]) (Tip [3,9,7])) (Bin (Tip [6,7,8,9]) (Tip [8,2,1]))
λ>
λ> reverseTree = fmap reverse exampleTree
λ>
λ> reverseTree
Bin (Bin (Tip [5,4,3,2,1]) (Tip [7,9,3])) (Bin (Tip [9,8,7,6]) (Tip [1,2,8]))
λ>
Upvotes: 1
Reputation: 331
Since you've created the BTree
type yourself, no, there is no standard function for it. You can quite easily write a Functor
instance yourself though.
instance Functor BTree where
fmap f (Tip a) = Tip (f a)
fmap f (Bin l r) = Bin (fmap f l) (fmap f r)
Now you can write reverseTree tree = fmap myReverse tree
.
Note that fmap
is the exact same as map
in the context of lists, but it is more generic, meaning it works for any Functor
instance.
Upvotes: 2