简体   繁体   中英

How to curry functions in Haskell

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM