2

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?

3
  • 4
    That is because Haskell has interpreted it as factorial - 4 (so a subtraction), you should use factorial (-4). Commented Aug 7, 2018 at 20:09
  • 1
    See: stackoverflow.com/q/20391391/67579 Commented Aug 7, 2018 at 20:10
  • I don't really believe "My code works fine without the last line". What makes you think that? Commented Aug 7, 2018 at 21:18

1 Answer 1

6

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 Number, hence the error. Strictly speaking, one can make functions Numbers, 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).

Sign up to request clarification or add additional context in comments.

2 Comments

Ok! Thanks for your help. Here is fatorial (pt language...). ;)
@eightShirt: aah, I removed the note :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.