简体   繁体   English

为什么我的Haskell函数不接受负数?

[英]Why doesn't my Haskell function accept negative numbers?

I am fairly new to Haskell but do get most of the basics. 我对Haskell相当新,但确实掌握了大部分基础知识。 However there is one thing that I just cannot figure out. 然而,有一件事我无法弄清楚。 Consider my example below: 考虑下面的例子:

example :: Int -> Int
example (n+1) = .....

The (n+1) part of this example somehow prevents the input of negative numbers but I cannot understand how. 这个例子的(n + 1)部分以某种方式阻止输入负数,但我无法理解如何。 For example.. If the input were (-5) I would expect n to just be (-6) since (-6 + 1) is (-5). 例如..如果输入为(-5),我认为n只是(-6),因为(-6 + 1)是(-5)。 The output when testing is as follows: 测试时的输出如下:

Program error: pattern match failure: example (-5) 程序错误:模式匹配失败:示例(-5)

Can anyone explain to me why this does not accept negative numbers? 任何人都可以向我解释为什么这不接受负数?

That's just how n+k patterns are defined to work: 这就是如何定义n + k模式的工作方式:

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. 如果x> = k,则将n + k模式(其中n是变量,k是正整数文字)与值v匹配成功,导致n与x-k的绑定,否则失败。

The point of n+k patterns is to perform induction, so you need to complete the example with a base case (k-1, or 0 in this case), and decide whether a parameter less than that would be an error or not. n + k模式的要点是执行归纳,因此您需要使用基本情况(在这种情况下为k-1或0)完成示例,并确定小于该参数的参数是否是错误。 Like this: 像这样:

example (n+1) = ...
example 0 = ...

The semantics that you're essentially asking for would be fairly pointless and redundant — you could just say 你基本上要求的语义将是毫无意义和多余的 - 你可以这么说

example n = let n' = n-1 in ...

to achieve the same effect. 达到同样的效果。 The point of a pattern is to fail sometimes. 模式的重点有时会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM