4

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?

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
sof
  • 9,113
  • 16
  • 57
  • 83

1 Answers1

11

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.

Community
  • 1
  • 1
dk14
  • 22,206
  • 4
  • 51
  • 88