Programming Search⌘K

Taskcore

Compose functions

Also called function composition, compose helper, combine functions, chain functions, compose many functions.

Write a generic compose helper that takes any number of functions and returns one function, where the last function runs first, and use it to compose functions that are chosen by name.

Task

Write a generic helper compose(f1, f2, ..., fn). It takes any number of functions from a type to the same type, and it returns one function. The returned function applies the functions from the last to the first, as in mathematics: compose(f, g)(x) is f(g(x)). With no functions, compose() is the identity function.

Then use the helper with four functions on integers, chosen by name:

Name The function
inc x + 1
dec x - 1
double 2 * x
negate -x

The entry function compose_all(ops, x) composes the functions that ops names, in the order of ops, and applies the result to x. So compose_all(["inc", "double"], 3) is inc(double(3)), which is 7, and compose_all(["double", "inc"], 3) is 8. ops has 0 to 20 names and x is from -1000 to 1000, so each result fits in a 32-bit signed integer.

"In computer science, function composition is an act or mechanism to combine simple functions to build more complex ones."1 The two-function form is the subject of Function composition. A helper that takes a list of functions is a fold over the list: it starts from the identity function and composes one function at a time. Map, filter and reduce explains the fold, and Write a higher-order function is the task for one function that takes and returns a function.

Solutions

Language The compose helper How it combines the functions
Python compose(*functions) functools.reduce with the identity function as the start
JavaScript compose(...fs) reduceRight over the functions
TypeScript compose<T>(...fs: Array<(x: T) => T>) reduceRight over the functions
Java <T> Function<T, T> compose(List<Function<T, T>> fs) Stream.reduce from Function.identity() with Function.compose
C# Func<T, T> Compose<T>(params Func<T, T>[] fs) Aggregate from the identity lambda
C apply_composed(fs, n, x) a loop from the last pointer to the first
C++ template <typename T> std::function<T(T)> compose(std::vector<std::function<T(T)>> fs) a lambda with a reverse loop
Go func Compose[T any](fs ...func(T) T) func(T) T a function literal with a reverse loop
Rust fn compose<T>(fs: Vec<Box<dyn Fn(T) -> T>>) -> impl Fn(T) -> T iter().rev().fold(...) in a move closure
Bash compose_all X NAME... a loop from the last name to the first
  • Python. functools.reduce does the fold. It applies a "function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value."2 The function of two arguments is lambda f, g: lambda x: f(g(x)), the same as in the Wikipedia example1. The solution gives the identity function as the third argument, because "If the optional initial is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty."2
  • JavaScript. "The reduceRight() method of Array instances applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value."3 The accumulator is the value, not a function, so the helper starts with x and applies the last function first. Wikipedia gives the same one-line helper1.
  • TypeScript. The helper has a type parameter T, because "It’s common to write a function where the types of the input relate to the type of the output"4. Each function takes a T and gives a T.
  • Java. Function has two methods that compose. compose "Returns a composed function that first applies the before function to its input, and then applies this function to the result."5 andThen "Returns a composed function that first applies this function to its input, and then applies the after function to the result."5 The helper uses compose, and it starts from Function.identity(), which "Returns a function that always returns its input argument."5
  • C#. Aggregate "Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value."6 The seed is the identity lambda x => x, and the accumulator function is (f, g) => x => f(g(x)).
  • C. "A pointer to function can be used on the left-hand side of the function call operator; this invokes the pointed-to function"7, so an array of pointers can hold the functions. C cannot make a new function at run time, because "There are no nested functions"8. So the helper apply_composed takes the array and the value, and it calls the functions from the last to the first.
  • C++. "Class template std::function is a general-purpose polymorphic function wrapper."9 The helper is a template that takes a vector of std::function<T(T)> and returns a lambda that owns the vector.
  • Go. "A type parameter list declares the type parameters of a generic function, method, or type declaration."10 Compose[T any] takes a variadic list of func(T) T. "Function literals are closures"10, so the returned function keeps the list.
  • Rust. Each closure has its own type, so a list of different closures needs a trait object. The Rust book uses "a Vec of closures defined by functions that return Box so that they have the same type"11. The returned closure calls rev, which "Reverses an iterator’s direction."12, and fold, which "Folds every element into an accumulator by applying an operation, returning the final result."12
  • Bash. A function is a name for a group of commands13, not a value. compose_all takes the names, puts them in an array, and calls them from the last to the first. Each call prints its result, and the loop reads it with $( ).

