The Corialization of Scala Series
The Corialization of the Scala series, which transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function).
And returns the technique of a new function that accepts the remaining parameters and returns the result.
Let's first give a common non-Corialized function definition and implement an addition function:
Scala > def plainOldSum (XRU IntMagi YRO Int) = x + y
PlainOldSum: (X: Int, y: Int) Int
Scala > plainOldSum (1Jue 2)
Res0: Int = 3
Using the "Corialization" technique, the function is defined as a list of parameters:
Scala > def curriedSum (x:Int) (y:Int) = x + y
CurriedSum: (X: Int) (y: Int) Int
Scala > curriedSum (1) (2)
Res0: Int = 3
When you call curriedSum (1) (2), you are actually calling two ordinary functions (non-Corialized functions) in turn. The first call uses a parameter x, which returns a value of a function type, and the second time you use the parameter y to call the value of this function type. We use the following two separate definitions to simulate the curriedSum Corialized function:
First define the first function:
Scala > def first (x:Int) = (y:Int) = > x + y
First: (X: Int) Int = > Int
Then we call this function with argument 1 to generate the second function.
Scala > val second=first (1)
Second: Int = > Int =
Scala > second (2)
Res1: Int = 3
The definition of first,second demonstrates the process of calling the Corialization function, which itself has nothing to do with curriedSum, but we can use curriedSum to define second, as follows:
Scala > val onePlus = curriedSum (1)
OnePlus: Int = > Int =
The underscore "" is used as a placeholder for the second parameter list, and the return value of this definition is a function that adds one to the called parameter when called.
Scala > onePlus (2)
Res2: Int = 3
With Corialization, you can also define several onePlus-like functions, such as twoPlus
Scala > val twoPlus = curriedSum (2) _
TwoPlus: Int = > Int =
Scala > twoPlus (2)
Res3: Int = 4