【发布时间】:2016-09-04 15:39:56
【问题描述】:
我想从前缀符号创建算术二叉树。
我的树定义为:
data Tree a = Leaf Int | Node Tree String Tree deriving (Show)
我想把它转换成算术二叉树,像这样: arithmetic tree
为了从字符串计算前缀表达式,我写了这个函数:
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
这基本上是来自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
现在我想将前缀表达式转换为算术树,这样我就可以遍历树并以这种方式对其进行评估,或者将其转换为后缀或中缀。
我该怎么做?
我想折叠的时候不评估栈,而是创建节点,但是不知道用Haskell怎么表达。
谁能给我一个提示?
【问题讨论】:
-
将
x * y替换为Node x "*" y等。更简单的是,编写foldingFunction (x:y:ys) o | isOp o = Node x o y:ys,其中isOp确定字符串是否是您的运算符之一。
标签: haskell recursion tree fold postfix-notation