Haskell 使用 foldl 的函数组合
Haskell function composition using foldl
我在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]
和字符串运算符 *
并将运算符应用于数组中的最后两项和 returns 以下数组 [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
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
我在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]
和字符串运算符 *
并将运算符应用于数组中的最后两项和 returns 以下数组 [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
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