使用foldl的Haskell函数合成

时间:2019-01-03 07:35:43

标签: haskell fold foldleft

我在haskell中定义了以下函数:

step :: [Int] -> [Char] -> [Int]
step stack str
    | str == "*" =  remaining ++ [x*y] 
    | str == "+" =  remaining ++ [x+y]
    | str == "-" =  remaining ++ [x-y]
    | str == "/" =  remaining ++ [x `div` y]
    | otherwise = stack ++ [read str :: Int] 
    where x = (last . init) stack
          y = (last stack)
          remaining = (init . init) stack

此函数采用整数数组[10, 4, 3]和字符串运算符*,并将该运算符应用于数组的最后两项,并返回以下数组[10, 7]

这是一个中间函数的一部分,最终结果是反向抛光符号求值器函数。

如何使用已定义的step函数和foldl进行以下操作

使用示例字符串:"10 4 3 + 2 * -"

将每个元素添加到字符串上,直到遇到第一个运算符为止:

10, 4, 3然后将运算符应用于堆栈顶部的两个元素,并将结果放在堆栈上:

10, 7

如此继续,直到评估出最终答案(-4

答案:

为了完整起见,这是我在@talex的帮助下实现的功能

rpn :: String -> Int
rpn input = head result
    where arr = words input
          result = foldl step [] arr

1 个答案:

答案 0 :(得分:1)

foldl step [] ["10",  "4", "3", "+", "2", "*", "-"]

[]是初始堆栈。

如果您以以下方式重写您的步骤,它将更快地工作:

step :: [Int] -> [Char] -> [Int]
step stack str
        | str == "*" =  (x*y):remaining 
        | str == "+" =  (x+y):remaining
        | str == "-" =  (x-y):remaining
        | str == "/" =  (x `div` y):remaining
        | otherwise = (read str :: Int):stack
        where x = head $ tail stack
              y = head stack
              remaining = tail $ tail stack