Programming Search⌘K

Conceptcore

Concatenative programming

Also called stack-based programming, stack languages, Forth style, postfix programming, point-free stack programming.

In concatenative programming, every word is a function from a stack to a stack, so writing two programs one after the other composes them, and no word names its arguments.

Applies to
core-languages

Idea

A concatenative program is a sequence of words, and writing two programs one after the other composes them. Each word is a function from a stack of values to a new stack: 2 pushes the number 2, + pops two numbers and pushes their sum, and dup copies the top item. The program 2 3 + 4 * pushes 2 and 3, adds them, pushes 4 and multiplies, and leaves 20. No word names its arguments, because every word takes its inputs from the stack and leaves its results there. Forth, PostScript, Joy, Factor and the bytecode of the JVM and of CPython work in this way.

import operator

WORDS = {}  # word name -> function that changes the stack
DEFS = {"square": "dup *", "inc": "1 +"}  # words defined by other words


def binary(f):
    def word(s):
        b, a = s.pop(), s.pop()
        s.append(f(a, b))
    return word


WORDS.update({"+": binary(operator.add), "*": binary(operator.mul),
              "-": binary(operator.sub)})
WORDS["dup"] = lambda s: s.append(s[-1])
WORDS["swap"] = lambda s: s.extend([s.pop(), s.pop()])
WORDS["i"] = lambda s: run(s.pop(), s)  # call the quotation on top


def dip(s):  # run the quotation under the top item
    q, x = s.pop(), s.pop()
    run(q, s)
    s.append(x)


WORDS["dip"] = dip


def parse(tokens):
    out = []
    while tokens:
        t = tokens.pop(0)
        if t == "[":
            out.append(parse(tokens))  # a quotation is a program as data
        elif t == "]":
            return out
        else:
            out.append(int(t) if t.lstrip("-").isdigit() else t)
    return out


def run(prog, stack):
    if isinstance(prog, str):
        prog = parse(prog.split())
    for w in prog:
        if isinstance(w, list) or isinstance(w, int):
            stack.append(w)
        elif w in DEFS:
            run(DEFS[w], stack)
        else:
            WORDS[w](stack)
    return stack


print(run("2 3 + 4 *", []))
print(run("3 square inc", []))
print(run("1 2 [ 10 * ] dip", []))
print(run("5 [ square ] i", []))

p, q = "2 3 +", "4 * inc"
print(run(p + " " + q, []) == run(q, run(p, [])))
Output
[20]
[10]
[10, 2]
[25]
True

The interpreter is a loop over the words. A number pushes itself, a defined word such as square runs its definition, and a quotation in brackets pushes itself as data until a combinator such as i or dip runs it. The last line shows the central property: running p and then q on the result gives the same stack as running the text of p joined to the text of q.

How it works

Concatenation is composition. In most languages a program applies functions to arguments, as in f(g(x), y). In a concatenative language, every word denotes a function from stacks to stacks, and putting words side by side composes their functions. Manfred von Thun, who designed Joy, wrote: "Whereas all other functional programming languages are based on the application of functions to arguments, Joy is based on the composition of functions. All such functions take a stack as argument and produce a stack as value."1 Because composition is associative, a program can be cut at any point between two words, and each part is a valid program. This makes refactoring mechanical: any sequence of words that appears twice can become a new word.

The stack carries the data. The stack replaces named variables. A word states its stack effect, the items it takes from the top and the items it leaves, and Forth programmers write it in a comment before each definition, while Factor requires it in the syntax of each definition. Shuffle words such as dup, drop, swap, over and rot rearrange the top items, so that the next word finds its inputs in the right order. Short definitions keep the shuffling small, and Forth programmers aim for words of one or two lines.

Quotations and combinators. A quotation is a program written as data, such as [ 10 * ]. It stays on the stack until a combinator runs it. i runs the quotation on top, dip runs it under the item below, and map, filter and ifte give loops and conditionals. Von Thun summed up the design: "where other functional languages use abstraction and application, Joy uses quotation and combinators".1 Quotations play the role of the lambdas of other languages, so higher-order programming needs no variables. See higher-order functions.

A simple semantics. The meaning of a program follows from the meaning of its words and one rule. The paper on the foundations of Joy states it: "The concatenation of two programs denotes the composition of the functions denoted by the two programs."2 In algebraic terms, the meaning of programs is a homomorphism from the monoid of programs under concatenation to the monoid of functions under composition. Equations such as swap swap = id and dup drop = id hold for every stack, and a programmer or a compiler can rewrite programs with them.

