Currying in Scala

Currying is a technique in functional programming that involves transforming a function with multiple arguments into a sequence of functions, each taking a single argument. In Scala, currying is supported natively, and can be used to create more expressive and flexible code.

In Scala, you can curry a function by defining it as a series of nested functions, each taking a single argument. For example, consider the following function that takes two arguments and returns their sum:

scala
def add(x: Int, y: Int): Int = x + y

To curry this function, you can define it as a series of nested functions, each taking a single argument:

scala
def add(x: Int)(y: Int): Int = x + y

In this example, the `add()` function is defined with two parameter lists, separated by parentheses. The first parameter list takes a single argument `x` of type `Int`, and returns a new function that takes a single argument `y` of type `Int`. The second function then adds `x` and `y` together and returns the result.

You can now use the curried function `add()` to add two integers as follows:

scala
val result = add(2)(3) // returns 5

In this example, the `add()` function is called with two input parameters: `2` and `3`. The first parameter `2` is passed to the first parameter list,which returns a new function that takes a single argument `y`. The second parameter `3` is then passed to the second function, which adds it to `2` and returns the result `5`.

One advantage of currying is that it allows you to create partially applied functions, which are functions that have some, but not all, of their arguments applied. For example, you can create a partially applied function that fixes the first argument of `add()` as follows:

scala
val add2 = add(2) _

In this example, the underscore `_` is used to represent the second argument of the `add()` function, which has not yet been specified. The resulting function `add2` takes a single argument, and returns the result of adding `2` to that argument.

You can now use the partially applied function `add2` to add `2` to any integer value as follows:

scala
val result = add2(3) // returns 5

In this example, the `add2` function is called with a single input parameter of value `3`, which is passed as the second argument to the `add()` function. The result is `5`, which is the sum of `2` and `3`.

Overall, currying is a powerful technique in functional programming that allows for more expressive and flexible code, particularly when combined with higher-order functions and partially applied functions.