Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate curried function

Tags:

scala

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 ?

like image 708
blue-sky Avatar asked Sep 01 '26 17:09

blue-sky


1 Answers

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)
like image 158
dhg Avatar answered Sep 04 '26 14:09

dhg