Stack machines underneath. Many virtual machines are stack machines: the JVM, the .NET runtime, CPython and WebAssembly run bytecode that pushes and pops values. A compiler for one of them translates the nested expressions of the source into a concatenative program, so (a + b) * c becomes a b + c *. Concatenative languages expose this model to the programmer, and a simple implementation needs only a loop, a stack and a dictionary of words.

In languages

LanguageVerdictNote
PythonAbsent
C++Absent
JavaAbsent
CAbsent
C#Absent
JavaScriptAbsent
TypeScriptAbsentAs JavaScript; a type for a word can state the stack that it takes and the stack that it leaves as tuple types.
GoAbsent
RustAbsent
KotlinAbsentKotlin applies functions to arguments; the JVM that runs it is a stack machine; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applySQL queries are expressions over tables, with no stack and no sequence of words.
BashIdiomA pipeline joins programs by writing them one after another, and the POSIX calculator dc is a stack language, so echo '2 3 + p' | dc prints 5.
PowerShellIdiomThe pipeline joins commands left to right, and each command takes the objects of the one before it; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no programs to compose.
CSSDoes not applyCSS has no programs to compose.
Regular expressionsDoes not applyA regular expression is a pattern, not a program of words; concatenating two patterns does give a pattern for the concatenated languages.
Language Verdict Mechanism
Python absent closures over a list or tuple stack; CPython bytecode is a stack machine
JavaScript absent arrays of functions; method chains
TypeScript absent as JavaScript
Java absent andThen on functional interfaces; JVM bytecode
Kotlin absent function composition; JVM bytecode
C# absent delegates over ImmutableStack<T>; CIL bytecode
Go absent a map of words and a loop
Rust absent an enum of operations and match; iterator chains
C absent a global stack and a loop over tokens
C++ absent lambdas composed with a fold expression
Bash idiom pipelines; the dc calculator
PowerShell idiom the object pipeline
SQL n/a no stack and no words
Regex n/a patterns, not programs of words
HTML n/a no programs to compose
CSS n/a no programs to compose

None of the core languages of this site is concatenative. They all apply functions to named arguments, so the concatenative model appears in them as an interpreter: a stack, a dictionary of words and a loop, as every example file builds. Each such interpreter is short, which shows how little machinery the model needs.

Several common features have a concatenative shape without a stack. Unix pipelines join programs by writing them in sequence, and each program takes the output of the one before it. Method chains such as items.filter(f).map(g) in JavaScript, Java streams, LINQ and Rust iterators read left to right, and the pipe operators |> of F#, Elixir and OCaml turn nested calls into a sequence. These are compositions of functions of one value, while a concatenative word can take and leave any number of values.

PythonGitHub
from functools import reduce

# A word is a pure function from a stack (a tuple) to a new stack.
def push(n):
    return lambda s: s + (n,)


def lift2(f):
    return lambda s: s[:-2] + (f(s[-2], s[-1]),)


dup = lambda s: s + (s[-1],)
add = lift2(lambda a, b: a + b)
mul = lift2(lambda a, b: a * b)


def compose(*words):
    return reduce(lambda f, g: lambda s: g(f(s)), words, lambda s: s)


program = [push(2), push(3), add, dup, mul, push(1), add]  # (2 + 3) squared, plus 1
print(compose(*program)(()))

# Cut the program at every point: the two halves composed give the same result.
results = {compose(compose(*program[:k]), compose(*program[k:]))(())
           for k in range(len(program) + 1)}
print(results)
Output
(26,)
{(26,)}

This code runs but gives a wrong answer on purpose.

def run(text):
    s = []
    for t in text.split():
        if t in "-*":
            b, a = s.pop(), s.pop()
            s.append(a - b if t == "-" else a * b)
        else:
            s.append(int(t))
    return s


# Intended: 10 minus the product of 2 and 3.
print(run("2 3 * 10 -"))
Output
[-4]
  • Verdict: absent. Python applies functions to named arguments. The first block builds the concatenative model from closures: each word is a pure function from a tuple to a tuple, a program is the composition of its words, and the set of results shows that a cut at any point gives the same answer. CPython itself runs a stack machine: its bytecode pushes and pops values, as dis.dis shows.
  • The wrong block computes 6 minus 10, not 10 minus 6. - takes the item under the top as its left operand, so the 10 must be pushed before the product: 10 2 3 * - gives 4. A reader must track the stack to see the order of operands, which is the main cost of the style.
#include <iostream>
#include <vector>

using Stack = std::vector<int>;