Compose and andThen

In Java, f.compose(g) runs g first, and f.andThen(g) runs f first5:

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> inc = x -> x + 1;
        Function<Integer, Integer> twice = x -> 2 * x;
        System.out.println(inc.compose(twice).apply(3));
        System.out.println(inc.andThen(twice).apply(3));
    }
}
Output
7
8

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: no names give the identity function, so the result is x.
  • single-zero: one function. negate of 0 is 0.
  • inc-after-double and double-after-inc: the same two names in the two orders give 7 and 8.
  • negative and low: negative values. dec then negate on -5 gives 4.
  • duplicates: the same name three times applies the function three times.
  • limit-high and limit-low: 20 times double on 1000 and on -1000 give 1048576000 and -1048576000, which fit in 32 bits.
  • mixed-20 and mixed-20-swapped: 20 names that alternate, in the two orders.

Pitfalls

reduce with no start value

Wikipedia's Python example calls reduce with no initial value1. Then compose() with no functions fails, because there is no item to start from:

This code runs but gives a wrong answer on purpose.

from functools import reduce


def compose(*functions):
    return reduce(lambda f, g: lambda x: f(g(x)), functions)


def inc(x):
    return x + 1


def double(x):
    return 2 * x


print(compose(inc, double)(3))
try:
    print(compose()(3))
except TypeError as error:
    print(error)
Output
7
reduce() of empty iterable with no initial value

Give the identity function as the initial value, as the solution does. Then the empty case is the identity2.

A loop that reads the variable at call time

A loop can build the composition one function at a time. But a lambda reads a variable from the outer scope when it is called, not when it is made. The Python FAQ says that the variable "is accessed when the lambda is called — not when it is defined."14 Here g names the new lambda when it is called, so the lambda calls itself:

This code runs but gives a wrong answer on purpose.

def compose(*functions):
    g = lambda x: x
    for f in functions:
        g = lambda x: g(f(x))
    return g


def inc(x):
    return x + 1


def double(x):
    return 2 * x


try:
    print(compose(inc, double)(3))
except RecursionError as error:
    print(type(error).__name__, error)
Output
RecursionError maximum recursion depth exceeded

Bind the current values as default arguments, lambda x, g=g, f=f: g(f(x)), as the FAQ shows for its loop14, or use reduce.

reduce in place of reduceRight

reduceRight goes from right to left3. reduce goes from left to right, so with reduce the first function runs first:

This code runs but gives a wrong answer on purpose.

const compose = (...fs) => (x) => fs.reduce((acc, f) => f(acc), x);

const inc = (x) => x + 1;
const double = (x) => 2 * x;

console.log(compose(inc, double)(3));
Output
8

inc(double(3)) is 7. Use reduceRight, or call the helper pipe and say in its name that the first function runs first.

Code

The build runs the native tests of each language in a pinned toolchain.

compose.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compose-functions/.

from collections.abc import Callable
from functools import reduce


def identity[T](x: T) -> T:
    """Return x."""
    return x


def compose[T](*functions: Callable[[T], T]) -> Callable[[T], T]:
    """Return the composition of the functions. The last one runs first."""
    return reduce(lambda f, g: lambda x: f(g(x)), functions, identity)


OPS: dict[str, Callable[[int], int]] = {
    "inc": lambda x: x + 1,
    "dec": lambda x: x - 1,
    "double": lambda x: 2 * x,
    "negate": lambda x: -x,
}


def compose_all(ops: list[str], x: int) -> int:
    """Compose the functions that ops names and apply the result to x."""
    return compose(*(OPS[name] for name in ops))(x)
test_compose.py 36 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compose-functions/.

import pytest

from compose import compose, compose_all

CASES = {
    "inc-after-double": (["inc", "double"], 3, 7),
    "double-after-inc": (["double", "inc"], 3, 8),
    "three-functions": (["negate", "dec", "double"], 5, -9),
    "empty": ([], 42, 42),
    "single-zero": (["negate"], 0, 0),
    "negative": (["dec", "negate"], -5, 4),
    "low": (["inc"], -1000, -999),
    "duplicates": (["inc", "inc", "inc"], 7, 10),
    "limit-high": (["double"] * 20, 1000, 1048576000),
    "limit-low": (["double"] * 20, -1000, -1048576000),
    "mixed-20": (["double", "inc"] * 10, 1000, 1026046),
    "mixed-20-swapped": (["inc", "double"] * 10, 1000, 1025023),
}


