sof
sof

Reputation: 9649

How to define function accepting curried function parameter?

Below fn2 failed to compile,

def fn(x: Int)(y: Int) = x + y
def fn2(f: ((Int)(Int)) => Int) = f
fn2(fn)(1)(2) // expected = 3

How to define fn2 to accept fn?

Upvotes: 4

Views: 191

Answers (1)

dk14
dk14

Reputation: 22374

It should be as follows:

scala> def fn2(f: Int => Int => Int) = f
fn2: (f: Int => (Int => Int))Int => (Int => Int)

scala> fn2(fn)(1)(2)
res5: Int = 3

(Int)(Int) => Int is incorrect - you should use Int => Int => Int (like in Haskell), instead. Actually, the curried function takes Int and returns Int => Int function.

P.S. You could also use fn2(fn _)(1)(2), as passing fn in previous example is just a short form of eta-expansion, see The differences between underscore usage in these scala's methods.

Upvotes: 11

Related Questions