0

General Form

The general form of a function with multiple parameter lists is as follows:

In the illustration above, n>1.

The above function is equivalent to the following:

The function f is taking the first n-1 lists of parameters and creating a new function h which takes the nth list of parameters. h then maps the nth list of parameters to the function body Exp with h being the function that gets returned.

The above, can also be written using anonymous functions as follows.

The above function can be further expanded:

If we do this n times, we would get the following:

An Example

We will expand the curriedSum function created in a previous lesson to better understand the general sequence of expansion explained above.

Just as a reminder. here is the curriedSum function:

1

def curriedSum(x: Int)(y: Int) = x + y

Let’s start expanding!

In the first expansion CurriedSum is now a function which takes a single parameter of type Int and returns a function.

In conclusion, curriedSum is a combination of two nested function calls. As mentioned in a previous lesson, the first function call takes a single parameter of type Int and returns a function value which will be used by the second function (the function returned by the first function is the second function). The second function, in turn, takes a parameter y of type Int and returns the sum of x and y.

Let’s try to implement both functions. The first function will be known as first and the second function will be known as second.

For our example, x = 3 and y = 2.

Source: Grepper

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.

Grepper Account Login Required