的經驗法則是:
- 顛撲不破/懶人模式如果
p
變量x
被徵求~p
匹配一切
- ,考慮所有構造函數中的
p
從除x
到達的語法樹向下移動向下跨越~
:匹配的值將被評估爲與這些構造函數匹配
- 如果匹配abov Ë失敗,拋出一個異常
例子:
case value of ~(x,y:ys,~(z,w:ws)) -> ...
- 如果我們沒有什麼要求,然後
value
不會被評估
- 如果我們要求
x
或y
或ys
,然後value
將根據需要進行評估以匹配y:ys
(和三聯體)
- 如果我們要求
z
或w
或ws
,然後value
將盡可能多的需要相匹配y:ys
和w:ws
評估(和三和一對)
測試:
> case undefined of ~(x,y:ys,~(z,w:ws)) -> "hello"
"hello"
> case (3,undefined,(4,[1])) of ~(x,y:ys,~(z,w:ws)) -> x
*** Exception: Prelude.undefined
> case (3,[],(4,[1])) of ~(x,y:ys,~(z,w:ws)) -> x
*** Exception: Irrefutable pattern failed for pattern (x, y : ys, ~(z, w : ws))
> case (3,[0],(4,undefined)) of ~(x,y:ys,~(z,w:ws)) -> x
3
> case (3,[0],(4,[])) of ~(x,y:ys,~(z,w:ws)) -> x
3
> case (3,[],(4,[1])) of ~(x,y:ys,~(z,w:ws)) -> z
*** Exception: Irrefutable pattern failed for pattern (x, y : ys, ~(z, w : ws))
> case (3,[0],(4,[])) of ~(x,y:ys,~(z,w:ws)) -> z
*** Exception: Irrefutable pattern failed for pattern (z, w : ws)
在我看來,語義可能如果~
下的每個子模式表現得好像它在上面有~
那樣更好。例如。如果~(x,y:ys)
等於~(x,~(y:ys))
。不過,當前的語義確實允許更多的靈活性。
即使存在「as」模式,該規則也適用。例如,在
case value of [email protected] ~(x,y:ys,[email protected](z,[email protected](w:ws))) -> ...
苛刻a
不會評估value
但苛刻的任何其他變量 會導致value
被如此評價相匹配的三倍。 此外,要求任何x,y,ys
也將導致評估匹配 y:ys
中的列表構造函數。相反,匹配b
或z,c,w,ws
中的任何一個將導致value
進一步評估,以便匹配(z,[email protected](w:ws))
以及列表w:ws
(其在第二個~
之下)。
--Here is an example with "as" pattern outside that will succeed
> case (1,[],(2,[3])) of [email protected] ~(x,y:ys,[email protected](z,[email protected](w:ws))) -> a
(1,[],(2,[3]))
--This will fail because the triple as well as y:ys will be evaluated along a
> case (1,[],(2,[3])) of [email protected](x,y:ys,[email protected](z,[email protected](w:ws))) -> a
*** Exception: Irrefutable pattern failed for pattern [email protected](x, y : ys, [email protected](z, [email protected](w : ws)))
在你的代碼,你可以簡單地把~
這樣外「的」結合:
helper [email protected] ~(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
,將工作的優良任何有效的RPN輸入。
你的架構不好,你應該感覺不好。解析與評估分離。 – rightfold
@rightfold我對此有一個解決方法使用第二個用'(x1:x2:xs)= stack'的地方,但我沒有反思「我怎樣才能解決這個問題」,但「Haskell如何工作,爲什麼這不是工作「 –