Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to curry a function in Scala

I'm trying to call a 2 parameters function in List.foreach, with the first parameter fixed for a loop. In fact I want to curry a function of two parameters into a function of one parameter which returns a function of one parameter (as List.foldLeft do)

This does not work:

private def mathFunc1(a: Double, b: Double) =
    println(a + b)


def eval(v: Double) = {
    List(1.0, 2.0, 3.0).foreach(mathFunc1(2.1))
}

This works:

private def mathFunc2(a: Double)(b: Double) =
    println(a + b)


def eval(v: Double) = {
    List(1.0, 2.0, 3.0).foreach(mathFunc2(2.1))
}

But I don't want to change the signature of mathFunc1, so I want to do something like:

private def mathFunc1(a: Double, b: Double) =
    println(a + b)


def eval(v: Double) = {
    List(1.0, 2.0, 3.0).foreach(CONVERT_TWO_PARAMS_TO_ONE_ONE(mathFunc1)(2.1))
}
like image 747
Maxime Avatar asked Sep 18 '09 23:09

Maxime


People also ask

What is function currying 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.

How do you define a function in Scala?

In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function. You can create function by using def keyword. You must mention return type of parameters while defining function and return type of a function is optional.

What does => mean in Scala?

=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).


1 Answers

private def mathFunc1(a: Double, b: Double) =
    println(a + b)


def eval(v: Double) = {
    List(1.0, 2.0, 3.0).foreach(mathFunc1(2.1, _))
}

Underline, the Scala wildcard!

As a minor curiosity, this will also work:

def eval(v: Double) = {
    List(1.0, 2.0, 3.0).foreach(Function.curried(mathFunc1 _)(2.1))
}

Or even:

val curriedMathFunc1 = Function.curried(mathFunc1 _)
def eval(v: Double) = {
    List(1.0, 2.0, 3.0).foreach(curriedMathFunc1(2.1))
}
like image 156
Daniel C. Sobral Avatar answered Oct 19 '22 22:10

Daniel C. Sobral