@pytest.mark.parametrize("name", CASES)
def test_compose_all(name):
    ops, x, want = CASES[name]
    assert compose_all(ops, x) == want


def test_compose_is_generic():
    shout = compose(lambda s: s + "!", str.upper, str.strip)
    assert shout("  hello ") == "HELLO!"


def test_compose_of_nothing_is_identity():
    assert compose()("same") == "same"
compose.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

#include "compose.hpp"

#include <map>

namespace composition {

int compose_all(const std::vector<std::string>& ops, int x) {
    static const std::map<std::string, std::function<int(int)>> table = {
        {"inc", [](int v) { return v + 1; }},
        {"dec", [](int v) { return v - 1; }},
        {"double", [](int v) { return 2 * v; }},
        {"negate", [](int v) { return -v; }},
    };
    std::vector<std::function<int(int)>> fs;
    fs.reserve(ops.size());
    for (const auto& name : ops) {
        fs.push_back(table.at(name));
    }
    return compose(std::move(fs))(x);
}

}  // namespace composition
compose.hpp 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

#ifndef COMPOSE_HPP
#define COMPOSE_HPP

#include <functional>
#include <string>
#include <utility>
#include <vector>

namespace composition {

// Returns the composition of the functions. The last one runs first.
template <typename T>
std::function<T(T)> compose(std::vector<std::function<T(T)>> fs) {
    return [fs = std::move(fs)](T x) {
        for (auto it = fs.rbegin(); it != fs.rend(); ++it) {
            x = (*it)(std::move(x));
        }
        return x;
    };
}

// Composes the functions that ops names and applies the result to x.
int compose_all(const std::vector<std::string>& ops, int x);

}  // namespace composition

#endif
test_compose.cpp 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

#include <cstdio>
#include <string>
#include <vector>

#include "compose.hpp"

namespace {

std::vector<std::string> times(const std::vector<std::string>& names, int n) {
    std::vector<std::string> out;
    for (int i = 0; i < n; ++i) {
        out.insert(out.end(), names.begin(), names.end());
    }
    return out;
}

struct test_case {
    const char* name;
    std::vector<std::string> ops;
    int x, want;
};

}  // namespace

