没有 (Ord int) 的实例因使用">"而产生,Haskell(哈斯克尔)



其他问题虽然相似,但与此不同。在这个特定的编译器错误中,Haskell GHC不会编译以下代码,原因如下。我一点也不明白——代码很直接。

--factorial
fact :: int -> int
fact 0 = 1
fact n | n > 0 = n * fact(n - 1)
main = print (fact 10)

(错误:)

No instance for (Ord int) arising from a use of `>'
Possible fix:
add (Ord int) to the context of
the type signature for fact :: int -> int
In the expression: n > 0
In a stmt of a pattern guard for
an equation for `fact':
n > 0
In an equation for `fact': fact n | n > 0 = n * fact (n - 1)

你能向我解释一下这个问题吗?

Int就是您想要的:

fact :: int -> int

-->

fact :: Int -> Int

由于在Haskell中,类型需要以cap开头。

编辑:感谢尤拉斯对此的评论:

或者,如果你愿意,你可以使用一个类型类:

fact :: Integral a => a -> a

您可以随意命名类型变量,包括int。此外,如果你想定义阶乘而不是一般数,Num可能更符合你的目的。

最新更新