简体   繁体   中英

Scala - understanding a code snippet involving currying

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM