Haskell Tree To List
Haskell here we go! Okay so here is an example of the code currently used:
data Tree a = Node (Tree a) (Tree a) | Leaf a | Empty deriving (Show)
main = do
let my_tree = Node (Node (Leaf [1,2,4,9]) (Leaf [3,5,5,8,5])) (Leaf [2,7,5,5,2])
cc my_tree
bb my_tree
aa my_tree
cc my_tree
print("Done")
Simply creating a tree that holds Int lists and need 3 functions to work aa,bb,cc:
cc - simply outputs a tree
bb - ads to each value +2 aa - outputs a list for each value like: [length,minimum, maximum]now there is a code that does all this almost perfectly, I put it in codepad (ask me if you want): http://codepad.org/??????? now as you can see the last output of aa is also a tree
its probably a quick fix but I cant figure it out - so that aa would output not a tree but a list [] of these:开发者_运维技巧[length param,minimum param,maximum param]
in other words, does someone know how to output it as a list, not inside tree??
so in output instead of:Node (Node (Leaf [4,1,9]) (Leaf [6,0,8])) (Leaf [5,2,7])
would be
[[4,1,9],[6,0,8],[5,2,7]]
I believe something has to be modified here:
fmap3 ff (Node l r) = Node (fmap2 ff l) (fmap2 ff r)
fmap3 ff (Leaf x) = Leaf (ff x)
Anyone ??
This one works
data Tree a = EmptyTree | Node a (Tree a) (Tree a)
treeToList :: (Ord a) => Tree a -> [a]
treeToList EmptyTree = []
treeToList (Node root left right) = treeToList left ++ [root] ++ treeToList right
You're trying to perform a reduce operation: turn a tree into a single value (three times: length, maximum, minimum). This cannot be done using a map function, because a map by definition always turns a tree into a tree.
A typical reduce algorithm uses a function to "merge" together two reduced results, and recursively merges the results obtained anywhere in the tree. So, you'll be having something like this:
reduce ff (Node l r) = ff (reduce ff l) (reduce ff r)
reduce ff (Leaf x) = x
Once this is done, you can use a map function to turn your tree of (whatever) into a tree of values to be reduced, and apply the reduce function.
cc tree = [ reduce (+) (fmap2 length tree) ,
reduce (min) (fmap2 minimum tree) ,
reduce (max) (fmap2 maximum tree) ]
EDIT: you've changed your question while I was answering. You can do this using the above reduction function and the list concatenation function ++
, but list concatenation is not very sexy in terms of performance.
There's an idiomatic way to turn a tree into a list by using a traversal with an accumulator argument:
traverse init (Node l r) = traverse (traverse init r) l
traverse init (Leaf x) = x : init
cc tree = traverse [] (fmap2 h tree)
精彩评论