3

I want to create arithmetic binary tree from prefix notation.

My tree is defined as:

data Tree a = Leaf Int | Node Tree String Tree deriving (Show)

I want to convert it to arithmetic binary tree, like this: arithmetic tree

To evaluate prefix expression from string, I wrote this function:

evaluatePrefix:: String -> Int
evaluatePrefix expression = head (foldl foldingFunction [] (reverse (words  ( expression))) )
where   foldingFunction (x:y:ys) "*" = (x * y):ys  
        foldingFunction (x:y:ys) "+" = (x + y):ys  
        foldingFunction (x:y:ys) "-" = (x - y):ys  
        foldingFunction (x:y:ys) "/" = ( x `div` y):ys  
        foldingFunction xs numberString = read numberString:xs 

Which is basically an algorithm from wikipedia

Scan the given prefix expression from right to left
for each symbol
 {
  if operand then
    push onto stack
  if operator then
   {
    operand1=pop stack
    operand2=pop stack
    compute operand1 operator operand2
    push result onto stack
   }
 }
return top of stack as result

Now I want to convert prefix expression into the arithmetic tree, so I can walk the tree and evaluate it that way, or convert it to postfix or infix.

How could I do that?

I thought of not evaluatig stack when folding, but instead creating nodes, but I don't know how to express it in Haskell.

Can anybody give me a hint?

  • 1
    Replace `x * y` with `Node x "*" y`, etc. Simpler yet, write `foldingFunction (x:y:ys) o | isOp o = Node x o y:ys` where `isOp` determines if the string is one of your operators. – user2407038 May 09 '16 at 21:09

1 Answers1

4

Here's a hint -- in your foldingFunction approach, the first argument is a list of numbers. Use the same approach, but this time the first argument will be a list of Tree values.

When the folding function comes across a number, e.g. "3", you'll want to push Leaf 3 onto the stack.

When it comes across an operator like *, you'll want to push Node x "*" y where x and y are the Tree values of the top two values on the stack.

ErikR
  • 51,541
  • 9
  • 73
  • 124