[英]How to curry functions in Haskell
I have a function multThree for multiplying 3 numbers which works with currying. 我有一个函数multThree,用于将3个数字相乘,从而可以使用curring。 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. 这更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.