Search code examples
scalafunctional-programming

Scala: from f(x1, ... xn) create x1 => f(x2, ..., xn)


If we restrict it to the case of three parameters, I want to get from this

val f = (x: Int, y: Int, z: Int) => x + y + z

to this:

val g = (x: Int) => { (y: Int, z: Int) => f(x, y, z) }

I don't even know how that operation is called, presumably "curry the first parameter"?

Does Scala have utility function for this operation, or is writing it out like above the only way to achieve it?


Solution

  • Out of the box, there is only .curried which curries all arguments:

    val f = (x: Int, y: Int, z: Int) => x + y + z
    
    f.curried // Int => Int => Int => Int
    

    However, you could use _ syntax to make your code slightly shorter:

    (x: Int) => f(x, _, _) // Int => (Int, Int) => Int
    

    If you really need to use it often, you could implement some extension methods yourself

    // Scala 2
    implicit class Function3CurryFirstOps[A, B, C, D](private val f: (A, B, C) => D) extends AnyVal {
      def curriedFirst: A => (B => C) => D = (a: A) => f(a, _, _)
    }
    
    // Scala 3
    extension [A, B, C, D](f: (A, B, C) => D)
      def curriedFirst: A => (B => C) => D = (a: A) => f(a, _, _)