Joe
Joe

Reputation: 365

Representing functions as trees

I'm doing a past Function Programming exam paper and have this question:

Here are two ways of writing essentially the same expression:

f (g(x,y),z,h(t))

f (g x y) z (h t)

(a) Illustrate the different structures of the two expressions by drawing them as two different kinds of tree.

(b) Define Haskell data types Bush a and Tree a to capture the two different structures.

I'm kind of stuck because I've never done any thing like this in my course. It's pretty obvious from a later part that the first expression should be represented by Tree a and the second by Bush a, but I don't really know where to go from here. I guessed something like:

data Tree a = Leaf a | Node (Tree a) (Tree a)
data Bush a = Node a [Bush a]

But I don't think the Binary tree type is the right one to use. Could someone point me in the right direction?

Upvotes: 1

Views: 444

Answers (1)

Emily
Emily

Reputation: 2684

Actually, the first expression is represented by Bush and the second by Tree.

In Haskell, g x y means that g x is applied to y; in C, g(x, y) means that g is applied to a collection of arguments — {x, y}. Therefore, in C:

f(g(x,y),z,h(t)) = Bush f [Bush g [Bush x [], Bush y []], Bush z [], Bush h [Bush t []]]

  f
  +--g
  |  +--x
  |  +--y
  |
  +--z
  |
  +--h
     +--t

And in Haskell:

f (g x y) z (h t) = App (App (App f (App (App g x) y)) z) (App h t)

         +
        / \
       /  /\
      +  h  t  
     / \
    /\  z
   f  +
     / \
    /\  y
   g  x

Upvotes: 4

Related Questions