namespace w {
auto push(int n) {
    return [n](Stack s) { s.push_back(n); return s; };
}

auto lift2(auto f) {
    return [f](Stack s) {
        int b = s.back(); s.pop_back();
        int a = s.back(); s.pop_back();
        s.push_back(f(a, b));
        return s;
    };
}

const auto dup = [](Stack s) { s.push_back(s.back()); return s; };
const auto add = lift2([](int a, int b) { return a + b; });
const auto mul = lift2([](int a, int b) { return a * b; });

// seq(f, g, h) is the program "f g h": apply f, then g, then h.
auto seq(auto... words) {
    return [=](Stack s) { ((s = words(std::move(s))), ...); return s; };
}
}  // namespace w

void show(const Stack& s) {
    for (int x : s) std::cout << x << " ";
    std::cout << "\n";
}

int main() {
    auto square = w::seq(w::dup, w::mul);
    show(w::seq(w::push(2), w::push(3), w::add, square)({}));

    auto left = w::seq(w::seq(w::push(4), w::push(5)), w::seq(w::add, square));
    auto right = w::seq(w::push(4), w::seq(w::push(5), w::add), square);
    show(left({}));
    show(right({}));
}
Output
25 
81 
81 
  • Verdict: absent. C++ applies functions to arguments. A fold expression over a pack of lambdas composes the words at compile time, so seq builds a program that the compiler can inline into straight-line code. Grouping the words in different ways gives the same program, because composition is associative.
JavaGitHub
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.function.Consumer;

public class Main {
    // A word changes the stack. then() puts one word after another.
    interface Word extends Consumer<Deque<Integer>> {
        default Word then(Word next) {
            return s -> { accept(s); next.accept(s); };
        }
    }

    static Word push(int n) { return s -> s.push(n); }

    static final Word DUP = s -> s.push(s.peek());
    static final Word ADD = s -> s.push(s.pop() + s.pop());
    static final Word MUL = s -> s.push(s.pop() * s.pop());
    static final Word SWAP = s -> { int b = s.pop(), a = s.pop(); s.push(b); s.push(a); };

    public static void main(String[] args) {
        Word square = DUP.then(MUL);
        Word sumOfSquares = square.then(SWAP).then(square).then(ADD);

        Deque<Integer> stack = new ArrayDeque<>();
        push(3).then(push(4)).then(sumOfSquares).accept(stack);
        System.out.println(stack);
    }
}
Output
[25]
  • Verdict: absent. Java applies methods to arguments. Consumer.andThen and Function.andThen compose functions, and the then method above builds programs from words in the same way. The JVM is a stack machine: its bytecode, such as iload, imul and iadd, is a concatenative program, and the verifier checks the stack effect of each method, the number and the types of the values that it takes and leaves.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static long stack[64];
static int sp = 0;

static void push(long x) {
    if (sp == 64) { fprintf(stderr, "stack overflow\n"); exit(1); }
    stack[sp++] = x;
}

static long pop(void) {
    if (sp == 0) { fprintf(stderr, "stack underflow\n"); exit(1); }
    return stack[--sp];
}

static const char *defs[][2] = {{"square", "dup *"}, {"cube", "dup square *"}};

static void eval(const char *p) {
    char t[32];
    int used;
    while (sscanf(p, "%31s%n", t, &used) == 1) {
        p += used;
        long a, b;
        int found = 0;
        for (size_t i = 0; i < sizeof defs / sizeof defs[0]; i++)
            if (strcmp(t, defs[i][0]) == 0) { eval(defs[i][1]); found = 1; }
        if (found) continue;
        if (strcmp(t, "+") == 0) { b = pop(); a = pop(); push(a + b); }
        else if (strcmp(t, "*") == 0) { b = pop(); a = pop(); push(a * b); }
        else if (strcmp(t, "dup") == 0) { a = pop(); push(a); push(a); }
        else push(strtol(t, NULL, 10));
    }
}

int main(void) {
    eval("2 3 + square");
    eval("1 cube");
    eval("3 cube +");
    for (int i = 0; i < sp; i++) printf("%ld ", stack[i]);
    printf("\n");
    return 0;
}
Output
25 28 
  • Verdict: absent. C applies functions to arguments. A global stack, a table of definitions and a loop over the words give a Forth-like interpreter in a page of code, which is why Forth runs on very small machines. The three calls to eval share one stack, so the second and third lines of text continue the first, as in Forth.
using System;
using System.Collections.Immutable;
using System.Linq;

Word Push(int n) => s => s.Push(n);
Word Lift2(Func<int, int, int> f) => s =>
{
    s = s.Pop(out int b).Pop(out int a);
    return s.Push(f(a, b));
};
Word Seq(params Word[] words) => s => words.Aggregate(s, (acc, w) => w(acc));

