0
 scala> def sum(a:Int)(b:Int) = a+b; sum: (a: Int)(b: Int)Int scala> var psum = sum(5)_ psum: Int => Int = $$Lambda$1035/814753967@724c5cbe scala> psum(23) res0: Int = 28 

The above snippet works fine but not sure why the below snippet complains.I am assuming that if I put underscore for an argument,I can curry that function

 scala> def sum(a:Int)(b:Int)(c:Int) = a + b + c; sum: (a: Int)(b: Int)(c: Int)Int scala> var psum = sum(5)_(23) 
0

4 Answers 4

1

You hit on an ambiguity/limitation of the parser. You can work around it by adding parenthesis

val psum = (sum(5)_)(23) 
Sign up to request clarification or add additional context in comments.

4 Comments

Your answer is incorrect as I demonstrate here: def sum(a:Int)(b:Int)(c:Int) = s"a: $a, b: $b, c: $c"; val psum = (sum(5)_)(23); psum(50) == "a: 5, b: 23, c: 50"
Also, do you realize it only gives the same answer because "+" is commutative right? It has little to do with order or function application.
yep, it looks wrong now that I take a look at it. Fixing it, thanks!
I thought the OP still wanted to partially apply the first two params, if that's not the case, @Alexey answer looks spot on.
1

What you need for this case is val psum = sum(5)(_: Int)(23). (sum(3)_)(2) is calculated as follows: sum(3)_ is the same as (b: Int) => (c: Int) => sum(3)(b)(c) and applying it to 2 gives (c: Int) => sum(3)(2)(c).

1 Comment

Oh, nice observation!
0

If I'm not mistaken, you are looking for partially applied arguments in a function and not for currying. You would have to do it this way:

def sum(a:Int,b:Int,c:Int) = a * b + c sum: (a: Int, b: Int, c: Int)Int sum(10, _:Int, 1) res1: Int => Int = $$Lambda$1131/1517266286@1981d861 res1 (2) res13: Int = 21 

Comments

0

This is a limitation of the scala syntax. You can achieve the same semantics like this:

scala> def sum(a:Int)(b:Int)(c:Int) = s"a: $a, b: $b, c: $c" sum: (a: Int)(b: Int)(c: Int)String scala> def flip[A,B,C](f:A => B => C): B => A => C = b => a => f(a)(b) flip: [A, B, C](f: A => (B => C))B => (A => C) scala> flip(sum(5))(23) res1: Int => String = <function1> scala> res1(50) res2: String = a: 5, b: 50, c: 23 

Basically, flip switches the order of binary functions, so we can use it make the middle argument b be the last argument of flip(sum(5)).

(*) I took the liberty to make sum give as back a String, which abstracts out any properties that are not relevant to the order functions application, which I interpret as being the core of your question.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.