0

I want to do what the title says, but it keeps me showing errors. I put my code below.

data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show

treeToList :: Tree a -> [a]
treeToList (Leaf x) = [x]
treeToList (Branch a b) = (treeToList a):(treeToList b)

It would show something like this:

treeToList Branch (Branch (Leaf 2) (Leaf 3)) (Leaf 4)

[2,3,4]

8
  • I see this kind of tree (with data in leaves but not in branches) every now and then, and always wonder what's the point of it. Commented Nov 17, 2014 at 18:55
  • @n.m. Isn't it recursively defined in Branch anyway ? Commented Nov 17, 2014 at 18:57
  • @Sibi Consider this: data List a = Continue (List a) | Finish a. Makes sense? Commented Nov 17, 2014 at 19:02
  • @n.m. But your data structure only allows to store one data. (eg: Continue (Continue (Continue (Finish 3)))) ? Commented Nov 17, 2014 at 19:08
  • @n.m.- my filesystem is a tree with data in the leaves (files) but not in the branches (the dirs).... Makes sense to me. Commented Nov 17, 2014 at 19:12

1 Answer 1

2

In the first pattern match you get a value of type list. Now all you have to do is concatenate them when you pattern match the Branch constructor.

treeToList :: Tree a -> [a]
treeToList (Leaf x) = [x]
treeToList (Branch a b) = (treeToList a) ++ (treeToList b)

Demo in ghci:

*Main> treeToList (Branch (Branch (Leaf 2) (Leaf 3)) (Leaf 4))
[2,3,4]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.