Logo

Programming-Idioms

  • Pascal
  • VB
  • Lua
  • Java
  • Erlang
  • Rust

Idiom #37 Currying

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

fn add(a: u32, b: u32) -> u32 {
    a + b
}

let add5 = move |x| add(5, x);
 
local unpack = unpack or table.unpack
local function aux_ncurry(n, m, fn, args)
  if m>n then return fn(unpack(args,1,n))end
  local new_args, new_m = {}, m
  for i=1,m-1 do new_args[i]=args[i]end
  return function(a) 
    new_args[new_m]=a
    return aux_ncurry(n, new_m + 1, fn, new_args)
  end
end
local function ncurry(n, fn) return aux_ncurry(n,1,fn,{}) end
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)
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));
(def rev-key #(update %2 %1 reverse))

(def rev-a (partial rev-key :a))

New implementation...
< >
Adrian