我对函数式编程,尤其是 Haskell 很陌生,有两个问题比比皆是:as-pattern 和通过使用它减少重叠。 给出以下代码示例:
last1 :: [a] -> a
last1 [x] = x
last1 (x:xs) = last xs
last2 :: [a] -> a
last2 [y] = y
last2 (y:ys@(_:_)) = last ys
与 last2
相比,last1
应该不重叠。
我们来看一下具体的Stringf:[]
。它将与 last1
中的 [x]
和 (x:xs)
匹配。
在last2
中它将匹配[y]
。但不是 (y:ys@(_:_))
,因为 ys
必须匹配 (_:_)
并且只满足首先是任何带有 []
的模式。
我的假设正确吗?
现在看一下具体的字符串f:o:o:[]
。现在模式 (y:ys@(_:_))
匹配。在这种情况下,我很好奇绑定(bind)是如何工作的。第一次调用后,ys
是什么?我假设它是o:o:[]
。
最佳答案
在这两种情况下,您的递归都将是last
,而不是last1
/last2
。
last1
should be non overlapping in comparison tolast2
. Lets take a look at the specific Stringf:[]
. It would match to[x]
and(x:xs)
inlast1
.
它可以匹配 (x:xs)
但它不会,因为模式匹配只会匹配第一次成功。在这方面,重叠并不含糊(始终采用第一个定义)。
In
last2
it would match to[y]
. But not to(y:ys@(_:_))
, becauseys
has to match(_:_)
and just fulfills the first any pattern with[]
.
您的措辞有点奇怪,但您是正确的,f:[]
无法与 (y:ys@(_:_))
匹配,因为后者是基本上与 _:_:_
匹配,但不匹配。
Now take a look at the specific String
f:o:o:[]
. Now the pattern(y:ys@(_:_))
matches. In this case I am curious how the binding works. What isys
after the first call? I assume it iso:o:[]
.
ys
等于 o:o:[]
(或 "oo"
或 [o,o]
).
关于haskell - as-pattern 的功能,通过 'as pattern' 的非重叠模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385303/