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

2020-04-10 02:59发布

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条回答
Animai°情兽
2楼-- · 2020-04-10 03:56

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.

查看更多
登录 后发表回答