This language bar is your friend. Select your favorite languages!

Idiom #37 Currying

Technique of transforming a function that takes multiple arguments and returning a function for which some of the arguments are preset.

adder = -> a, b { a + b }
add_two = adder.curry.(2)
add_two.(5) # => 7
import std.functional;
int add(int n1, int n2)
{
    return n1 + n2;
}

alias add5 = curry!(add, 5);
	
curry(f(a, b), a) => (b) => f(a, b);
defmodule Curry do

  def curry(fun) do
    {_, arity} = :erlang.fun_info(fun, :arity)
    curry(fun, arity, [])
  end

  def curry(fun, 0, arguments) do
    apply(fun, Enum.reverse arguments)
  end

  def curry(fun, arity, arguments) do
    fn arg -> curry(fun, arity - 1, [arg | arguments]) end
  end

end
type PayFactory func(Company, *Employee, *Employee) Payroll

type CustomPayFactory func(*Employee) Payroll

func CurryPayFactory(pf PayFactory,company Company, boss *Employee) CustomPayFactory {
	return func(e *Employee) Payroll {
		return pf("Richissim", boss, e)
	}
}
(curry range 1)
function curry (fn, scope) {
   
    scope = scope || window;
    
    // omit curry function first arguments fn and scope
    var args = Array.prototype.slice.call(arguments, 2);
    
    return function() {
	var trueArgs = args.concat(Array.prototype.slice.call(arguments, 0));
        fn.apply(scope, trueArgs);
    };
}
import java.util.function.*;
IntBinaryOperator simpleAdd = (a, b) -> a + b;
IntFunction<IntUnaryOperator> curriedAdd = a -> b -> a + b;
System.out.println(simpleAdd.applyAsInt(4, 5));
System.out.println(curriedAdd.apply(4).applyAsInt(5));
function curry2(f)
   return function(a)
      return function(b)
         return f(a,b)
      end
   end
end

function add(a,b)
   return a + b
end

local curryAdd = curry2(add)
local add2 = curryAdd(2)
sub curry {
   my ($func, $fixed_arg) = @_;
   return sub {
      $func->($fixed_arg, @_);
   }
}
from functools import partial
def f(a):
	def add(b):
		return a+b
	return add

print (f(2)(1)

#add_to_two = partial(f, 2)
(define add5 (curry + 5))

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

Adrian