Scala - understanding a piece of code using currying

I am new to scala and I have a little problem understanding currying. At the moment I am programming simple functions and need clarification of the following

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

Is the above definition of a function the same as below?

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

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

+4
source share
1 answer

Your interpretation is correct. But you do not need all these curly 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 the general case, you can rewrite any function with several arguments in the form of a carded chain, where each argument creates a function that takes another argument until the last one really gives a value:

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

In Scala, natural grouping is done by a parameter block, not a separate parameter, so

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

Source: https://habr.com/ru/post/1436578/


All Articles