Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create curried anonymous function in scala?

How can I create an anonymous and curried function in Scala? The following two failed:

scala> (x:Int)(y:Int) => x*y
<console>:1: error: not a legal formal parameter
       (x:Int)(y:Int) => x*y
              ^

scala> ((x:Int)(y:Int)) => x*y
<console>:1: error: not a legal formal parameter
       ((x:Int)(y:Int)) => x*y
               ^
like image 873
Niket Kumar Avatar asked Jun 15 '12 10:06

Niket Kumar


People also ask

What is curried function in Scala?

Currying is the process of converting a function with multiple arguments into a sequence of functions that take one argument. Each function returns another function that consumes the following argument.

What is anonymous function in Scala?

In Scala, An anonymous function is also known as a literal function. A function that does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.

What is the difference between method and function in Scala?

A function doesn't need any object and is independent, while the method is a function, which is linked with any object. We can directly call the function with its name, while the method is called by the object's name. Function is used to pass or return the data, while the method operates the data in a class.

What is the currying function in Javascript?

It is a technique in functional programming, transformation of the function of multiple arguments into several functions of a single argument in sequence. The translation of function happens something like this, function simpleFunction(param1, param2, param3, …..)


1 Answers

To create a curried function write it as if it were multiple functions (that's actually the case ;-) ).

scala> (x: Int) => (y: Int) => x*y
res2: Int => Int => Int = <function1>

This means you have a function from Int to a function from Int to Int.

scala> res2(3)
res3: Int => Int = <function1>

alternatively you can write it like this:

scala> val f: Int => Int => Int = x => y => x*y
f: Int => Int => Int = <function1>
like image 51
drexin Avatar answered Sep 28 '22 07:09

drexin