Currying
Function
Currying in Scala is simply a technique or a process of
transforming a function. This function takes multiple arguments into a function
that takes single argument. It is applied widely in multiple functional
languages.
Syntax
def function name(argument1, argument2) = operation
Example:
object Curry
{
// Define
currying function
def
multiply(x: Int, y: Int) = x * y;
def
main(args: Array[String])
{
println(multiply(20, 19));
}
}
//Output
380
Another way to declare currying function
we have to transform this add function into a Curried
function, that is transforming the function that takes two(multiple) arguments
into a function that takes one(single) argument.
Syntax
def function name(argument1) = (argument2) =>
operation
Example:
object Curry
{
//
transforming the function that takes two(multiple) arguments into a function
that takes one(single) argument.
def
multiply(a: Int) = (b: Int) => a * b;
// Main
method
def
main(args: Array[String])
{
println(multiply(20)(19));
}
}
//Output
380
Currying Function Using Partial Application
We have another way to use this Curried function and
that is Partially Applied function. So, let’s take a simple example and
understand. we have defined a variable sum in the main function
Example:
object Curry
{
def
multiply(a: Int) = (b: Int) => a * b;
// Main
function
def
main(args: Array[String])
{
//
Partially Applied function.
val mult
= multiply(29);
//val
mult=multiply(29)_;
println(mult(5));
}
}
//Output
145
Also, another way(syntax) to write the currying
function.
Syntax
def function name(argument1) (argument2) = operation
Example:
object Curry
{
// Curring
function declaration
def
multiply(a: Int) (b: Int) = a * b;
def
main(args: Array[String])
{
println(multiply(29)(5));
}
}
//Output
145
No comments:
Post a Comment