Reputation: 1447
I am using GHCI 7.10.3 and I'm getting error in a simple fatorial code.
I would like to do something like this:
fatorial n
| n == 0 = 1
| n > 0 = n * fatorial(n-1)
| otherwise = error "My error"
But when fatorial -4
was called, the output was:
:21:1: Non type-variable argument in the constraint: Num (a -> a) (Use FlexibleContexts to permit this) When checking that ‘it’ has the inferred type it :: forall a. (Num a, Num (a -> a), Ord a) => a -> a
My code works fine without the last line. So how can I use error message in haskell?
Upvotes: 2
Views: 1081
Reputation: 476574
Well the error is a type error, so that means that Haskell thinks that what you wrote makes no sense (from a type system point of view).
It interprets the -
as the "binary minus operator", like:
-- v operator
factorial - 4
-- ^ operand ^
So Haskell thinks you want to subtract 4
from factorial
, but it does not see how factorial
is a Num
ber, hence the error. Strictly speaking, one can make functions Num
bers, as long as one implements the Num
typeclass (as well as the Eq
and Show
typeclasses) we are fine.
If you want to use negative number literals in such function call, you need to use brackets, like:
factorial (-4)
This then produces:
Prelude> fatorial (-4)
*** Exception: My error
CallStack (from HasCallStack):
error, called at <interactive>:5:19 in interactive:Ghci1
So now it raises your error "My error"
(see the first output line).
Upvotes: 6