1

I'm seeking any suggestion how to solve a problem with a binary search tree in Haskell. It has declaration as follows:

data TreeMap v = Leaf | Node { pair::(Integer, v), l::TreeMap v, r::TreeMap v} deriving (Show, Read, Eq, Ord)

Now I want to zip all pairs to have them as array elements. My solution so far is

listMyTuples :: TreeMap v -> [(Integer, v)]
listMyTuples Leaf = []
listMyTuples (Node pair Leaf tree2) = pair : listMyTuples tree2
listMyTuples (Node pair tree1 Leaf) = pair : listMyTuples tree1
...other pattern matching needed 

I'm barely to complete that due to some lack of comprehension what to do in a case of missing leafs. So, how to make some kind of functional brigde between two subtrees to get it right?

Max_ReFactor
  • 67
  • 2
  • 7

1 Answers1

2

Why pattern match on the subtrees? You can just use Node pair t1 t2. Indeed:

listFromTree :: TreeMap v -> [(Integer, v)]
listFromTree Leaf = []
listFromTree (Node pair t1 t2) = pair : listFromTree t1 ++ listFromTree t2

Here we use (++) :: [a] -> [a] -> [a] to append two lists together.

In case one of the two subtrees is a Leaf, then this will result in an empty list, and appending with an empty list, results in the other list.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555