int main() {
    const std::vector<test_case> cases = {
        {"inc-after-double", {"inc", "double"}, 3, 7},
        {"double-after-inc", {"double", "inc"}, 3, 8},
        {"three-functions", {"negate", "dec", "double"}, 5, -9},
        {"empty", {}, 42, 42},
        {"single-zero", {"negate"}, 0, 0},
        {"negative", {"dec", "negate"}, -5, 4},
        {"low", {"inc"}, -1000, -999},
        {"duplicates", {"inc", "inc", "inc"}, 7, 10},
        {"limit-high", times({"double"}, 20), 1000, 1048576000},
        {"limit-low", times({"double"}, 20), -1000, -1048576000},
        {"mixed-20", times({"double", "inc"}, 10), 1000, 1026046},
        {"mixed-20-swapped", times({"inc", "double"}, 10), 1000, 1025023},
    };
    int failures = 0;
    for (const auto& c : cases) {
        const int got = composition::compose_all(c.ops, c.x);
        if (got != c.want) {
            std::printf("FAIL %s: got %d, want %d\n", c.name, got, c.want);
            ++failures;
        }
    }
    const auto shout = composition::compose<std::string>({
        [](std::string s) { return s + "!"; },
        [](std::string s) { return s + s; },
    });
    if (shout("ab") != "abab!") {
        std::printf("FAIL compose with strings\n");
        ++failures;
    }
    if (composition::compose<int>({})(5) != 5) {
        std::printf("FAIL compose of nothing\n");
        ++failures;
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Compose.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

import java.util.List;
import java.util.Map;
import java.util.function.Function;

/** A generic compose helper. */
public final class Compose {
    private Compose() {}

    private static final Map<String, Function<Integer, Integer>> OPS = Map.of(
            "inc", x -> x + 1,
            "dec", x -> x - 1,
            "double", x -> 2 * x,
            "negate", x -> -x);

    /** Returns the composition of the functions. The last one runs first. */
    public static <T> Function<T, T> compose(List<Function<T, T>> fs) {
        return fs.stream().reduce(Function.identity(), (f, g) -> f.compose(g));
    }

    /** Composes the functions that ops names and applies the result to x. */
    public static int composeAll(List<String> ops, int x) {
        return compose(ops.stream().map(OPS::get).toList()).apply(x);
    }
}
ComposeTest.java 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ComposeTest {
    static List<String> times(List<String> names, int n) {
        List<String> out = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            out.addAll(names);
        }
        return out;
    }

    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("inc-after-double", List.of("inc", "double"), 3, 7),
                Arguments.of("double-after-inc", List.of("double", "inc"), 3, 8),
                Arguments.of("three-functions", List.of("negate", "dec", "double"), 5, -9),
                Arguments.of("empty", List.of(), 42, 42),
                Arguments.of("single-zero", List.of("negate"), 0, 0),
                Arguments.of("negative", List.of("dec", "negate"), -5, 4),
                Arguments.of("low", List.of("inc"), -1000, -999),
                Arguments.of("duplicates", List.of("inc", "inc", "inc"), 7, 10),
                Arguments.of("limit-high", times(List.of("double"), 20), 1000, 1048576000),
                Arguments.of("limit-low", times(List.of("double"), 20), -1000, -1048576000),
                Arguments.of("mixed-20", times(List.of("double", "inc"), 10), 1000, 1026046),
                Arguments.of("mixed-20-swapped", times(List.of("inc", "double"), 10), 1000, 1025023)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void composeAll(String name, List<String> ops, int x, int want) {
        assertEquals(want, Compose.composeAll(ops, x));
    }

    @Test
    void composeIsGeneric() {
        List<Function<String, String>> fs = List.of(s -> s + "!", String::toUpperCase, String::strip);
        assertEquals("HELLO!", Compose.compose(fs).apply("  hello "));
    }

    @Test
    void composeOfNothingIsTheIdentity() {
        assertEquals("same", Compose.<String>compose(List.of()).apply("same"));
    }
}
compose.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

#include "compose.h"

#include <string.h>

static int inc(int x) { return x + 1; }
static int dec(int x) { return x - 1; }
static int twice(int x) { return 2 * x; }
static int negate(int x) { return -x; }

int apply_composed(const int_fn fs[], size_t n, int x) {
    for (size_t i = n; i > 0; i--) {
        x = fs[i - 1](x);
    }
    return x;
}

int_fn op_by_name(const char *name) {
    if (strcmp(name, "inc") == 0) {
        return inc;
    }
    if (strcmp(name, "dec") == 0) {
        return dec;
    }
    if (strcmp(name, "double") == 0) {
        return twice;
    }
    if (strcmp(name, "negate") == 0) {
        return negate;
    }
    return NULL;
}

int compose_all(const char *const ops[], size_t n, int x) {
    int_fn fs[COMPOSE_MAX];
    for (size_t i = 0; i < n; i++) {
        fs[i] = op_by_name(ops[i]);
    }
    return apply_composed(fs, n, x);
}
compose.h 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

#ifndef COMPOSE_H
#define COMPOSE_H

#include <stddef.h>

// A pointer to a function from one int to one int.
typedef int (*int_fn)(int);

// The largest number of names that compose_all takes.
#define COMPOSE_MAX 20

// Applies the n functions in fs to x, from the last to the first. C cannot
// make a new function at run time, so the helper takes the value too.
int apply_composed(const int_fn fs[], size_t n, int x);

// Returns the function that name names, or NULL for an unknown name.
int_fn op_by_name(const char *name);

// Composes the functions that the n names in ops name and applies the
// result to x. n is at most COMPOSE_MAX.
int compose_all(const char *const ops[], size_t n, int x);

#endif
test_compose.c 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

#include "compose.h"

#include <stdio.h>
#include <stdlib.h>

#define D5 "double", "double", "double", "double", "double"
#define D20 D5, D5, D5, D5
#define DI5 "double", "inc", "double", "inc", "double", "inc", "double", "inc", "double", "inc"
#define ID5 "inc", "double", "inc", "double", "inc", "double", "inc", "double", "inc", "double"

struct test_case {
    const char *name;
    const char *ops[COMPOSE_MAX];
    size_t n;
    int x, want;
};

static const struct test_case cases[] = {
    {"inc-after-double", {"inc", "double"}, 2, 3, 7},
    {"double-after-inc", {"double", "inc"}, 2, 3, 8},
    {"three-functions", {"negate", "dec", "double"}, 3, 5, -9},
    {"empty", {NULL}, 0, 42, 42},
    {"single-zero", {"negate"}, 1, 0, 0},
    {"negative", {"dec", "negate"}, 2, -5, 4},
    {"low", {"inc"}, 1, -1000, -999},
    {"duplicates", {"inc", "inc", "inc"}, 3, 7, 10},
    {"limit-high", {D20}, 20, 1000, 1048576000},
    {"limit-low", {D20}, 20, -1000, -1048576000},
    {"mixed-20", {DI5, DI5}, 20, 1000, 1026046},
    {"mixed-20-swapped", {ID5, ID5}, 20, 1000, 1025023},
};

static int square(int x) {
    return x * x;
}

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int got = compose_all(c->ops, c->n, c->x);
        if (got != c->want) {
            printf("FAIL %s: got %d, want %d\n", c->name, got, c->want);
            failures++;
        }
    }
    const int_fn fs[] = {square, op_by_name("inc")};
    int got = apply_composed(fs, 2, 4);
    if (got != 25) {
        printf("FAIL square after inc: got %d, want 25\n", got);
        failures++;
    }
    if (op_by_name("halve") != NULL) {
        printf("FAIL an unknown name gives a function\n");
        failures++;
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Composition.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>A generic compose helper.</summary>
public static class Composition
{
    private static readonly Dictionary<string, Func<int, int>> Ops = new()
    {
        ["inc"] = x => x + 1,
        ["dec"] = x => x - 1,
        ["double"] = x => 2 * x,
        ["negate"] = x => -x,
    };

    /// <summary>Returns the composition of the functions. The last one runs first.</summary>
    public static Func<T, T> Compose<T>(params Func<T, T>[] fs)
    {
        return fs.Aggregate((Func<T, T>)(x => x), (f, g) => x => f(g(x)));
    }

    /// <summary>Composes the functions that ops names and applies the result to x.</summary>
    public static int ComposeAll(IReadOnlyList<string> ops, int x)
    {
        return Compose(ops.Select(name => Ops[name]).ToArray())(x);
    }
}
CompositionTests.cs 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

using System.Linq;
using Xunit;

public sealed class CompositionTests
{
    private static string[] Times(string[] names, int n) =>
        Enumerable.Repeat(names, n).SelectMany(x => x).ToArray();

    public static TheoryData<string, string[], int, int> Cases => new()
    {
        { "inc-after-double", new[] { "inc", "double" }, 3, 7 },
        { "double-after-inc", new[] { "double", "inc" }, 3, 8 },
        { "three-functions", new[] { "negate", "dec", "double" }, 5, -9 },
        { "empty", System.Array.Empty<string>(), 42, 42 },
        { "single-zero", new[] { "negate" }, 0, 0 },
        { "negative", new[] { "dec", "negate" }, -5, 4 },
        { "low", new[] { "inc" }, -1000, -999 },
        { "duplicates", new[] { "inc", "inc", "inc" }, 7, 10 },
        { "limit-high", Times(new[] { "double" }, 20), 1000, 1048576000 },
        { "limit-low", Times(new[] { "double" }, 20), -1000, -1048576000 },
        { "mixed-20", Times(new[] { "double", "inc" }, 10), 1000, 1026046 },
        { "mixed-20-swapped", Times(new[] { "inc", "double" }, 10), 1000, 1025023 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void ComposeAll(string name, string[] ops, int x, int want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Composition.ComposeAll(ops, x));
    }

    [Fact]
    public void ComposeIsGeneric()
    {
        var shout = Composition.Compose<string>(s => s + "!", s => s.ToUpperInvariant(), s => s.Trim());
        Assert.Equal("HELLO!", shout("  hello "));
    }

    [Fact]
    public void ComposeOfNothingIsTheIdentity()
    {
        Assert.Equal("same", Composition.Compose<string>()("same"));
    }
}
compose.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

/** Returns the composition of the functions. The last one runs first. */
export function compose(...fs) {
  return (x) => fs.reduceRight((acc, f) => f(acc), x);
}

const OPS = new Map([
  ["inc", (x) => x + 1],
  ["dec", (x) => x - 1],
  ["double", (x) => 2 * x],
  // 0 - x and not -x, so that negate(0) is 0 and not -0.
  ["negate", (x) => 0 - x],
]);

/** Composes the functions that ops names and applies the result to x. */
export function composeAll(ops, x) {
  return compose(...ops.map((name) => OPS.get(name)))(x);
}
compose.test.js 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { compose, composeAll } from "./compose.js";

const times = (names, n) => Array.from({ length: n }, () => names).flat();

const cases = [
  ["inc-after-double", ["inc", "double"], 3, 7],
  ["double-after-inc", ["double", "inc"], 3, 8],
  ["three-functions", ["negate", "dec", "double"], 5, -9],
  ["empty", [], 42, 42],
  ["single-zero", ["negate"], 0, 0],
  ["negative", ["dec", "negate"], -5, 4],
  ["low", ["inc"], -1000, -999],
  ["duplicates", ["inc", "inc", "inc"], 7, 10],
  ["limit-high", times(["double"], 20), 1000, 1048576000],
  ["limit-low", times(["double"], 20), -1000, -1048576000],
  ["mixed-20", times(["double", "inc"], 10), 1000, 1026046],
  ["mixed-20-swapped", times(["inc", "double"], 10), 1000, 1025023],
];

for (const [name, ops, x, want] of cases) {
  test(name, () => {
    assert.equal(composeAll(ops, x), want);
  });
}

test("compose is generic", () => {
  const shout = compose(
    (s) => s + "!",
    (s) => s.toUpperCase(),
    (s) => s.trim(),
  );
  assert.equal(shout("  hello "), "HELLO!");
});

test("compose of nothing is the identity", () => {
  assert.equal(compose()("same"), "same");
});
compose.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

/** Returns the composition of the functions. The last one runs first. */
export function compose<T>(...fs: Array<(x: T) => T>): (x: T) => T {
  return (x: T): T => fs.reduceRight((acc: T, f) => f(acc), x);
}

const OPS = new Map<string, (x: number) => number>([
  ["inc", (x) => x + 1],
  ["dec", (x) => x - 1],
  ["double", (x) => 2 * x],
  // 0 - x and not -x, so that negate(0) is 0 and not -0.
  ["negate", (x) => 0 - x],
]);

/** Composes the functions that ops names and applies the result to x. */
export function composeAll(ops: string[], x: number): number {
  const fs = ops.map((name) => {
    const f = OPS.get(name);
    if (f === undefined) {
      throw new Error(`unknown function: ${name}`);
    }
    return f;
  });
  return compose(...fs)(x);
}
compose.test.ts 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { compose, composeAll } from "./compose.ts";

const times = (names: string[], n: number): string[] =>
  Array.from({ length: n }, () => names).flat();

const cases: [string, string[], number, number][] = [
  ["inc-after-double", ["inc", "double"], 3, 7],
  ["double-after-inc", ["double", "inc"], 3, 8],
  ["three-functions", ["negate", "dec", "double"], 5, -9],
  ["empty", [], 42, 42],
  ["single-zero", ["negate"], 0, 0],
  ["negative", ["dec", "negate"], -5, 4],
  ["low", ["inc"], -1000, -999],
  ["duplicates", ["inc", "inc", "inc"], 7, 10],
  ["limit-high", times(["double"], 20), 1000, 1048576000],
  ["limit-low", times(["double"], 20), -1000, -1048576000],
  ["mixed-20", times(["double", "inc"], 10), 1000, 1026046],
  ["mixed-20-swapped", times(["inc", "double"], 10), 1000, 1025023],
];

for (const [name, ops, x, want] of cases) {
  test(name, () => {
    assert.equal(composeAll(ops, x), want);
  });
}

test("compose is generic", () => {
  const shout = compose(
    (s: string) => s + "!",
    (s: string) => s.toUpperCase(),
    (s: string) => s.trim(),
  );
  assert.equal(shout("  hello "), "HELLO!");
});

test("compose of nothing is the identity", () => {
  assert.equal(compose<string>()("same"), "same");
});
compose.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

// Package composition has a generic compose helper.
package composition

// Compose returns the composition of the functions. The last one runs first.
func Compose[T any](fs ...func(T) T) func(T) T {
	return func(x T) T {
		for i := len(fs) - 1; i >= 0; i-- {
			x = fs[i](x)
		}
		return x
	}
}

var ops = map[string]func(int) int{
	"inc":    func(x int) int { return x + 1 },
	"dec":    func(x int) int { return x - 1 },
	"double": func(x int) int { return 2 * x },
	"negate": func(x int) int { return -x },
}

// ComposeAll composes the functions that names names and applies the result to x.
func ComposeAll(names []string, x int) int {
	fs := make([]func(int) int, len(names))
	for i, name := range names {
		fs[i] = ops[name]
	}
	return Compose(fs...)(x)
}
compose_test.go 60 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

package composition

import (
	"strings"
	"testing"
)

func times(names []string, n int) []string {
	var out []string
	for i := 0; i < n; i++ {
		out = append(out, names...)
	}
	return out
}

var cases = []struct {
	name    string
	ops     []string
	x, want int
}{
	{"inc-after-double", []string{"inc", "double"}, 3, 7},
	{"double-after-inc", []string{"double", "inc"}, 3, 8},
	{"three-functions", []string{"negate", "dec", "double"}, 5, -9},
	{"empty", []string{}, 42, 42},
	{"single-zero", []string{"negate"}, 0, 0},
	{"negative", []string{"dec", "negate"}, -5, 4},
	{"low", []string{"inc"}, -1000, -999},
	{"duplicates", []string{"inc", "inc", "inc"}, 7, 10},
	{"limit-high", times([]string{"double"}, 20), 1000, 1048576000},
	{"limit-low", times([]string{"double"}, 20), -1000, -1048576000},
	{"mixed-20", times([]string{"double", "inc"}, 10), 1000, 1026046},
	{"mixed-20-swapped", times([]string{"inc", "double"}, 10), 1000, 1025023},
}

func TestComposeAll(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := ComposeAll(c.ops, c.x); got != c.want {
				t.Fatalf("got %d, want %d", got, c.want)
			}
		})
	}
}

