PDA

View Full Version : need help with haskell


eizeit
12-17-2003, 11:14 AM
data Rose = Node Int [Rose]

rt1:: Rose
rt1 = Node 3 [ Node 4 [], Node 5 [Node 6 [], Node 7 [], Node 8 []]]

how to define leaves :: Rose -> [Int]
so that from rt1 the leaves are [4,6,7,8]

here what ive done so far..
leaves :: Rose -> [Int]
leaves (Node x []) = []
leaves (Node x [Node n []]) = [n]
leaves (Node x (Node n [] : [xs])) = [n] ++ leaves xs

help plz....

Little_C
12-20-2003, 01:35 AM
OK:

I don't know haskell. But a few tips on getting a reply:

use CODE tags.

Try to explain what doen't work in the code, and what you are trying to get it to do. If possible, provide an error message from the compiler/interpreter/whatever.

I hope this helps you get a reply faster

slidewinder
12-21-2003, 06:10 PM
You could try something like this:


leaves :: Rose -> [Int]
leaves (Node x []) = [x]
leaves (Node _ (x:xs)) = leaves x ++ leaves' xs
where
leaves' [] = []
leaves' (x':xs') = leaves x' ++ leaves' xs'


The important bit being "leaves'" in the where clause that breaks down your [Rose] list.

Or, if you want to get cute:

leaves :: Rose -> [Int]
leaves (Node x []) = [x]
leaves (Node _ (x:xs)) = leaves x ++ concatMap leaves xs


Where "concatMap" is a prelude function much like "map", except it takes a function that returns a list (here our "leaves") and concatenates the lists returned so that you get a list with all "top level" values, instead of a list made up of potentially nested lists. I.e., [1, 2, 3] instead of something like [1, [2,3]].