Haskell 中否定文字的模式匹配

pattern matching of negative literals in Haskell

我试图理解为什么 Haskell 中禁止使用 n + k 模式。 Whosebug上一个著名的post给出了一个函数的例子如下:

f 0 = 0
f (n + 5) = 5

Haskell 在匹配 f 1、f 2、f 3、f 4 时显示错误。 我不明白为什么 (-1) 不能与 n 匹配。首先,我认为整数只包含非负文字 (0,1,..),但 Haskell 对 Int 类型的定义包括负文字。

为什么-1匹配不到?这就是 n+k 模式的定义方式,大概是因为这在当时看起来是个好主意。对自然数使用归纳法很自然,那么为什么不定义我们很酷的 n+k 模式来处理自然数呢?来自 the Haskell report:

Matching an n+k pattern (where n is a variable and k is a positive integer literal) against a value v succeeds if x >= k, resulting in the binding of n to x - k, and fails otherwise. Again, the functions >= and - are overloaded, depending on the type of the pattern. The match diverges if the comparison diverges.

您发现这令人惊讶的事实可能是删除 n+k 模式的原因之一。另一个是不需要它们:您可以轻松地将任何 n+k 模式转换为不使用此功能的模式。