Programming Search⌘K

Conceptcore

Declarative programming

Also called declarative style, what not how, logic and control, nonprocedural language, declarative UI, declarative configuration.

Declarative programming describes the result a program must produce, such as a query, a pattern or a wanted state, and leaves the steps to an engine that decides how to compute it.

Applies to
core-languages

Idea

Declarative programming describes the result that a program must produce, not the steps to produce it. The programmer writes a description: a query, a pattern, a set of rules or the wanted state of a system. An engine then decides how to compute it. The SQLite documentation states the idea for SQL: "When programming in SQL you tell the system what you want to compute, not how to compute it."1 The same split appears in regular expressions, HTML and CSS, build files, configuration languages and user interface libraries:

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE emp (name TEXT, dept TEXT, salary INTEGER)")
db.executemany(
    "INSERT INTO emp VALUES (?, ?, ?)",
    [("ana", "eng", 120), ("bo", "eng", 100), ("cy", "ops", 90), ("di", "ops", 95), ("ed", "art", 70)],
)

query = """
SELECT dept, COUNT(*), MAX(salary)
FROM emp
WHERE salary >= 80
GROUP BY dept
ORDER BY dept
"""
for row in db.execute(query):
    print(row)
Output
('eng', 2, 120)
('ops', 2, 95)

The query says which rows to keep, how to group them and what to report. It does not say whether to scan the table or use an index, how to group, or in which order to visit the rows. The database can choose a different plan when the data grows or an index is added, and the query stays the same.

How it works

Logic and control. Robert Kowalski divided an algorithm into two parts: "a logic component, which specifies the knowledge to be used in solving problems, and a control component, which determines the problem-solving strategies by means of which that knowledge is used."2 He noted that "The logic component determines the meaning of the algorithm whereas the control component only affects its efficiency."2 A declarative program is the logic component. The engine supplies the control. Kowalski argued that programs "would be more often correct and more easily improved and modified if their logic and control aspects were identified and separated in the program text."2

An engine does the work. Each declarative language has an engine that turns a description into steps. A SQL database has a query planner. The SQLite documentation explains that for one statement "there might be hundreds or thousands or even millions of different algorithms of performing the operation", and the planner "tries to pick the fastest and most efficient algorithm for each SQL statement."1 A regular expression engine compiles a pattern into an automaton or a backtracking matcher. A browser turns HTML and CSS into a layout. A build tool turns a graph of dependencies into an order of commands. A logic language such as Prolog searches for values that make the rules true.

Independence from the representation. Because the description does not say how to find the data, the representation can change under it. Edgar Codd built the relational model on this point: "Future users of large data banks must be protected from having to know how the data is organized in the machine (the internal representation)."3 An index can be added, a table can be split, or a new version of the engine can choose a better plan, and the queries need no change.

Order does not matter, or matters less. In an imperative program, the order of the statements is part of the meaning. In a declarative description, it often is not. The Terraform documentation says that its language "is declarative, describing an intended goal rather than the steps to reach that goal. The ordering of blocks and the files they are organized into are generally not significant".4 The engine finds the order from the relationships between the parts, so it can also run independent parts in parallel.

Describe states, not transitions. User interface code used to change the screen step by step: enable this button, hide that message. React describes the other approach: "Instead of manipulating individual pieces of the UI directly, you describe the different states that your component can be in, and switch between them in response to the user input."5 A function maps each state to a description of the screen, and the library computes the changes. The number of states is usually much smaller than the number of transitions between them, so there is less code to get wrong.

In languages

LanguageVerdictNote
PythonNative
C++Idiom
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript; type declarations are also declarative, and they state the shape of values without code.
GoIdiom
RustIdiom
KotlinIdiomCollection functions, regular expressions and type-safe builders for declarative DSLs such as Jetpack Compose; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLNativeA query states the result, and the query planner chooses the algorithm; the Python example runs a query in SQLite.
BashIdiom
PowerShellIdiomWhere-Object, Sort-Object and Group-Object describe the result of a pipeline, and Desired State Configuration declares the state of a machine; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLNativeHTML declares the structure of a document, and the browser decides how to lay it out and draw it.
CSSNativeCSS declares styles for the elements that match each selector, and the browser applies the cascade to decide which rule wins.
Regular expressionsNativeA regular expression describes a set of strings, and the engine decides how to search; the Python, JavaScript, Java, Go, C and C++ examples use one.
Language Verdict Mechanism
Python native sqlite3 with SQL, re, comprehensions, decorators and data classes
JavaScript native regex literals, array methods, declarative UI libraries
TypeScript native as JavaScript, plus type declarations
Java native streams and collectors, java.util.regex, annotations
Kotlin idiom collection functions, regex, type-safe builders
C# native LINQ query syntax, attributes, Regex
Go idiom text/template, regexp, struct tags
Rust idiom match patterns, derive attributes; regex in a crate
C idiom POSIX <regex.h>, printf format strings
C++ idiom <regex>, range algorithms with projections
Bash idiom awk patterns and actions, find, make
PowerShell idiom Where-Object, Group-Object, Desired State Configuration
SQL native queries planned by the engine
Regex native patterns compiled into matchers
HTML native document structure; the browser lays it out
CSS native rules for selectors; the cascade decides

