This curried function accepts a function of two arguments and converts it into a function of 1 argument :
def hotcurry[A, B, C](f: (A, B) => C): A => (B => C) =
a => b => f(a, b) //> hotcurry: [A, B, C](f: (A, B) => C)A => (B => C)
def f(a : Int , b : Int) = a + b //> f: (a: Int, b: Int)Int
hotcurry(f) //> res0: Int => (Int => Int) = <function1>
How can the return function res0: Int => (Int => Int) = <function1>
be evaulated ?
I've tried fu(2) //> res0: Int => Int = <function1>
What is a good use case for this function ?
Just pass the parameters one at a time:
val g: Int => (Int => Int) = (a: Int) => (b: Int) => a + b
g(3)(4)
// res4: Int = 7
g
takes an Int
, and returns a function Int => Int
. That function then takes an Int
and returns an Int
. So you pass a parameter to the first function, and then pass one to the function that's returned.
In your case, just do:
val g = hotcurry(f)
g(3)(4)
You can use it if you have a two parameter function that you want to use later as a one parameter function, packing one parameter in ahead of time. For instance, map
takes a parameter Int => Int
, so you could do something like:
val add = hotcurry(f)
val add3 = add(3)
Vector(1, 2, 3).map(add3)
// Vector(4, 5, 6)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments