Advertisement
Guest User

Untitled

a guest
Sep 18th, 2014
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. module RoseTree where
  3.  
  4.  
  5. -- A tree whose nodes can have an arbitrary finite number of children is sometimes called
  6. -- a "Rose Tree". Our particular variant stores a value of type 'a' at each node, at at each leaf.
  7.  
  8. data RoseTree a = Node a [RoseTree a]
  9.                 | Leaf a
  10.   deriving (Show)
  11.            
  12. -- A rose tree is a functor, meaning it has a "map" function. This function
  13. -- applies a given function f :: A -> B to every value in a rose tree, preserving
  14. -- the tree structure.
  15.  
  16. instance Functor RoseTree where
  17.   fmap f (Node v children) = (Node (f v) (map (fmap f) children))
  18.   fmap f (Leaf v) = (Leaf (f v))
  19.  
  20. -- It also has a fold, which you can think of as replacing every occurrence
  21. -- of the "Node" constructor with "nf" and every occurrence of the "Leaf"
  22. -- constructor with "lf".
  23. --
  24. -- For example. foldRoseTree (\ v cs -> RoseTree v cs) (\ v -> Leaf v)
  25. -- will give you back the original rose tree!
  26.  
  27. foldRoseTree :: (a -> [b] -> b) ->  (a -> b) -> (RoseTree a) -> b
  28. foldRoseTree nf lf (Node v children) = nf v (map (foldRoseTree nf lf) children)
  29. foldRoseTree nf lf (Leaf v) = lf v
  30.  
  31. -- exercise: Implement fmap for RoseTree in terms of foldRoseTree
  32.  
  33. -- some examples
  34.  
  35. -- First, if we want to say, add one to every value stored in a rose tree of
  36. -- integers, we simply do
  37.  
  38. treePlusOne :: RoseTree Integer -> RoseTree Integer
  39. treePlusOne = fmap (+1)
  40.  
  41. -- We could also map all the 0 values to True and all the nonzero values to False
  42.  
  43. treeIntToBool :: RoseTree Integer -> RoseTree Bool
  44. treeIntToBool = fmap (\x -> if x == 0 then True else False)
  45.  
  46. -- we can also use fold to do some more complicated things, for example
  47. -- we could sum all the values in an integer rose tree by doing
  48.  
  49. treeSum :: RoseTree Integer -> Integer
  50. treeSum = foldRoseTree (\ v vs -> v + (sum vs)) id
  51.  
  52. -- finally, an example RoseTree Integer for you to play with. (try drawing it if you
  53. -- are having trouble visualizing the structure!)
  54.  
  55. exampleTree :: RoseTree Integer
  56. exampleTree = (Node 3 [(Node 4 [(Leaf 7),(Node 5 [(Leaf 6)])]),(Leaf 1),(Node 2 [(Leaf 3)])])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement