Skip to main content

Curry Function

Functional Programming4 functions

Utility Overview

Details

Transforms functions to enable partial application, converting multi-argument functions into sequences of single-argument functions

Category:Functional Programming
Functions:curry, autoCurry, curry2, curry3
Concepts:
closureshigher-order functionsfunctional programmingpartial application

Implementation

curry

Time: O(1) | Space: O(n)
export function curry<T extends (...args: unknown[]) => unknown>(fn: T): T {
  const arity = fn.length;
  
  function curried(...args: unknown[]): unknown {
    if (args.length >= arity) {
      return fn(...args);
    }
    return (...nextArgs: unknown[]) => curried(...args, ...nextArgs);
  }
  
  return curried as T;
}

// Auto-curry with flexible arity

Usage Examples

Basic function currying

const add = (a: number, b: number) => a + b;
const curriedAdd = curry(add);

// All equivalent calls:
curriedAdd(1)(2);        // 3
curriedAdd(1, 2);        // 3

// Partial application:
const addOne = curriedAdd(1);
addOne(2);               // 3

Multi-argument function currying

const multiply = (a: number, b: number, c: number) => a * b * c;
const curriedMultiply = autoCurry(multiply);

// Flexible partial application:
const double = curriedMultiply(2);
const doubleTriple = double(3);
doubleTriple(4);         // 24

// Or all at once:
curriedMultiply(2)(3)(4); // 24

Functional programming patterns

const map = <T, U>(fn: (item: T) => U, array: T[]) => array.map(fn);
const curriedMap = curry2(map);

const double = (x: number) => x * 2;
const mapDouble = curriedMap(double);

mapDouble([1, 2, 3]);    // [2, 4, 6]
mapDouble([4, 5, 6]);    // [8, 10, 12]

// Compose with other functions:
const numbers = [1, 2, 3, 4, 5];
const doubledEvens = numbers
  .filter(x => x % 2 === 0)
  .map(double);            // Uses curried function

Ā© 2025 John Dilig. Built with Next.js & TypeScript. Open Source (MIT) • Wiki

v... • Auto-versioned