No general-purpose language in the table is declarative at its base. Python, Java, C#, Go, Rust and C are imperative, and they reach declarative style through embedded languages and libraries. The common pattern is a small language for one domain, inside a string or a builder: SQL in a string passed to a driver, a regular expression, a template, a format string. C# went further and put a query language into the syntax. Microsoft's guide says that with LINQ "you write declarative code that describes what you want to retrieve."6 The compiler turns the query into method calls, and a provider can turn the same query into SQL.

SQL, regular expressions, HTML and CSS are declarative by design. They are not general-purpose languages, and their engines are complex: a query planner, a regex compiler, a layout engine. The narrow domain is what lets the engine choose a good strategy.

Annotations and attributes are another declarative form in Java, C#, Python and Rust. A field marked as required, a method marked as a route for a URL, or a type marked to derive Debug states a fact, and a framework or the compiler writes the code. See annotations.

PythonGitHub
import re
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (item TEXT, qty INTEGER, price INTEGER)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", [("pen", 3, 2), ("book", 1, 12), ("ink", 2, 5), ("pen", 4, 2)])

query = "SELECT item, SUM(qty * price) FROM orders GROUP BY item ORDER BY 2 DESC"
for row in db.execute(query):
    print(row)

print(re.findall(r"\b(\d{4})-(\d{2})-(\d{2})\b", "from 2024-01-31 to 2025-12-01"))
Output
('pen', 14)
('book', 12)
('ink', 10)
[('2024', '01', '31'), ('2025', '12', '01')]

This code runs but gives a wrong answer on purpose.

import re

html = "<b>bold</b> and <i>italic</i>"
print(re.findall(r"<.*>", html))
print(re.findall(r"<.*?>", html))
Output
['<b>bold</b> and <i>italic</i>']
['<b>', '</b>', '<i>', '</i>']
  • Verdict: native. The standard library includes sqlite3, so a Python program can state a query in SQL and let the SQLite engine choose how to run it. The re module compiles a regular expression into a matcher.
  • The ? placeholders pass values to the query as data. Do not build SQL text from values with string formatting.
  • In the wrong block, .* is greedy, so the first pattern matches from the first < to the last >. A regular expression states what to match, but its rules for which match wins still need care. The lazy form .*? matches each tag.
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

struct Order {
    std::string item;
    int qty;
    int price;
};

int main() {
    std::vector<Order> orders{{"pen", 3, 2}, {"book", 1, 12}, {"ink", 2, 5}};
    std::ranges::sort(orders, std::ranges::greater{}, [](const Order& o) { return o.qty * o.price; });
    for (const auto& o : orders) std::cout << o.item << " ";
    std::cout << "\n";

    const std::string text = "from 2024-01-31 to 2025-12-01";
    const std::regex date(R"((\d{4})-(\d{2})-(\d{2}))");
    for (auto it = std::sregex_iterator(text.begin(), text.end(), date); it != std::sregex_iterator(); ++it) {
        std::cout << (*it)[1] << "\n";
    }
}
Output
book ink pen 
2024
2025
  • Verdict: idiom. The call to std::ranges::sort states the order with a comparison and a projection, and the library chooses the algorithm. <regex> provides regular expressions, though it is slow compared with other engines.
JavaGitHub
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    record Order(String item, int qty, int price) {}

    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("pen", 3, 2), new Order("book", 1, 12), new Order("ink", 2, 5), new Order("pen", 4, 2));

        Map<String, Integer> totals = orders.stream()
                .collect(Collectors.groupingBy(Order::item, TreeMap::new, Collectors.summingInt(o -> o.qty() * o.price())));
        System.out.println(totals);

        var m = Pattern.compile("\\b(\\d{4})-(\\d{2})-(\\d{2})\\b").matcher("from 2024-01-31 to 2025-12-01");
        while (m.find()) {
            System.out.println(m.group(1) + " " + m.group(2));
        }
    }
}
Output
{book=12, ink=10, pen=14}
2024 01
2025 12
  • Verdict: native. Collectors.groupingBy states the grouping and the sum, and the stream library writes the loop. java.util.regex compiles patterns into matchers.
  • Annotations such as @Override and frameworks that read them, such as dependency injection containers, are another declarative layer on top of the language.
