1

A really simple question: I want to implement the multiplication of 2 integers in Haskell. What I wrote doesn't compile:

mult :: Int -> Int -> Int

mult x 1 = x

mult 1 y = y

mult x y = x + (mult x-1 y)

The problem is the last statement. I've tried writing it as:

mult x y = x + (mult x-1 y)

and also

mult x y = x + (mult(x-1,y))

The error I get is:

   Couldn't match expected type `Int' with actual type `Int -> Int'
    In the return type of a call of `mult'

I don't know why the compiler would say that mult returns an Int -> Int when it clearly returns an Int.

1
  • When you apply mult to one argument, like this mult 5, you get something of type Int -> Int because you have partially applied it to one argument. Plainly, you have mult 5 :: Int -> Int. This is pretty unrelated to the issue you're having now, but I thought it might be a useful side note for the future, if not for now. If it is confusing now, ignore this until later and don't worry about it. Commented Apr 21, 2014 at 23:18

3 Answers 3

4

You have to put x-1 into brackets! Like so

mult x y = x + (mult (x-1) y)

By the way, this does not compute the multiplication of x and y :-) Try some examples... it's a little mistake only.

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

1 Comment

haha yea just realized it.. really dumb mistake though really easy to spot :)
4

In

mult x y = x + (mult x-1 y)

the expression within the parentheses parses as:

(mult x) - (1 y)

And so the compiler thinks the first argument to (-) is mult x, which is an Int -> Int function because just one argument (rather than two) is being passed. Instead, you want:

mult x y = x + mult (x-1) y

Comments

0

It's a simple parser issue. The compiler is reading mult x-1 y as ((-) (mult x) y) when what you mean is mult (x-1) y. Function application binds very tightly in Haskell, so it's sometimes better to use too many parentheses rather too few, especially while you're still learning the basics of the language.

The error occurs because the type of (mult x) is Int -> Int but the type of y is Int, and you can't subtract those two things.

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.