func TestComposeIsGeneric(t *testing.T) {
	exclaim := func(s string) string { return s + "!" }
	shout := Compose(exclaim, strings.ToUpper, strings.TrimSpace)
	if got := shout("  hello "); got != "HELLO!" {
		t.Fatalf("got %q, want %q", got, "HELLO!")
	}
}

func TestComposeOfNothingIsTheIdentity(t *testing.T) {
	if got := Compose[string]()("same"); got != "same" {
		t.Fatalf("got %q, want %q", got, "same")
	}
}
compose.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

/// A boxed function from a type to the same type.
pub type Func<T> = Box<dyn Fn(T) -> T>;

/// Returns the composition of the functions. The last one runs first.
pub fn compose<T>(fs: Vec<Func<T>>) -> impl Fn(T) -> T {
    move |x| fs.iter().rev().fold(x, |acc, f| f(acc))
}

/// Returns the function that name names.
fn op(name: &str) -> Func<i32> {
    match name {
        "inc" => Box::new(|x: i32| x + 1),
        "dec" => Box::new(|x: i32| x - 1),
        "double" => Box::new(|x: i32| 2 * x),
        "negate" => Box::new(|x: i32| -x),
        _ => panic!("unknown function: {name}"),
    }
}

/// Composes the functions that ops names and applies the result to x.
pub fn compose_all(ops: &[&str], x: i32) -> i32 {
    compose(ops.iter().copied().map(op).collect())(x)
}
tests/compose_test.rs 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compose-functions/.

