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?