Word dup = s => s.Push(s.Peek());
Word mul = Lift2((a, b) => a * b);
Word sub = Lift2((a, b) => a - b);
Word square = Seq(dup, mul);

var result = Seq(Push(7), square, Push(9), sub)(ImmutableStack<int>.Empty);
Console.WriteLine(string.Join(" ", result));

var before = ImmutableStack<int>.Empty.Push(1);
var after = Seq(Push(2), Push(3))(before);
Console.WriteLine($"{string.Join(" ", before)} | {string.Join(" ", after)}");

delegate ImmutableStack<int> Word(ImmutableStack<int> s);
Output
40
1 | 3 2 1
  • Verdict: absent. C# applies methods to arguments. With ImmutableStack<T>, each word is a pure function that returns a new stack and leaves the old one as it was, so before still holds only 1 after the program ran on it. The stack lists its top item first. The .NET runtime runs CIL, the bytecode of a stack machine.
JavaScriptGitHub
// A word maps a stack to a stack. A program is an array of words,
// so joining two programs is array concatenation.
const push = (n) => (s) => [...s, n];
const lift2 = (f) => (s) => [...s.slice(0, -2), f(s.at(-2), s.at(-1))];
const words = {
  "+": lift2((a, b) => a + b),
  "*": lift2((a, b) => a * b),
  dup: (s) => [...s, s.at(-1)],
  swap: (s) => [...s.slice(0, -2), s.at(-1), s.at(-2)],
};

const compile = (text) =>
  text.split(/\s+/).map((t) => (t in words ? words[t] : push(Number(t))));
const run = (prog, stack = []) => prog.reduce((s, w) => w(s), stack);

const square = compile("dup *");
const sumOfSquares = [...square, ...compile("swap"), ...square, ...compile("+")];

console.log(run(compile("3 4"), []), "->", run(sumOfSquares, [3, 4]));
console.log(run([...compile("3 4"), ...sumOfSquares]));
Output
[ 3, 4 ] -> [ 25 ]
[ 25 ]
  • Verdict: absent. JavaScript applies functions to arguments. Because functions are values, a program can be an array of words, and two programs join with the spread operator, as sumOfSquares does. Method chains such as array.filter(f).map(g) read left to right in the same way, but each step names its function, and the value passes along one at a time instead of on a stack.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Stack []int
type Word func(Stack) Stack

func Push(n int) Word {
	return func(s Stack) Stack { return append(s[:len(s):len(s)], n) }
}

func Lift2(f func(a, b int) int) Word {
	return func(s Stack) Stack {
		n := len(s)
		out := append(Stack{}, s[:n-2]...)
		return append(out, f(s[n-2], s[n-1]))
	}
}

var dict = map[string]Word{
	"+":   Lift2(func(a, b int) int { return a + b }),
	"*":   Lift2(func(a, b int) int { return a * b }),
	"dup": func(s Stack) Stack { return append(s[:len(s):len(s)], s[len(s)-1]) },
}

// Compile turns text into one word: the composition of its words.
func Compile(text string) Word {
	var words []Word
	for _, t := range strings.Fields(text) {
		if w, ok := dict[t]; ok {
			words = append(words, w)
		} else if n, err := strconv.Atoi(t); err == nil {
			words = append(words, Push(n))
		} else {
			panic("unknown word " + t)
		}
	}
	return func(s Stack) Stack {
		for _, w := range words {
			s = w(s)
		}
		return s
	}
}

func main() {
	dict["square"] = Compile("dup *")
	fmt.Println(Compile("2 3 + square")(nil))
	fmt.Println(Compile("4 square square")(Stack{1}))
}
Output
[25]
[1 256]
  • Verdict: absent. Go applies functions to arguments. A dictionary from names to functions and a loop give a small concatenative language, and a new word is the compiled text of older words, as square is. The full slice expression s[:len(s):len(s)] makes append copy, so a word never changes the stack that it received.
RustGitHub
use Op::*;

