Maxime
Maxime

Reputation: 2078

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))
}

Upvotes: 12

Views: 2457

Answers (1)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297195

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))
}

Upvotes: 18

Related Questions