Avi Caspe
Avi Caspe

Reputation: 575

Simple Haskell Factorial Function not compiling

So I have this simple Haskell function:

fact :: (Num a) => a -> a
fact 0 = 1
fact n = n * fact (n - 1)

and when I try to compile it with GHCi, I get an error:

test.hs:2:6: error:
    • Could not deduce (Eq a) arising from the literal ‘0’
      from the context: Num a
        bound by the type signature for:
                   fact :: Num a => a -> a
        at test.hs:1:1-25
      Possible fix:
        add (Eq a) to the context of
          the type signature for:
            fact :: Num a => a -> a
    • In the pattern: 0
      In an equation for ‘fact’: fact 0 = 1
Failed, modules loaded: none.

Look, I know that better way to write this function exist, but I don't care. I just want to get this function to compile. I can't do that though. It was my impression that if something was a number, it must be an instance of Eq a, and therefore the compiler's suggestion of a possible fix is wrong.

How can I get this code to compile?

Upvotes: 0

Views: 226

Answers (1)

chepner
chepner

Reputation: 532448

Your assumption that a type that is an instance of Num must also be an instance of Eq is false. Consider the inferred type for your function:

> fact 0 = 1; fact n = n * fact (n - 1)
> :t fact
fact :: (Num t, Eq t) => t -> t

To be an instance of Num, a type need only define the following functions:

  • (+)
  • (*)
  • abs
  • signum
  • fromInteger
  • either negate or (-)

Upvotes: 1

Related Questions