gpt4 book ai didi

Haskell AS 绑定(bind)无可辩驳的模式

转载 作者:行者123 更新时间:2023-12-02 04:21:30 25 4
gpt4 key购买 nike

我正在尝试在计算反向波兰表示法表达式的函数中使用无可辩驳的模式和 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com