use algo_compose_functions::{compose, compose_all};

fn times<'a>(names: &[&'a str], n: usize) -> Vec<&'a str> {
    names.repeat(n)
}

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<&str>, i32, i32)> = vec![
        ("inc-after-double", vec!["inc", "double"], 3, 7),
        ("double-after-inc", vec!["double", "inc"], 3, 8),
        ("three-functions", vec!["negate", "dec", "double"], 5, -9),
        ("empty", vec![], 42, 42),
        ("single-zero", vec!["negate"], 0, 0),
        ("negative", vec!["dec", "negate"], -5, 4),
        ("low", vec!["inc"], -1000, -999),
        ("duplicates", vec!["inc", "inc", "inc"], 7, 10),
        ("limit-high", times(&["double"], 20), 1000, 1048576000),
        ("limit-low", times(&["double"], 20), -1000, -1048576000),
        ("mixed-20", times(&["double", "inc"], 10), 1000, 1026046),
        ("mixed-20-swapped", times(&["inc", "double"], 10), 1000, 1025023),
    ];
    for (name, ops, x, want) in cases {
        assert_eq!(compose_all(&ops, x), want, "{name}");
    }
}

#[test]
fn compose_is_generic() {
    let fs: Vec<algo_compose_functions::Func<String>> = vec![
        Box::new(|s: String| s + "!"),
        Box::new(|s: String| s.to_uppercase()),
        Box::new(|s: String| s.trim().to_string()),
    ];
    assert_eq!(compose(fs)("  hello ".to_string()), "HELLO!");
}

