Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - understanding a code snippet involving currying

Tags:

scala

I'm new to scala and I'm having a little trouble understanding currying - I'm practicing by coding simple functions for now, and would need clarification about the following

 def mul (a: Int) (b: Int): Int =
  {
  {
  a * b
  }
  } 

Is the above function definition same as the below?

def mul: Int => Int => Int = {
  (a: Int) =>
    {
      (b: Int) =>
        a * b
    }
}

From syntax I could interpret mul as a function that accepts an integer, and returns a function that accepts an integer and returns an integer. But I'm not sure if my interpretation is actually correct. Any explanation regarding the above example or the syntax of curried functions will be really helpful.

like image 372
Raj Avatar asked Dec 26 '22 17:12

Raj


1 Answers

Your interpretation is correct. But you don't need all those braces.

def mul(a: Int)(b: Int) = a*b

val mulAB = (a: Int) => { (b: Int) => a*b }   // Same as mul _
val mul5B = (b: Int) => 5*b                   // Same as mulAb(5) or mul(5) _

In general, you can rewrite any function with multiple arguments as a curried chain instead, where each argument produces a function that takes one fewer arguments until the last one actually produces the value:

f(a: A ,b: B ,c: C, d: D): E  <===>  A => B => C => D => E

In Scala, the natural grouping is by parameter block, not by individual parameter, so

f(a: A)(b: B, c: C)(d: D): E  <===>  A => (B,C) => D => E
like image 162
Rex Kerr Avatar answered Jan 05 '23 01:01

Rex Kerr