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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With