DemianArdus
DemianArdus

Reputation: 827

Haskell expression evaluation?

I have the following type and function definitions:

data Tree a = Tree a [Tree a]
list t = list' [t]
           where list'  [] = []
                 list'  (Tree a hs:ts) = a : list' (ts ++ hs)

and I have this expression:

list (Tree (-1) [Tree 0 [ Tree 4 [], Tree 7 []],Tree 8 [Tree 5 []]])

Which is giving me:

[-1,0,8,4,7,5]

Problem is I can't understand why! I think my problem is that I can't understand why list' takes a list as an argument and at the second where expressions it uses: (Tree a hs:ts), and not something like x:xs. I'm new at Haskell so probably this is something basic but I couldn't understand it. Thank you and sorry for my english!

Upvotes: 1

Views: 99

Answers (1)

hugomg
hugomg

Reputation: 69924

Pattern matches can be nested. So x:xs is not the only way to pattern match against a non-empty list.

When you match (Tree a hs : ts) against a list of trees, what it does is bind the tail of the list of trees to ts and continue pattern matching the first tree in the list against Tree a hs. This will bind a to the key of the first element of the list of trees and hs to the child trees of the first tree of the list of trees.

Upvotes: 4

Related Questions