Haskell笔记 (16)—— Currying

Currying定义如下:

Currying is the process of transforming a function that takes multiple arguments into a function that takes just a single argument and returns another function if any arguments are still needed.

Haskell中所有函数都可以认为是curried,即函数只包含一个参数。在Haskell类型表示中,->是右相关的,因此f :: a -> b -> c实际上也是f :: a -> ( b -> c ),所以f x y(f x) y

参考资料:
Currying

下面参考自Curried functions

Every function in Haskell officially only takes one parameter. So how is it possible that we defined and used several functions that take more than one parameter so far? Well, it’s a clever trick! All the functions that accepted several parameters so far have been curried functions.

Putting a space between two things is simply function application. The space is sort of like an operator and it has the highest precedence.

So how is that beneficial to us? Simply speaking, if we call a function with too few parameters, we get back a partially applied function, meaning a function that takes as many parameters as we left out. Using partial application (calling functions with too few parameters, if you will) is a neat way to create functions on the fly so we can pass them to another function or to seed them with some data.

关于curry infix function(需要加括号):

Infix functions can also be partially applied by using sections. To section an infix function, simply surround it with parentheses and only supply a parameter on one side. That creates a function that takes one parameter and then applies it to the side that’s missing an operand. An insultingly trivial function:

divideByTen :: (Floating a) => a -> a  
divideByTen = (/10) 

The only special thing about sections is using -. From the definition of sections, (-4) would result in a function that takes a number and subtracts 4 from it. However, for convenience, (-4) means minus four. So if you want to make a function that subtracts 4 from the number it gets as a parameter, partially apply the subtract function like so: (subtract 4).