#[derive(Clone, Copy, Debug)]
enum Op {
    Push(i64),
    Add,
    Mul,
    Dup,
    Swap,
    Call(&'static [Op]),
}

const SQUARE: &[Op] = &[Dup, Mul];
const SUM_OF_SQUARES: &[Op] = &[Call(SQUARE), Swap, Call(SQUARE), Add];

fn run(prog: &[Op], stack: &mut Vec<i64>) {
    for op in prog {
        match *op {
            Push(n) => stack.push(n),
            Add | Mul => {
                let b = stack.pop().expect("stack underflow");
                let a = stack.pop().expect("stack underflow");
                stack.push(if matches!(op, Add) { a + b } else { a * b });
            }
            Dup => {
                let top = *stack.last().expect("stack underflow");
                stack.push(top);
            }
            Swap => {
                let n = stack.len();
                stack.swap(n - 2, n - 1);
            }
            Call(body) => run(body, stack),
        }
    }
}

fn main() {
    let mut s = vec![];
    run(&[Push(3), Push(4), Call(SUM_OF_SQUARES)], &mut s);
    println!("{s:?}");

    let p = [Push(2), Push(5)];
    let q = [Mul, Dup, Add];
    let joined: Vec<Op> = [&p[..], &q[..]].concat();
    let (mut one, mut two) = (vec![], vec![]);
    run(&joined, &mut one);
    run(&p, &mut two);
    run(&q, &mut two);
    println!("{one:?} {two:?}");
}
Output
[25]
[20] [20]
  • Verdict: absent. Rust applies functions to arguments. An enum of operations and a match loop give a stack machine whose programs are slices, and concat joins two programs into one that does the work of both in turn. Iterator chains read left to right like a concatenative program, but each adaptor names its function and takes one value at a time.
  • Forth. A small, fast language for machine control and embedded systems, with words that compile to threaded code. Users extend the compiler itself with new words.
  • PostScript. A stack language for page description, which printers run to draw text and graphics. PDF grew from its imaging model.
  • Joy. A purely functional concatenative language by Manfred von Thun, with quotations and combinators in place of variables.
  • Factor. Its home page calls it "a concatenative, stack-based programming language with high-level features including dynamic types, extensible syntax, macros, and garbage collection".3 It has an optimizing compiler and a large library.
  • Typed stack languages. Cat and Kitten give each word a type that states the stack it takes and the stack it leaves, and infer these types, so that an unbalanced stack is a compile-time error.
  • Array stack languages. Uiua combines the stack of concatenative languages with the primitives of APL. See array-oriented programming.
  • Point-free style. Functional programmers write sum . map square in Haskell, which composes functions without naming the argument. Concatenative languages make this the only style. See functional programming.
  • Stack machines. The JVM, CIL, CPython bytecode and WebAssembly are concatenative instruction sets, and RPN calculators from Hewlett-Packard use the same order of operands.

Pitfalls

  • Operand order. 2 3 * 10 - computes 6 minus 10, because - takes the item under the top as its left operand. The wrong block in the Python file shows this mistake.
  • Stack effects that do not balance. A word that leaves one item too many, or takes one too few, breaks every word that runs after it, often far from the cause. State the stack effect of each word and test words alone. Typed stack languages find these errors before the program runs.
  • Stack juggling. A word that needs four values and a long series of rot, over and swap is hard to read. Split the word into smaller ones, or use the named locals that Forth and Factor give.
  • Hidden arity. A reader cannot see how many items a word takes without its definition or its stack comment, so a sequence of unfamiliar words is hard to follow.
  • Underflow. Popping an empty stack is an error at run time in a dynamic implementation and undefined behavior in some small Forth systems. Check the depth at the boundaries of a program.

Cost

A word costs one dispatch in an interpreter, often a jump through a table of addresses in Forth's threaded code. Pushes and pops are memory accesses near the top of the stack, which stays in the cache. An optimizing compiler, such as Factor's or a JIT for the JVM, keeps the top items of the stack in registers and removes most of the pushes and pops, so the code runs like code from an applicative language. A definition costs one call, and inlining short words removes that. An interpreter for the model fits in a few kilobytes, which is why Forth systems run on microcontrollers.

History

Charles H. Moore developed Forth in the late 1960s and used it in 1970 to control the telescopes of the National Radio Astronomy Observatory. Forth spread to embedded systems, boot firmware and space hardware, and ANSI standardized it in 1994. Hewlett-Packard calculators used Reverse Polish notation from 1968. John Warnock and Charles Geschke released PostScript at Adobe in 1984, and it made a stack language run in millions of printers.

Manfred von Thun designed Joy in the 1990s and gave the model its algebraic foundations: programs form a monoid under concatenation, and their meaning is a homomorphism to functions under composition.2 Slava Pestov started Factor in 2003, and the community around Joy, Factor and Cat adopted the name concatenative programming. Stack bytecode came with Pascal's p-code in the 1970s and the JVM in 1995, and WebAssembly made a stack machine a standard target for the web in 2017.

References

  1. Manfred von Thun, Rationale for Joy, a functional language, Introduction
  2. Manfred von Thun, Mathematical foundations of Joy, Introduction; program concatenation and function composition
  3. Factor programming language, Why Factor

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)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DFH6NR/text.yaml