#[test]
fn compose_of_nothing_is_the_identity() {
    assert_eq!(compose::<i32>(Vec::new())(5), 5);
}
compose.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compose-functions/.

inc() { echo $(($1 + 1)); }
dec() { echo $(($1 - 1)); }
double() { echo $((2 * $1)); }
negate() { echo $((0 - $1)); }

# compose_all X NAME...
# Calls the functions that the names name, from the last to the first, on
# X, and prints the result. A Bash function is not a value, so the helper
# takes the names and the value, and it cannot return a new function.
compose_all() {
  local x=$1
  shift
  local -a fs=("$@")
  local i
  for ((i = ${#fs[@]} - 1; i >= 0; i--)); do
    x=$("${fs[i]}" "$x")
  done
  echo "$x"
}
test_compose.bats 31 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compose-functions/.

setup() {
  source "$BATS_TEST_DIRNAME/compose.sh"
}

times() {
  local n=$1 i
  shift
  for ((i = 0; i < n; i++)); do
    printf '%s\n' "$@"
  done
}

square() { echo $(($1 * $1)); }

@test "inc-after-double" { run compose_all 3 inc double; [ "$output" = "7" ]; }
@test "double-after-inc" { run compose_all 3 double inc; [ "$output" = "8" ]; }
@test "three-functions" { run compose_all 5 negate dec double; [ "$output" = "-9" ]; }
@test "empty" { run compose_all 42; [ "$output" = "42" ]; }
@test "single-zero" { run compose_all 0 negate; [ "$output" = "0" ]; }
@test "negative" { run compose_all -5 dec negate; [ "$output" = "4" ]; }
@test "low" { run compose_all -1000 inc; [ "$output" = "-999" ]; }
@test "duplicates" { run compose_all 7 inc inc inc; [ "$output" = "10" ]; }
@test "limit-high" { mapfile -t ops < <(times 20 double); run compose_all 1000 "${ops[@]}"; [ "$output" = "1048576000" ]; }
@test "limit-low" { mapfile -t ops < <(times 20 double); run compose_all -1000 "${ops[@]}"; [ "$output" = "-1048576000" ]; }
@test "mixed-20" { mapfile -t ops < <(times 10 double inc); run compose_all 1000 "${ops[@]}"; [ "$output" = "1026046" ]; }
@test "mixed-20-swapped" { mapfile -t ops < <(times 10 inc double); run compose_all 1000 "${ops[@]}"; [ "$output" = "1025023" ]; }
@test "another function" { run compose_all 4 square inc; [ "$output" = "25" ]; }

References

  1. Function composition (computer science), Wikipedia, the introduction; First-class composition
  2. functools, The Python Standard Library, functools.reduce
  3. Array.prototype.reduceRight(), MDN Web Docs JavaScript Reference, the introduction
  4. More on Functions, The TypeScript Handbook, Generic Functions
  5. Interface Function, Java SE 25 API, andThen; compose; identity
  6. Enumerable.Aggregate Method, .NET API, Overloads
  7. Pointer declaration, C reference, cppreference.com, Pointers to functions
  8. Functions, C reference, cppreference.com, the introduction
  9. std::function, C++ reference, cppreference.com, the introduction
  10. The Go Programming Language Specification, Type parameter declarations; Function literals
  11. Advanced Functions and Closures, The Rust Programming Language, Returning Closures, Listing 20-34
  12. Trait Iterator, The Rust Standard Library, rev; fold
  13. Shell Functions, Bash Reference Manual, 3.3 Shell Functions
  14. Programming FAQ, Python documentation, Why do lambdas defined in a loop with different values all return the same result?

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source