namespace Func =

  function id(x : 'a) : 'a = x

  function const(x : 'a) : 'b => 'a = (y) => x

  function flip(f : ('a, 'b) => 'c) : ('b, 'a) => 'c = (b, a) => f(a, b)

  function comp(f : 'b => 'c, g : 'a => 'b) : 'a => 'c = (x) => f(g(x))

  function pipe(f : 'a => 'b, g : 'b => 'c) : 'a => 'c = (x) => g(f(x))

  function rapply(x : 'a, f : 'a => 'b) : 'b = f(x)

  /* The Z combinator - replacement for local and anonymous recursion.
   */
  function recur(f : ('arg => 'res, 'arg) => 'res) : 'arg => 'res =
    (x) => f(recur(f), x)

  function iter(n : int, f : 'a => 'a) : 'a => 'a = iter_(n, f, (x) => x)
  private function iter_(n : int, f : 'a => 'a, acc : 'a => 'a) : 'a => 'a =
    if(n == 0) acc
    elif(n == 1) comp(f, acc)
    else iter_(n / 2, comp(f, f), if(n mod 2 == 0) acc else comp(f, acc))

  function curry2(f : ('a, 'b) => 'c) : 'a => ('b => 'c) =
    (x) => (y) => f(x, y)
  function curry3(f : ('a, 'b, 'c) => 'd) : 'a => ('b => ('c => 'd)) =
    (x) => (y) => (z) => f(x, y, z)

  function uncurry2(f : 'a => ('b => 'c)) : ('a, 'b) => 'c =
    (x, y) => f(x)(y)
  function uncurry3(f : 'a => ('b => ('c => 'd))) : ('a, 'b, 'c) => 'd =
    (x, y, z) => f(x)(y)(z)

  function tuplify2(f : ('a, 'b) => 'c) : (('a * 'b)) => 'c =
    (t) => switch(t)
      (x, y) => f(x, y)
  function tuplify3(f : ('a, 'b, 'c) => 'd) : 'a * 'b * 'c => 'd =
    (t) => switch(t)
      (x, y, z) => f(x, y, z)

  function untuplify2(f : 'a * 'b => 'c) : ('a, 'b) => 'c =
    (x, y) => f((x, y))
  function untuplify3(f : 'a * 'b * 'c => 'd) : ('a, 'b, 'c) => 'd =
    (x, y, z) => f((x, y, z))