#include <regex.h>
#include <stdio.h>

int main(void)
{
    regex_t re;
    if (regcomp(&re, "([0-9]{4})-([0-9]{2})-([0-9]{2})", REG_EXTENDED) != 0)
        return 1;

    const char *p = "from 2024-01-31 to 2025-12-01";
    regmatch_t m[4];
    while (regexec(&re, p, 4, m, 0) == 0) {
        printf("%.*s\n", (int)(m[1].rm_eo - m[1].rm_so), p + m[1].rm_so);
        p += m[0].rm_eo;
    }
    regfree(&re);

    printf("[%-6s|%6.2f]\n", "pen", 3.14159);
    return 0;
}
Output
2024
2025
[pen   |  3.14]
  • Verdict: idiom. C is imperative, but it has small declarative languages inside its libraries: the POSIX regular expressions of <regex.h> and the format strings of printf, which state the layout of the output.
var orders = new[] { new Order("pen", 3, 2), new Order("book", 1, 12), new Order("ink", 2, 5), new Order("pen", 4, 2) };

var totals =
    from o in orders
    group o by o.Item into g
    let total = g.Sum(o => o.Qty * o.Price)
    orderby total descending
    select $"{g.Key}: {total}";

foreach (var line in totals)
{
    Console.WriteLine(line);
}

record Order(string Item, int Qty, int Price);
Output
pen: 14
book: 12
ink: 10
  • Verdict: native. LINQ query syntax reads like SQL, and the compiler turns it into calls to methods such as GroupBy, OrderByDescending and Select. Microsoft's guide says that with LINQ "you write declarative code that describes what you want to retrieve."
  • A LINQ provider such as Entity Framework can translate the same query into SQL for a database.
JavaScriptGitHub
function view(state) {
  if (state.status === "sending") return "[form disabled] Sending...";
  if (state.status === "sent") return "Thank you!";
  const button = state.answer.trim() === "" ? "[Submit disabled]" : "[Submit]";
  const error = state.error ? ` Error: ${state.error}` : "";
  return `[input: ${state.answer}] ${button}${error}`;
}

const states = [
  { status: "typing", answer: "" },
  { status: "typing", answer: "Lima" },
  { status: "sending", answer: "Lima" },
  { status: "typing", answer: "Lima", error: "network" },
  { status: "sent", answer: "Lima" },
];
for (const s of states) console.log(view(s));

const dates = "from 2024-01-31 to 2025-12-01".matchAll(/\b(\d{4})-(\d{2})-(\d{2})\b/g);
console.log([...dates].map((m) => m[1]));
Output
[input: ] [Submit disabled]
[input: Lima] [Submit]
[form disabled] Sending...
[input: Lima] [Submit] Error: network
Thank you!
[ '2024', '2025' ]
  • Verdict: native. The view function describes what the screen shows for each state, and it does not say how to change the screen from one state to the next. This is the model of React and other declarative UI libraries: the library compares the old and the new description and makes the changes.
  • Regular expressions are built in, with literal syntax /.../.
package main

import (
	"fmt"
	"os"
	"regexp"
	"text/template"
)

type Order struct {
	Item       string
	Qty, Price int
}

func main() {
	t := template.Must(template.New("report").Parse(
		"{{range .}}{{if gt .Qty 1}}{{.Item}} x{{.Qty}}\n{{end}}{{end}}"))
	orders := []Order{{"pen", 3, 2}, {"book", 1, 12}, {"ink", 2, 5}}
	if err := t.Execute(os.Stdout, orders); err != nil {
		panic(err)
	}

	re := regexp.MustCompile(`\b(\d{4})-(\d{2})-(\d{2})\b`)
	for _, m := range re.FindAllStringSubmatch("from 2024-01-31 to 2025-12-01", -1) {
		fmt.Println(m[1], m[2], m[3])
	}
}
Output
pen x3
ink x2
2024 01 31
2025 12 01
  • Verdict: idiom. Go code is mostly imperative, but the standard library has declarative parts: text/template and html/template describe output, regexp describes text, and struct tags describe how encoding/json maps fields.
  • The regexp package guarantees time linear in the size of the input, because it does not support backreferences.
RustGitHub
#[derive(Debug)]
enum Cmd<'a> {
    Get(&'a str),
    Set(&'a str, &'a str),
    Quit,
}

fn parse<'a>(words: &[&'a str]) -> Option<Cmd<'a>> {
    match words {
        ["get", key] => Some(Cmd::Get(*key)),
        ["set", key, value] => Some(Cmd::Set(*key, *value)),
        ["quit"] | ["exit"] => Some(Cmd::Quit),
        _ => None,
    }
}

