Reputation: 497
I have a function multThree for multiplying 3 numbers which works with currying. However, when I tried extending this to multiplying four numbers using the same structure it doesn't work. Why is this and how could it be fixed?
multThree :: Num a => a -> (a -> (a -> a))
multThree x = (*) . (*) x
multFour :: Num a => a -> (a -> (a -> (a -> a)))
multFour x = (*) . (*) . (*) x
Error given:
• Occurs check: cannot construct the infinite type: a ~ a -> a
Expected type: a -> a -> a -> a
Actual type: a -> (a -> a) -> a -> a
• In the expression: (*) . (*) . (*) x
In an equation for ‘multFour’: multFour x = (*) . (*) . (*) x
• Relevant bindings include
x :: a (bound at test2.hs:19:10)
multFour :: a -> a -> a -> a -> a
Upvotes: 0
Views: 783
Reputation: 4360
Let’s write it out without (.)
:
multFour x = (*) . (*) . (*) x
= (*) . (\y -> (y*)) . (x*)
= (\w -> (w*)) . (\z -> ((x*z)*))
= (\w -> (w*)) . (\z v -> x*z*v)
= \z -> \u -> (\v -> x*z*v) * u
And so we see that we are trying to multiply a function by a number.
The key error is this:
multFour x = (*) . multThree x
And the types are:
(*) :: Num a => a -> (a -> a)
multThree x :: Num b => b -> (b -> b)
x :: b
(.) :: (y -> z) -> (x -> y) -> (x -> z)
So the types unify as:
a = y
z = (a -> a)
b = x
y = b -> b
multFour :: Num b => b -> x -> z
multFour :: (Num b, Num (b -> b)) => b -> b -> (b -> b) -> (b -> b)
Which is not the type you want it to be.
To fix your code, I recommend:
multFour a b c d = a * b * c * d
This is much more readable.
Upvotes: 3