haskell - as-pattern 的功能,通过 'as pattern' 的非重叠模式

标签 haskell design-patterns overlapping-matches as-pattern

我对函数式编程,尤其是 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 to last2. Lets take a look at the specific String f:[]. It would match to [x] and (x:xs) in last1.

它可以匹配 (x:xs) 但它不会,因为模式匹配只会匹配第一次成功。在这方面,重叠并不含糊(始终采用第一个定义)。

In last2it would match to [y]. But not to (y:ys@(_:_)), because ys 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 is ys after the first call? I assume it is o:o:[].

ys 等于 o:o:[] (或 "oo"[o,o]).

关于haskell - as-pattern 的功能,通过 'as pattern' 的非重叠模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385303/

相关文章:

haskell - OCaml 有融合定律吗

java - 使用新功能丰富类的设计模式

java - 生成调用图的好算法?

python - 如何找到所有大小可变的重叠匹配项?

python - 匹配并索引所有子字符串,包括重叠的子字符串

haskell - 如何防止抢劫模板中的 JavaScript 逃逸?

haskell - 如何在 Haskell 中迭代 `newtype` 列表

Haskell:为什么以下顺序运行?

组中的MySQL重叠日期

java - 使用 Bloch 的 Builder 模式是否会影响内存和性能?