fn main() {
    for line in ["get name", "set name ada", "exit", "set name"] {
        let words: Vec<&str> = line.split_whitespace().collect();
        println!("{:?}", parse(&words));
    }
}
Output
Some(Get("name"))
Some(Set("name", "ada"))
Some(Quit)
None
  • Verdict: idiom. Rust code is imperative, but match with slice patterns states the shape of each valid input, and the compiler builds the tests. Derive attributes such as #[derive(Debug)] declare traits that the compiler then writes.
  • The standard library has no regular expressions. The regex crate is the common choice.
BashGitHub
printf '%s\n' "pen 3 2" "book 1 12" "ink 2 5" "pen 4 2" |
    awk '$2 > 1 { total[$1] += $2 * $3 }
         END    { for (k in total) print k, total[k] }' |
    sort
Output
ink 10
pen 14
  • Verdict: idiom. An awk program is a list of patterns and actions: for each line that matches the pattern, awk runs the action. The program does not write the loop over the lines. Tools such as find, make and sort also take a description of what to do.
  • Functional programming. Pure functions describe values, not steps, so functional programs are often called declarative. See functional programming.
  • Logic programming. A program is a set of facts and rules, and the engine searches for answers to queries. Prolog and Datalog are the main examples.
  • Constraint programming. The program states constraints on variables, and a solver finds values that satisfy them. SAT and SMT solvers, and constraint solvers in scheduling, work this way.
  • Configuration as code. Terraform, Kubernetes manifests and Nix describe the wanted state of a system, and a tool computes the changes to reach it.
  • Build systems. Make, Bazel and similar tools take a graph of targets and dependencies and decide what to rebuild and in which order.
  • Dataflow and reactive programming. A spreadsheet is declarative: each cell states how to compute its value, and the engine updates cells when their inputs change.
  • Embedded DSLs. A library can give a declarative interface inside an imperative language, such as LINQ, query builders and UI builders.

Pitfalls

  • Performance depends on the engine. The same query can take a millisecond or an hour, depending on the plan and the indexes. Read the plan, for example with EXPLAIN, when a query is slow.
  • The abstraction leaks. Regular expressions with nested repetition can backtrack for exponential time on some inputs. CSS rules can conflict in ways that need knowledge of the cascade and of specificity.
  • Greedy and default rules. A description can match more than the author meant, such as a greedy .* in a regular expression or an unqualified CSS selector.
  • Injection. Building SQL, shell commands or HTML from untrusted text by string concatenation lets the text change the description. Use parameters and escaping that the engine provides.
  • Hard to debug. There are no steps to trace. When the result is wrong, reduce the description or ask the engine to explain its plan.
  • Hidden order. Some declarative systems still depend on order in places, such as the order of rules in CSS when specificity is equal, or the order of clauses in Prolog for termination.

Cost

The cost of a declarative program is the cost of the plan that the engine chooses, plus the cost of choosing it. A good engine can beat hand-written code, because it knows the indexes, the sizes of the data and the hardware, and can change its plan when they change. A poor plan can be much slower than a simple loop. Engines also cost start-up time: a query must be parsed and planned, and a regular expression must be compiled, so programs cache prepared statements and compiled patterns. Engines with guarantees make the cost predictable: Go's regexp and the RE2 library run in time linear in the input because they do not support backreferences.

History

Declarative ideas came from logic and from data. In 1970, Edgar Codd proposed the relational model, in which a query is a statement about relations and not a program that walks a file.3 SEQUEL, later SQL, came out of IBM's System R project in the 1970s. Alain Colmerauer and Philippe Roussel designed Prolog in 1972, and Kowalski described logic programming and the split of logic and control in 1979.2 Ken Thompson built regular expression search into text editors in the 1960s, and Unix tools such as grep, sed, awk and make spread declarative small languages among programmers. HTML in 1991 and CSS in 1996 made declarative description the basis of the web. From the 2010s on, declarative user interfaces such as React and SwiftUI, and declarative infrastructure such as Terraform and Kubernetes, moved the idea into application and operations code.

References

  1. Query Planning, SQLite documentation, 1 Overview
  2. Algorithm = Logic + Control, Robert Kowalski, Communications of the ACM 22(7), 1979, abstract
  3. A Relational Model of Data for Large Shared Data Banks, E. F. Codd, Communications of the ACM 13(6), 1970, 1.1 Introduction
  4. Terraform Language Documentation, HashiCorp, About the Terraform Language
  5. Reacting to Input with State, React documentation, How declarative UI compares to imperative
  6. Introduction to LINQ Queries in C#, Microsoft Learn, introduction

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/0HBVK7/text.yaml