【问题标题】:No instance for (Ord int) arising from a use of `>', Haskell没有使用 `>' 产生 (Ord int) 的实例,Haskell
【发布时间】:2013-06-29 02:22:00
【问题描述】:

其他问题和问题虽然相似,但与这个不太相似。在这个特定的编译器错误中,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)

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

【问题讨论】:

    标签: haskell compilation


    【解决方案1】:

    Int 是你想要的:

    fact :: int -> int
    

    -->

    fact :: Int -> Int
    

    由于在 Haskell 中,类型需要以大写字母开头。

    编辑:感谢 Yuras 对此发表评论:

    或者,如果您愿意,可以使用类型类:

    fact :: Integral a => a -> a
    

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

    【讨论】:

    • 为什么不Num int => int -> int? :)
    • @Yuras 嗯,这更好 - 我更喜欢 Integral,但很好的提示!
    • facepalm 谢谢。这是我用 Haskell 编写和编译的第一个程序(包含一个函数)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多