作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在计算反向波兰表示法表达式的函数中使用无可辩驳的模式和 AS 绑定(bind)。
这是我的代码:
resolveRPN :: String -> [Integer]
resolveRPN = foldl helper [] . words
where
helper ~stack@(x1:x2:xs) el
| el == "+" = (x2 + x1) : xs
| el == "-" = (x2 - x1) : xs
| el == "*" = (x2 * x1) : xs
| el == "/" = (x2 `div` x1) : xs
| otherwise = (read el) : stack
如果你给出一个少于 2 个元素的列表,基本上无可辩驳的方法将会失败,但这应该只用于“+-*/”。如果该函数应用于“10 10”,它应该只使用“否则”并使用 AS 绑定(bind)“堆栈”,并且不应该尝试将其分解为构造函数,但似乎它不能像那样工作。
例如,如果我用助手折叠并使用 [0,0] 作为累加器,即使不需要这个值,一切都可以正常工作。
有人可以解释为什么这段代码仍然引发“无可辩驳的模式”异常吗?或者 Haskell 如何评价这一点?
这是简化的代码:
notWorking :: [Int]
notWorking = helper [] "10"
where
helper ~stack@(x1:x2:xs) el = (read el) : stack
working:: [Int]
working = helper [] "10"
where
helper ~stack el = (read el) : stack
最佳答案
无可辩驳的模式适用于 stack@(x1:x2:xs)
而不是每个都适用,因此当您尝试提取 stack
时,这将自动评估 (x1:x2:xs)
。
此问题可以仅使用不可驳斥的模式匹配来修复,但不能作为定义 hepler
的绑定(bind),如下所示:
helper stack@ ~(x1:x2:xs) el
| el == "+" = (x2 + x1) : xs
| el == "-" = (x2 - x1) : xs
| el == "*" = (x2 * x1) : xs
| el == "/" = (x2 `div` x1) : xs
| otherwise = (read el) : stack
并且这在有效表达式上永远不会失败。
关于Haskell AS 绑定(bind)无可辩驳的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30122855/
我是一名优秀的程序员,十分优秀!