Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define function accepting curried function parameter?

Tags:

scala

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?

like image 412
sof Avatar asked Dec 20 '22 10:12

sof


1 Answers

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.

like image 75
dk14 Avatar answered Dec 21 '22 22:12

dk14