No instance for (Ord int) arising from a use of `>', Haskell

淺唱寂寞╮ 提交于 2019-12-01 23:44:52

问题


other questions and problems, although similar, are not quite like this one. in this specific compiler error, the Haskell GHC won't compile the following code, for the following reason. I don't understand at all - the code is pretty straight forward.

--factorial

fact :: int -> int
fact 0 = 1
fact n | n > 0 = n * fact(n - 1)

main = print (fact 10)

(error:)

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)

Can you explain the problem to me?


回答1:


Int is what you want:

fact :: int -> int

-->

fact :: Int -> Int

Since in Haskell, types need to begin with a cap.

Edit: Thank Yuras for commenting this:

Or if you want you could use a type class:

fact :: Integral a => a -> a

And you can name the type variable whichever you like, including int. Also, Num might fit your purpose better if you want to define factorial over general numbers.



来源:https://stackoverflow.com/questions/17376071/no-instance-for-ord-int-arising-from-a-use-of-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!