Reputation: 150
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
.
Upvotes: 1
Views: 4382
Reputation: 34378
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
Upvotes: 4
Reputation: 796
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.
Upvotes: 4
Reputation: 1519
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.
Upvotes: 0