【问题标题】:Haskell - create artihmetic tree from prefix expressionHaskell - 从前缀表达式创建算术树
【发布时间】: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


【解决方案1】:

这里有一个提示——在您的foldingFunction 方法中,第一个参数是一个数字列表。使用相同的方法,但这次第一个参数将是Tree 值的列表。

当折叠函数遇到一个数字时,例如“3”,您需要将Leaf 3 推入堆栈。

当遇到像* 这样的运算符时,您需要推送Node x "*" y,其中xy 是堆栈顶部两个值的Tree 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多