1

I am trying to learn the basics of Haskell and I am having a hard time understanding why the doubleMe type declaration causes an 'Illegal Operator' error, while addThree causes no error at all?

doubleMe :: Int -> Int -> Int
doubleMe x = x + x


addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z

I appreciate any clarification.

Many thanks in advance.

3 Answers 3

5

The declaration requires the type of each argument, and also the type of the result. Since doubleMe has only one argument, the declaration should be doubleMe :: Int -> Int.

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

2 Comments

Oh! I see. So if I was doing doubleMe x = x + x + x + y, the type declaration would be doubleMe :: Int -> Int -> Int ????
Yes, but you would have to add y on the left side of the = too; otherwise you'll get an error.
2

Your doubleMe type signature specifies two parameters.

If you supply only one as is (doubleMe x) then the right hand side should return a function (Int -> Int)

Comments

1

For such type questions ghci is a great tool. Use :t to ask for the type of an expression:

Prelude> let doubleMe x = x + x
Prelude> :t doubleMe
doubleMe :: Num a => a -> a

So the type is a -> a - you have just one argument, not two, as the other answers already pointed out.

You don't get Int because Haskell tries to derive the most general type signature. That's why you get Num a => instead, which means that doubleMe would work for all types a which are instances of the Num type-class (where (+) is defined), which in turn means doubleMe works for Int, Integer, Double (at least if you don't specify a more restrictive type like Int -> Int)...

Comments

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.