psyGhost
psyGhost

Reputation: 21

Binary Tree type constructor in Haskell

I'm trying binary tree type constructor which is:

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

How we prove that not all kinds of binary tree can be represented by this constructor? How we improve this definition to cover all types of binary tree? And how it works?

Upvotes: 0

Views: 666

Answers (2)

Will Ness
Will Ness

Reputation: 71119

Ask yourself, how many a values can your tree hold? They appear either in leaves or nodes,

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

so

num_values  =      1 | (      1 + num_values + num_values  )

It doesn't make much sense in this form, so let's write it as

numvals     =      1 : [      1 +            s          | s <- diagonalize
                                 [ [   n     +     m    | m <- numvals ] 
                                                        | n <- numvals   ] ]

diagonalize :: [[a]] -> [a]
diagonalize ((n:ns):t) = n:go [ns] t
   where
   go as (b:bs) = map head as ++ go (b:map tail as) bs

so that we get

~> take 100 numvals
[1,3,5,5,7,7,7,7,7,9,9,9,9,9,11,9,9,9,11,11,11,11,9,9,11,13,11,13,11,9,9,11,13,1 3,13,13,11,9,9,11,13,13,15,13,13,11,11,11,11,13,13,15,15,13,13,11,11,11,13,13,13 ,15,15,15,13,13,13,11,11,13,15,13,15,15,15,15,13,15,13,11,11,13,15,15,15,15,15,1 5,15,15,15,13,11,11,13,15,15,17,15,15]

but you want 0, 2, 4, ... to appear there as well.

edit: It is easy to fix this, with

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

Now

numvals2    =    0 : [      1 +       s          | s <- diagonalize
                          [ [     n   +   m      | m <- numvals2 ] 
                                                 | n <- numvals2   ] ]

and

~> take 100 numvals2
[0,1,2,2,3,3,3,3,3,4,4,4,4,4,5,4,4,4,5,5,5,5,4,4,5,6,5,6,5,4,4,5,6,6,6,6,5,4,4,5 ,6,6,7,6,6,5,5,5,5,6,6,7,7,6,6,5,5,5,6,6,6,7,7,7,6,6,6,5,5,6,7,6,7,7,7,7,6,7,6,5 ,5,6,7,7,7,7,7,7,7,7,7,6,5,5,6,7,7,8,7,7]

Upvotes: 1

Benjamin Hodgson
Benjamin Hodgson

Reputation: 44664

Your Tree a has labels of type a at every Branch and every Leaf constructor. So, for example, Branch 'u' (Branch 'n' (Leaf 'i') (Leaf 'p')) (Leaf 'z') looks like this:

    +-'u'-+
    |     |
 +-'n'-+ 'z'
 |     |
'i'   'p'

That excludes, say, trees with different labels at the nodes and leaves, or trees that are labelled only internally or only externally. For example, this tree has numbers at the leaves and characters at the nodes.

    +-'o'-+
    |     |
 +-'h'-+  9
 |     |
 7     2

(You can use Tree (Either n l) but that doesn't encode the invariant that only ns appear internally and only ls appear externally.)

Since this appears to be a homework assignment I won't tell you what a more general type of tree might look like, but I'm sure you can figure it out.

Upvotes: 2

Related Questions