Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Functional Programming in Java

Summary

This repository accompanies a book-length experiment on practicing functional programming in modern Java, primarily Java 21.

It is not an attempt to turn Java into Scala or Haskell. Nor is it a tutorial on functional syntax or library usage.

Instead, this work explores a simple question:

What kind of functional programming becomes possible when Java is pushed to the edge of its current language design?

Recent versions of Java have quietly accumulated features that significantly change how programs can be structured:

  • immutable data via record
  • algebraic-style modeling via sealed types
  • increasingly expressive pattern matching
  • improved type inference and lambda ergonomics

Taken together, these features make Java closer to functional languages than it has ever been before.

This book treats Java as a constrained functional language, and examines what can be built within those constraints.

Motivation

Functional programming is often taught using languages that were designed for it from the beginning. That is valuable—but it makes it easy to miss why those abstractions exist at all. This project takes the opposite approach.

By attempting functional programming inside Java, we are forced to confront design pressure directly: what the language enables, what it resists, and where abstractions begin to leak.

The goal is clarity rather than convenience.

Implementing core functional constructs in Java— such as Option, Either, State, IO, parser combinators, and even a minimal Free Monad— reveals why these abstractions exist and what structural problems they are meant to solve.

Java makes these problems visible precisely because it does not erase them with syntax.

Why Java 21?

Java 21 represents a turning point—not as a sudden break, but as the point where a long sequence of changes becomes coherent.

Java’s path toward functional programming did not begin with Java 21.

Java 8 introduced functional interfaces and lambda expressions, making it practical to pass functions into other functions in everyday Java code.

Java 17 added records and sealed interfaces, making it possible to model immutable data and closed sets of variants explicitly— a prerequisite for functional-style data modeling.

With Java 21, pattern matching integrates these features at the syntactic level. Data modeling, branching, and decomposition now work together, making functional-style control flow practical in Java.

Taken together, these changes make it possible to treat modern Java as a constrained functional language— not by accident, but by gradual design.

Scope of the Experiment

This book progresses from basic functional data types to effect modeling and DSL construction:

  • foundational types (Option, Either, Try)
  • state and effect suspension
  • functional data structures
  • parser combinators
  • Free Monads and interpretation
  • DSL design and the boundary between programs and data

The emphasis is not on performance or completeness, but on structural insight. Code exists to support reasoning, and reasoning exists to expose structure. The code is not presented as a solution, but as a concrete artifact through which structure becomes visible.

Rather than bringing Java closer to functional languages, this experiment uses Java to make the hidden structure of functional languages easier to see.

Chapter 01 — Introduction

Why Study Functional Programming in Java?

Recent versions of Java have introduced records, sealed types, and pattern matching. These features make the language appear closer to modern functional languages. At the beginning of this project, I held the expectation that:

“Perhaps Java is now expressive enough to support functional programming without friction.”

This expectation was reasonable — and incorrect.

Java can emulate certain patterns from functional languages, but it cannot offer the semantic foundations on which functional programming is built. Higher-kinded types do not exist, subtyping dominates the type system, and generics are erased at runtime. These constraints limit what can be expressed cleanly.

However, this limitation became the starting point of the book.

Attempting to write functional programs within Java’s boundaries reveals something essential:

Functional programming is not merely a collection of idioms. It is better understood as a discipline centered on algebraic data types, pure composition, and interpretable program structures.

Java’s resistance to these ideas makes the underlying principles easier—not harder—to see.

Throughout this book, we explore several core functional abstractions:

  • algebraic data types (Either, Option, Try)
  • immutable data structures
  • State and IO as explicit effects
  • parser combinators
  • Free monads and interpreters
  • domain-specific languages and intermediate representations

Each abstraction exposes the same lesson:

Functional programming is a way to describe computations, not a way to organize classes.

This book is therefore not an argument for writing functional programs in Java. Rather, it uses Java intentionally as a constrained environment in which the structure of functional programming becomes clearer.

If this book succeeds, you will not conclude that Java is a good choice for functional programs.
You will instead understand why functional languages are designed differently,
and why those designs matter.

Chapter 02 — Java 17 vs Java 21 — An FP-Oriented Comparison

Recent versions of Java introduce language features that make the language noticeably more hospitable to functional programming patterns.
However, the difference between “possible” and “comfortable” functional programming is significant.
This chapter clarifies what each version offers, and what functional abstractions become easier or remain awkward.

1. ADT Capability: Sealed Types vs. Open Hierarchies

Java 17

  • Introduces record and sealed classes.
  • Algebraic Data Types (ADTs) can be emulated, but require boilerplate.
  • Exhaustiveness is not enforced unless pattern matching is used carefully.

Java 21

  • Fully supports sealed hierarchies with pattern matching for both instanceof and switch.
  • ADT definitions become closer to their Scala/Haskell equivalents.
  • Compiler can enforce totality across patterns.

FP Impact

  • Core FP constructs such as Option, Either, Try, List, and Tree map naturally to ADTs.
  • Java 21 reduces syntactic friction, but deeper semantic FP features remain absent.

2. Pattern Matching: Toward Expression-Oriented Code

Java 17

  • Pattern matching is limited to instanceof.
  • Decomposition requires manual casting or visitor patterns.
  • FP-style recursion is verbose.

Java 21

Pattern-switch expressions allow expressive decomposition:

return switch (opt) {
  case Some(var v) -> f(v);
  case None _      -> defaultValue;
};

FP Impact

  • Removes a large amount of ceremony.
  • Enables clear interpreter and DSL implementations.
  • Shifts Java closer to an expression-oriented language, a key requirement for FP.

3. Records and Immutability

Java 17

  • record provides concise immutable data structures.
  • Plays well with FP-style case classes.
  • Immutability is shallow, but adequate for ADTs.

Java 21

  • Integrates cleanly with pattern matching and sealed types.

FP Impact

  • Records act as constructors for ADT nodes.
  • Combined with sealed, they form the foundation for FP modeling in Java.

4. How These Features Enable FP Constructs

Java 21 enables:

  • Expressive ADT modeling
  • Pure interpreter-style programming
  • Safer recursion via exhaustive pattern matching
  • Declarative, expression-based computation

These limitations are not accidental.

Java is fundamentally designed as an object-oriented, imperative language. Its type system, syntax, and standard library are optimized for explicit control flow, nominal typing, and long-term backward compatibility.

From this perspective, it is natural that features such as:

  • higher-kinded types
  • FP-oriented type inference
  • monadic syntax
  • comprehensive functional standard library

fall outside Java’s core design priorities.

Summary

Java 21 brings the language significantly closer to an FP-friendly environment,
but the underlying model remains object-oriented and nominally typed.
These additions enable functional-style programming, without changing Java’s conceptual center.

Its improvements matter for pedagogy and DSL construction,
yet they do not turn Java into a functional programming language.

This sets the stage for the next chapters: understanding how FP abstractions
can be expressed despite the host language, and what we learn from those attempts.

Chapter 03 — Option / Either / Try — Algebraic Data Types in a Nominal World

Algebraic Data Types (ADTs) form the basic vocabulary of functional programming.
They allow us to classify computations by their possible shapes, and they allow the compiler to enforce these shapes.
In this chapter, we reconstruct three essential ADTs in Java:

  • Option<A> — presence or absence
  • Either<L, R> — branching structure
  • Try<A> — exception-safe computation

Although these constructs are simple, they expose the core tension between FP semantics and Java’s nominal type system.

3.1 What ADTs Represent

An ADT is defined not by its methods, but by its constructors.
Option<A> is the sum of two cases:

Option<A> = Some(a) | None

Similarly:

Either<L, R> = Left(l) | Right(r)
Try<A>      = Success(a) | Failure(e)

Each of these structures encodes a logical space of possibilities.
Pattern matching allows us to make this structure explicit.

3.2 Expressing ADTs in Java 17

Java 17 supports records and sealed interfaces, enabling a minimal ADT style:

public sealed interface Option<A> permits Some, None {}

public record Some<A>(A value) implements Option<A> {}
public record None<A>()        implements Option<A> {}

Conceptually, this is close to Scala, but several limitations remain:

  • Generics are erased at runtime.
  • Exhaustiveness checking is partial.
  • Pattern matching on switch is not fully supported.

This results in some additional ceremony in fold/map/flatMap implementations, reflecting Java’s nominal type model, but the semantics remain clear and predictable.

3.3 Improvements in Java 21

With Java 21:

  • Pattern matching is available in switch.
  • Deconstruction patterns apply directly to records.
  • The compiler can check exhaustiveness for sealed hierarchies.

This allows expressive FP-style code:

return switch (opt) {
  case Some(var v) -> f.apply(v);
  case None _      -> defaultValue;
};

ADTs become more transparent, though not as concise as in FP-native languages.

3.4 Option — Modeling Optionality Explicitly

Intent

Option<A> explicitly represents absence, removing the need for null.

Essential operations

  • map — transform inside the container
  • flatMap — sequence optional computations
  • getOrElse — recover default values
  • fold — deconstruct the ADT (core abstraction)

Example

Option<Integer> x = some(10)
    .map(v -> v + 1)
    .flatMap(v -> v > 10 ? some(v) : none());

Interpretation

Option expresses non-failure absence.
It is appropriate when “no value” is a valid, expected result—not an error condition.

3.5 Either — Expressing Structured Alternatives

Either<L, R> carries two possible shapes:

  • Left<L> typically represents error or alternative path
  • Right<R> represents success or primary path

This ADT is essential for:

  • parser combinators
  • branch-sensitive computations
  • state machines
  • interpreter pipelines

Example

Either<String, Integer> result =
    parseInt("10")
      .map(i -> i + 1)
      .flatMap(i -> i < 20
          ? Either.right(i)
          : Either.left("Too large"));

Interpretation

Either exposes branching logic explicitly, making error paths visible in the type system.
This is a fundamental FP discipline: errors are values, not exceptions.

3.6 Try — Controlled Exceptional Computation

Try<A> captures Java exceptions in a pure ADT.

Motivation

Java’s built-in exception mechanism is:

  • invisible in the type system
  • non-compositional
  • side-effecting

Try restores structure:

Try<A> = Success(a) | Failure(exception)

Example

Try<Integer> t =
    Try.of(() -> Integer.parseInt("10"))
       .map(n -> n + 1)
       .recover(e -> 0);

Interpretation

Try is appropriate when exceptions must be handled locally and composed across transformations.

3.7 What These ADTs Reveal About Java

Before examining the limitations, it is worth emphasizing a positive and perhaps surprising result: Option, Either, and Try are pleasant to use in Java 21. With sealed interfaces, records, and pattern matching, these ADTs impose very little cognitive or syntactic burden. For many programs, especially those that do not attempt to abstract over higher-kinded types, Java 21 provides a sufficiently expressive substrate. In other words: if one stays at the level of concrete ADTs and does not pursue type-level abstraction, Java’s ergonomics are entirely acceptable.

Implementing these ADTs in Java clarifies several important points:

  1. fold is the central operation In Java 17, fold was the primary way to make the structure of an ADT explicit. Without pattern matching on switch, all structural recursion had to be expressed through library-level abstractions such as fold, map, and flatMap. In other words, fold carried the full weight of case analysis.

  2. FP relies on data constructors and explicit case analysis In Java’s nominal type system, this structure must be emulated explicitly, as generic variance and subtype relationships (for example, ? super / ? extends) do not naturally encode such cases.

  3. Java does not provide higher‑kinded types, which means abstractions such as Functor and Monad must be expressed explicitly rather than derived from the type system.

  4. Pattern matching substantially narrows the gap, though Java’s design remains oriented toward object‑centric composition.

  5. Error handling becomes explicit, which is a significant improvement over exceptions.

3.8 Summary

Option, Either, and Try form the conceptual foundation of all later chapters:

  • parser combinators rely on Either
  • State and IO rely on map/flatMap semantics
  • Free monads rely on ADTs to define instruction sets
  • DSL interpreters rely on structural recursion over ADTs

Understanding these data structures in Java clarifies the broader thesis of this book:

FP is the art of structuring computation through algebraic data types.
Java approaches this style with its own tools and trade‑offs, offering a practical—if distinct—path toward FP‑influenced design.

Chapter 04 — The State Monad

In functional programming, the State monad provides a disciplined way to model computations that carry state along a sequence of operations, without mutating variables. This chapter explores how to express this concept in Java, using immutable data structures and pure functions.

4.1 What Problem Does the State Monad Solve?

Many algorithms require some notion of state: counters, random number generators, accumulators, symbol tables, and so on.

In imperative Java, these are usually implemented through:

  • mutable fields,
  • shared objects,
  • side‑effects embedded in methods.

From an FP perspective, these techniques obscure data flow and make reasoning difficult.
The State monad provides a pure alternative:

  • State is passed explicitly, never hidden.
  • Each computation returns both a value and a new state.
  • Compositionality: complex stateful logic is built from smaller steps.

4.2 The State Monad Definition in Java

We adopt the canonical signature:

public record State<S, A>(Function<S, Tuple2<A, S>> run) {

    public <B> State<S, B> map(Function<A, B> f) {
        return new State<>(s -> {
            var result = run.apply(s);
            return Tuple.of(f.apply(result._1()), result._2());
        });
    }

    public <B> State<S, B> flatMap(Function<A, State<S, B>> f) {
        return new State<>(s -> {
            var result = run.apply(s);
            return f.apply(result._1()).run().apply(result._2());
        });
    }
}

Key points:

  • run encapsulates a computation from state S to a pair (A, S).
  • map transforms the value while keeping the state intact.
  • flatMap chains computations, threading state from one step to the next.

This design preserves purity while allowing sequential composition.

4.3 A Minimal Example: A Counter

A common example is a simple counter that increments as we evaluate expressions.

public static State<Integer, Integer> increment() {
    return new State<>(s -> Tuple.of(s, s + 1));
}

Using map and flatMap, we can chain operations:

State<Integer, Tuple2<Integer, Integer>> program =
    increment().flatMap(a ->
    increment().map(b ->
        Tuple.of(a, b)
    ));

Running:

var result = program.run().apply(0);
// result = ((0, 1), state = 2)

This illustrates the fundamental rule:

State flows purely through the computation without mutation.

4.4 Modeling Stateful Algorithms

The State monad becomes powerful when modeling logic such as:

  • recursive tree traversals that carry contextual data,
  • random number generators (RNG),
  • symbol table construction during parsing,
  • intermediate representations in compiler pipelines.

For example, a pseudo‑random generator:

State<Long, Long> nextLong = new State<>(seed -> {
    long newSeed = seed * 6364136223846793005L + 1;
    return Tuple.of(newSeed, newSeed);
});

Because both the value and the new seed are explicit, the computation is:

  • reproducible,
  • testable,
  • free of hidden side-effects.

4.5 Design Notes for Java

The State monad turns out to be one of the least problematic FP constructs to express in modern Java. Because its structure is simple—S → (A, S)—Java 21 provides all the tools needed:

  • records for lightweight immutable data containers,
  • lambdas for pure computations,
  • pattern matching for readability (when needed).

✔ Minimal friction

Unlike abstractions such as Free, or type-class–style polymorphism, State does not require higher-kinded types. Java’s parametric types are entirely sufficient, because State fixes the state parameter S and varies only the result type A. This means:

  • no encoding tricks,
  • no unsafe casts,
  • no boilerplate beyond what purity itself requires.

In practice, writing and composing State computations in Java 21 feels close to their Scala equivalents.

✔ What HKTs would enable—but are not required here

Higher-kinded types become relevant only when we want:

  • a unified abstraction over all monads,
  • generic combinators parameterized by a type constructor F<\_>,
  • a type-class-like syntax for Monad, Applicative, etc.

However, none of these are necessary to use State itself. For expressing deterministic state-threading in real-world algorithms (parsers, interpreters, random generators), Java’s type system is perfectly adequate.

✔ Remaining verbosity

The main friction points are incidental:

  • Java lambdas remain more verbose than Haskell/Scala,
  • Tuple types must be provided manually,
  • Lack of partial application requires nested lambdas.

These are ergonomic issues, not structural limitations.

Summary

The State monad offers:

  • predictable, explicit state threading,
  • referential transparency,
  • strong compositional properties.

It is particularly instructive when studying interpreter construction, compiler pipelines, or any domain where state must be tracked without sacrificing purity.

Chapter 05 — IO and Effect Suspension

Modern Java (particularly Java 21) offers enough expressive power to encode the essential FP effect patterns—IO, Reader, and Writer—without significant friction.
Records, lambdas, and pattern matching collectively allow these constructs to be implemented in a direct and readable manner.
This chapter examines how these effect abstractions work, why they matter, and how Java can express them cleanly.

5.1 Why effects must be suspended

A pure function always returns the same value for the same input.
Side effects—printing to the console, reading a file, mutating state—break this property because they depend on time and context.

FP does not forbid effects. Instead, it enforces discipline:

  • effects must be described, not executed immediately
  • effects must be composed before execution
  • effects must have one well-defined execution point

With IO, effects become referentially transparent: two identical IO values behave identically as descriptions of effects.

5.2 IO — Suspending effects

In Java 21, IO can be defined compactly using a record:

public record Io<A>(Supplier<A> thunk) {
    public A unsafeRun() { return thunk.get(); }

    public <B> Io<B> map(Function<? super A, ? extends B> f) {
        return new Io<>(() -> f.apply(unsafeRun()));
    }

    public <B> Io<B> flatMap(Function<? super A, Io<B>> f) {
        return new Io<>(() -> f.apply(unsafeRun()).unsafeRun());
    }
}

This structure closely mirrors IO implementations found in Scala or Haskell.

Why Java 21 works well here

  • record enables concise immutable wrappers
  • Lambdas naturally defer evaluation
  • map and flatMap create sequential effect chains
  • No higher-kinded types are needed

IO in Java 21 is therefore practical, expressive, and conceptually aligned with standard FP semantics.

5.3 Reader — Environment-passing computations

Reader represents computations that depend on some environment:

R → A

It offers an alternative to DI frameworks, favoring a simpler, explicit, and type-directed approach.

public record Reader<R, A>(Function<R, A> run) {
    public A apply(R env) { return run.apply(env); }

    public <B> Reader<R, B> map(Function<? super A, ? extends B> f) {
        return new Reader<>(env -> f.apply(run.apply(env)));
    }

    public <B> Reader<R, B> flatMap(Function<? super A, Reader<R, B>> f) {
        return new Reader<>(env -> f.apply(run.apply(env)).run.apply(env));
    }

    public static <R> Reader<R, R> ask() {
        return new Reader<>(env -> env);
    }

    public <B> Reader<R, B> local(Function<R, R> modify) {
        return new Reader<>(env -> run.apply(modify.apply(env)));
    }
}

Why Reader fits Java well

  • No higher-kinded types required
  • Very close to its Scala/Haskell counterparts
  • Expressive for configuration passing
  • Eliminates need for containers or global state

Reader is a strong example of FP abstractions fitting naturally within Java’s syntax and type system.

5.4 Writer — Accumulating logs

Writer captures a value plus an accumulated log:

(A, W)

Its Java 21 representation is compact:

public record Writer<W, A>(A value, W log, BinaryOperator<W> append) {
    public <B> Writer<W, B> map(Function<? super A, ? extends B> f) {
        return new Writer<>(f.apply(value), log, append);
    }

    public <B> Writer<W, B> flatMap(Function<? super A, Writer<W, B>> f) {
        Writer<W, B> next = f.apply(value);
        return new Writer<>(next.value, append.apply(log, next.log), append);
    }
}

Why Writer also works well in Java

  • Java collections (e.g., List<String>) naturally serve as logs
  • record eliminates boilerplate
  • append abstracts monoid behavior without type classes

Writer shows that Java can express FP accumulation patterns clearly and succinctly.

5.5 The shared structure: effectful computation as data

IO, Reader, and Writer share a unifying idea:

Effectful computations should be represented as values that can be combined before they are executed.

In Java 21, this model works smoothly:

  • pure wrappers (record)
  • first-class functions (Function, lambdas)
  • local reasoning via map and flatMap
  • explicit execution boundaries

These abstractions align cleanly with functional semantics while remaining practical for real-world Java development.

5.6 Summary

Java 21 provides a sufficiently expressive foundation for effect suspension.
IO, Reader, and Writer can be written with minimal ceremony, without advanced type-system features, and without deviating from their functional meaning.

These constructs complete the fundamental FP tools needed before moving on to more advanced abstractions such as parsers, interpreters, and—later in the book—free monads.

Chapter 06 — Functional Data Structures: List

In this chapter we introduce functional data structures in their canonical form. While Java provides List, ArrayList, and LinkedList, none of these are functional: they are mutable, operationally defined, and do not express structure in types.

A functional List is defined by two constructors only:

  • Nil — the empty list
  • Cons(head, tail) — an element followed by the rest of the list

This is the same structure as in Haskell or Scala, and underlies structural recursion.

6.1 The Algebraic Data Type

public sealed interface List<A> permits List.Nil, List.Cons {

    record Nil<A>() implements List<A> {}

    record Cons<A>(A head, List<A> tail) implements List<A> {}
}

This gives us:

  • Immutability by design
  • Total structural description of the data
  • A foundation for structural recursion

Compared to Java’s built‑in collections, the important difference is the absence of hidden mutation. All operations return new lists rather than modifying existing ones.

6.2 Basic Operations

The classical operations are:

  • prepend
  • map
  • foldRight and foldLeft
  • append
  • reverse

Example: map

public static <A, B> List<B> map(List<A> list, Function<A, B> f) {
    return switch (list) {
        case List.Nil<A> ignored -> new List.Nil<>();
        case List.Cons<A> cons   -> new List.Cons<>(f.apply(cons.head()), map(cons.tail(), f));
    };
}

Because the ADT is small and total, recursion is exhaustive — covering all possible cases — making missing cases structurally impossible.

6.3 Folding as the Core Abstraction

foldRight expresses the essence of structural recursion:

public static <A, B> B foldRight(List<A> list, B z, BiFunction<A, B, B> f) {
    return switch (list) {
        case List.Nil<A> ignored -> z;
        case List.Cons<A> cons   -> f.apply(cons.head(), foldRight(cons.tail(), z, f));
    };
}

Many operations—including map, length, and append—can be implemented via folds.

This is the “functional data structure lesson”:
data type dictates recursion scheme.

6.4 Performance Considerations

Functional lists have:

  • O(1) prepend
  • O(n) append
  • O(n) indexing

Unlike Java’s LinkedList, our ADT has no hidden machinery and no mutability. The tradeoff is intentional: structural clarity over operational tuning.

In FP languages, lists serve as semantic glue: they appear in interpreters, compilers, symbolic computing, and DSLs.

6.5 Why This Matters for FP in Java

Java 21’s sealed types make this pattern much more natural:

  • Exhaustive switch becomes safe
  • ADTs become explicit instead of accidental
  • Recursion is clearer and less error‑prone

Even so, Java’s pattern-matching remains less expressive than that of Scala, Kotlin, or Haskell, and its type system does not support higher-kinded abstraction. Within these constraints, however, the core ideas translate well, and the resulting code remains surprisingly clean.


Next we extend these ideas to Tree structures and structural recursion, which generalizes the same principles to branching shapes.

Chapter 07 — Tree and Structural Recursion

7.1 Trees as Algebraic Data Types

A tree is the canonical example of a recursively defined data structure.
In functional programming, trees allow us to express hierarchical computation, symbolic expressions, and evaluation rules.

A binary tree can be defined using two constructors:

  • Leaf — holds a single value
  • Branch — holds two subtrees

This mirrors the inductive definition of a tree and supports structural recursion: computations follow the shape of the data.

7.2 Defining a Tree ADT in Java

With Java 21, we can express this ADT directly:

public sealed interface Tree<A> permits Tree.Leaf, Tree.Branch {

    record Leaf<A>(A value) implements Tree<A> {}

    record Branch<A>(Tree<A> left, Tree<A> right) implements Tree<A> {}
}

This definition is:

  • closed — sealed, no uncontrolled subclassing
  • exhaustive — pattern matching can cover all variants
  • immutable — records enforce immutability
  • structural — matches the algebraic definition

7.3 Structural Recursion on Trees

Structural recursion is the process of:

  1. Handling the base case (Leaf)
  2. Recursively processing each subtree (Branch)

Example: computing the size of a tree

public static <A> int size(Tree<A> tree) {
    return switch (tree) {
        case Tree.Leaf<A> l -> 1;
        case Tree.Branch<A> b -> 1 + size(b.left()) + size(b.right());
    };
}

A more general form is fold, analogous to foldLeft for lists:

public static <A, B> B fold(
        Tree<A> tree,
        java.util.function.Function<A, B> leaf,
        java.util.function.BiFunction<B, B, B> combine
) {
    return switch (tree) {
        case Tree.Leaf<A> l -> leaf.apply(l.value());
        case Tree.Branch<A> b -> {
            B left  = fold(b.left(),  leaf, combine);
            B right = fold(b.right(), leaf, combine);
            yield combine.apply(left, right);
        }
    };
}

Examples:

int sum   = fold(tree, a -> a, (l, r) -> l + r);
int depth = fold(tree, a -> 1, (l, r) -> 1 + Math.max(l, r));
boolean containsX = fold(tree, v -> v.equals("x"), (l, r) -> l || r);

fold cleanly separates the shape of the data from the logic of computation.

7.4 Pattern Matching in Java 21

Java 21’s pattern matching makes Tree manipulation concise:

static <A> boolean contains(Tree<A> t, A target) {
    return switch (t) {
        case Tree.Leaf<A> l -> l.value().equals(target);
        case Tree.Branch<A> b ->
            contains(b.left(), target) || contains(b.right(), target);
    };
}

Though not as expressive as Scala or Haskell, the ergonomics for ADT-style trees are good enough for many practical cases.

7.5 FP Trees vs the OOP Composite Pattern

Traditional Java represents trees using the Composite Pattern:

  • abstract base class
  • Leaf/Node subclasses
  • virtual dispatch

FP takes a different view:

  • data is a closed algebraic structure
  • operations are external and total
  • pattern matching replaces polymorphic dispatch
  • structural recursion replaces visitors

The result is simpler reasoning, clearer invariants, and better exhaustiveness guarantees.

7.6 Summary

Trees illustrate how structural recursion emerges naturally from algebraic data types.
Java 21’s sealed types and pattern matching make these FP techniques directly accessible.

This chapter serves as a conceptual bridge to later chapters, where expression trees and Free monads extend this idea toward interpreter and compiler design.

Chapter 08 — Parser Combinator Basics in Java

Parser combinators are a powerful demonstration of how far we can go with "just functions" and immutable data. In this chapter we build the conceptual foundation: what a parser is, how it becomes a combinator, and why Java 21 is capable of expressing this style without external tools.

This prepares us for the next chapter, where we turn these ideas into a small but usable parsing library.

8.1 Why parser combinators?

Traditionally, parsers in Java are built using:

  • ad-hoc String manipulation,
  • regular expressions,
  • parser generators (ANTLR, JavaCC, etc.).

These approaches have drawbacks:

  • logic is often implicit (buried in regexes or grammar files),
  • refactoring requires tool support,
  • compositionality is weak.

Parser combinators take a different route:

  • a parser is just a function, wrapped in a convenient type,
  • small parsers are combined into larger parsers,
  • the resulting parser is an ordinary Java value.

This fits the overall theme of this book:

Treat behaviour as data. Compose it explicitly. Execute at the boundary.

8.2 The core parser type

Conceptually, a parser for values of type A is a function:

Input → Either[Error, (A, Input)]

In our Java code, we model this more concretely as a parser over String plus an index:

// Informal shape (the concrete type lives in fp.combinator.Parser):
// (String input, int position) -> Either<ParseError, Result<A>>

Where:

  • Result<A> holds the parsed value and the next input position,
  • ParseError describes what went wrong (and later, whether it is recoverable),
  • Either is our FP-style sum type from earlier chapters.

The Parser<A> type simply wraps this function together with combinators such as map, flatMap, and orElse.

The essential idea is:

  • a parser consumes a prefix of the input,
  • returns a value plus the remaining suffix,
  • or fails with a well-typed error.

8.3 Primitive parsers

Before we can compose parsers, we need a few primitive building blocks. Typical examples are:

  • char(c) — parse a single expected character,
  • digit() — parse a decimal digit,
  • string(s) — parse a fixed string,
  • eof() — succeed only at the end of input.

In our Java implementation, these are exposed as static factory methods on Parser or helper classes such as StringParser.

A schematic example for char(c) looks like this:

public static Parser<Character> ch(char expected) {
  return (input, pos) -> {
    if (pos < input.length() && input.charAt(pos) == expected) {
      return Either.right(new Result<>(expected, pos + 1));
    } else {
      return Either.left(ParseError.unexpectedChar(input, pos, expected));
    }
  };
}

This already exhibits the key pattern:

  • read from (input, pos),
  • on success, advance pos,
  • on failure, return a structured error without throwing.

8.4 From primitive parsers to combinators

A single primitive parser is not very interesting. The power comes from combinators—higher-order functions that take parsers as arguments and return new parsers.

The two fundamental ones are familiar by now:

  • map — transform the parsed value,
  • flatMap — sequence parsers where the second depends on the first.

Conceptually:

Parser<A> p;
Function<A, B> f;
Parser<B> q = p.map(f);

Function<A, Parser<B>> k;
Parser<B> r = p.flatMap(k);

With these in place, we can write code such as:

Parser<Integer> twoDigits =
    digit().flatMap(d1 ->
    digit().map(d2 ->
        10 * d1 + d2
    ));

This is structurally similar to the State and Io monads:

  • input plays the role of the state,
  • the parser’s result carries both a value and the new state (input position),
  • flatMap threads this state automatically.

In other words:

Parser is a specialised state monad over input streams.

8.5 Choice and repetition

To be useful, parsers must be able to express:

  • alternatives ("try this parser, or that one"),
  • repetition ("zero or more", "one or more").

We encode these as combinators as well.

Choice

Choice tries the first parser; if it fails without consuming input, it tries the second:

Parser<A> or(Parser<A> p, Parser<A> q);

This allows expressions like:

Parser<Character> sign =
    ch('+').orElse(ch('-'));

Later, we will refine this with the notion of recoverable vs fatal errors, and a commit combinator that fixes the branch. For now, we stay with the simpler, recoverable form of choice.

Repetition

Repetition combinators build on flatMap and choice:

  • many(p) — zero or more repetitions of p,
  • many1(p) — one or more repetitions of p.

Their implementation follows the typical pattern:

public static <A> Parser<java.util.List<A>> many(Parser<A> p) {
  return inputStart -> {
    var out = new java.util.ArrayList<A>();
    var input = inputStart;

    while (true) {
      var result = p.parse(input);
      if (result.isRight()) {
        var r = result.getRightUnsafe();
        out.add(r.value());
        input = r.next();
      } else {
        // on the first failure, stop and succeed with what we have
        return Either.right(new Result<>(out, input));
      }
    }
  };
}

The exact signature in our code is slightly different (we separate input and position), but the idea is identical.

8.6 How this feels in Java 21

Compared to FP-first languages, parser combinators in Java still have some syntactic overhead:

  • more explicit types,
  • more boilerplate around Either and Result,
  • less concise lambda syntax.

However, Java 21 gives us several advantages that earlier Java versions lacked:

  • records make Result and ParseError lightweight and immutable,
  • sealed types allow ParseError and ASTs to be closed and exhaustively matched,
  • pattern matching in switch improves readability of error handling.

Crucially, the core ideas survive translation almost unchanged:

  • parsers are pure values,
  • combinators compose them into larger grammars,
  • errors are data, not exceptions.

This chapter has focused on the shape of parser combinators.
In the next chapter, we will organise these ideas into a minimal reusable library, and address more advanced concerns such as fatal errors, backtracking control, and practical string parsing utilities.

Chapter 09 — Building a Minimal Parser Library

In Chapter 8, we introduced the core idea of parser combinators and demonstrated that Java 21 is expressive enough to encode functional parsing patterns: map, flatMap, or, structured errors, and chained combinators.

In this chapter, we turn those building blocks into a small but practical parser library. The goal is not to provide a complete parsing framework (Parsec, Megaparsec, Cats-parse, etc.) but to show how a carefully chosen set of primitives scales into a usable “mini-language” for writing parsers in a purely functional style.

9.1 Goals of This Minimal Library

A practical parser library must provide:

  1. Compositionality
    Complex parsers are built from smaller ones entirely through algebraic operators such as map, flatMap, or, and repetition.

  2. Structured errors
    End users should see where and why a parse failed.
    Our Parser.Error<S> type already encodes this.

  3. Controlled backtracking
    Some grammars are ambiguous, and naive backtracking leads to exponential blow-ups or surprising behaviour.
    Our fatal flag (and the commit() combinator) gives users fine-grained control.

  4. Deterministic semantics
    Every combinator must obey the “no consumption on failure” rule. This guarantees referential transparency and reliable debugging.

  5. Readable grammar definitions
    A parser library should allow grammars to be written declaratively, almost as if writing the grammar itself.

The Parser and StringParser modules we built earlier already satisfy these requirements; we now organise them into a cohesive whole.

9.2 Finalising the Core Types

Every parser has type:

(E, S) -> Either<Error<S>, Result<A,S>>
  • E — environment (immutable input or configuration)
  • S — state (cursor/index)
  • A — value

The standard FP interface emerges naturally:

Functor

map : (A -> B) -> Parser<E,S,A> -> Parser<E,S,B>

Monad

flatMap : (A -> Parser<E,S,B>) -> Parser<E,S,B>

Alternative

or : Parser<E,S,A> -> Parser<E,S,A> -> Parser<E,S,A>

Committed parsing

commit() : promote all failures to fatal

This small vocabulary is enough to express a surprisingly rich parsing DSL.

9.3 Why fatal Is Necessary in Real Grammars

Basic toy parsers can rely on implicit backtracking. But real grammars quickly run into ambiguity. Consider:

identifier  ::= letter (letter | digit)*
integer     ::= digit+

Given input:

123abc

Should this be parsed as:

  • integer = 123 followed by identifier = abc
    or
  • identifier = 123abc?

Different languages choose different resolutions.

If we implement both branches with naive backtracking:

integer().or(identifier())

the integer() parser will consume 1, 2, 3, then fail at a.
A naive combinator would then rewind the state and try identifier().
However, for many languages this behaviour is wrong.

To express “once I’ve committed to integer, do not backtrack into identifier”, we wrap it in:

integer().commit().or(identifier())

Thus fatal is a declarative signal:
“This path must not be undone.”

It upgrades a benign failure into a committed failure.

9.4 Standard Combinators

StringParser provides a standard suite of combinators:

  • Primitives
    chr, ch, string, digits, spaces

  • Repetition
    many, many1

  • Optional
    optional(p, default)

  • Delimited
    between(left, p, right)

  • Separated lists
    sepBy(p, sep)

  • Expression helpers
    chainl1(p, op) — left-associative operator chains

These mirror combinators in mature libraries such as Parsec/Megaparsec.

9.5 Worked Example: Arithmetic Expressions

We now build a parser for arithmetic expressions:

Expr ::= Term (("+" | "-") Term)*
Term ::= Factor (("*" | "/") Factor)*
Factor ::= integer | "(" Expr ")"

Lexical helpers

static final Parser<String,Integer,Character> plus =
    StringParser.ch('+').map(_c -> (BiFunction<Integer,Integer,Integer>) (x,y) -> x + y);

static final Parser<String,Integer,Character> minus =
    StringParser.ch('-').map(_c -> (BiFunction<Integer,Integer,Integer>) (x,y) -> x - y);

...

Recursive parser definition

Because Java lambdas are not self-referential, we wrap recursion in a supplier:

Supplier<Parser<String,Integer,Integer>> exprRef = new Supplier<>() {
  @Override
  public Parser<String,Integer,Integer> get() { return expr; }
};

Parser<String,Integer,Integer> factor =
    StringParser.integer()
      .or(StringParser.between(StringParser.ch('('), () -> exprRef.get(), StringParser.ch(')')));

Parser<String,Integer,Integer> term =
    StringParser.chainl1(factor, mulOp.or(divOp));

Parser<String,Integer,Integer> expr =
    StringParser.chainl1(term, plusOp.or(minusOp));

This demonstrates:

  • recursion
  • operator precedence
  • left associativity
  • use of chainl1

Running the parser

var r = expr.parse("1 + 2 * (3 + 4)", 0);
System.out.println(r);

Produces:

Right(Result(15, 13))

9.6 Error Messages and UX

All parsers eventually produce:

Either<Error<S>, Result<A,S>>

Errors include:

  • human-readable message
  • unexpected token
  • expected token
  • position
  • whether the error is fatal

A user can pretty print via:

err.pretty(Object::toString)

Labelled errors help:

expr.label(i -> "at " + i, "expression")

This produces:

expected expression at 5 but expected digit...

9.7 Summary — A Practical Parsing Kernel in Java

In this chapter we transformed a low-level Parser abstraction into a coherent miniature library capable of expressing:

  • recursion
  • sequences and alternatives
  • lexical tokenisation
  • committed parsing
  • operator-precedence grammars

Java 21’s enhanced pattern matching, records, and sealed types significantly improve readability and safety. Although not as concise as Scala or Haskell, Java 21 can host a clean, principled parser combinator framework suitable for DSLs, interpreters, and educational tools.

This minimal library also prepares the ground for Chapter 10, where we connect parsing to Free monads, AST construction, and interpreter design.

Chapter 10 — Free Monad Essentials

Free monads are often described as “an interpreter construction kit.”
In the previous chapters we implemented monads directly—Option, Either, Try, State, IO, Reader, and Writer.
All of them encode a specific effect in their data structure.

But Free is different.

Free does not encode any effect at all.
Instead, it encodes structure, leaving the meaning of a program to be supplied later by an interpreter.

This separation—“structure first, semantics later”—is the conceptual heart of FP architecture, compiler pipelines, and DSL design. And remarkably, Java can implement it with a modest amount of code, thanks to sealed interfaces and records — but not without friction. Java’s type system still requires occasional @SuppressWarnings (raw/unchecked), which reflects inherent limitations rather than mistakes in the Free design.

10.1 What Is a Free Monad?

Intuitively:

  • In a normal monad, flatMap executes the next step.
  • In a Free monad, flatMap merely builds a tree representing the next step.

Free transforms any functor F into a monad Free<F, A> without defining the meaning of F.

Functor F  ──(liftF)──▶  Free<F, A> (program description)
Interpreter ───────────▶  Result (meaning)

In other words:

Free can be viewed as a universal AST builder for effectful programs.

It gives you:

  • a uniform structure (Pure, Suspend, FlatMapped)
  • no commitment to semantics
  • multiple interpreters for the same program
    (evaluation, optimization, static analysis, codegen, visualization…)

This is why Free monads appear in:

  • compilers
  • interpreters
  • algebraic effects
  • structured logging
  • workflow engines
  • data pipelines
  • SQL/IR design
  • and all “Describe first, interpret later” systems

10.2 The Core Data Type

Our implementation consists of three constructors:

public sealed interface Free<F, A> permits
    Free.Pure, Free.Suspend, Free.FlatMapped {

    record Pure<F, A>(A value) implements Free<F, A> {}

    record Suspend<F, A>(F fa) implements Free<F, A> {}

    record FlatMapped<F, A, B>(
            Free<F, A> sub,
            Function<A, Free<F, B>> k
    ) implements Free<F, B> {}
}

Why these three?

  • Pure represents a completed computation.
  • Suspend wraps one step described by the functor F.
  • FlatMapped captures sequencing: “run sub, then feed the result into k.”

This is the entire structure of a program written in Free.

10.3 Building Programs with liftF

The essential constructor is:

static <F, A> Free<F, A> liftF(F fa) {
    return new Suspend<>(fa).flatMap(a -> new Pure<>(a));
}

This:

  1. wraps an instruction fa into a suspended node
  2. ensures the result type remains a proper monad (Free<F, A>)

liftF is how any DSL operation becomes a Free expression.

For example, in our arithmetic DSL:

Free<ExprF, Integer> expr =
    AddF.of(lit(1), lit(2)).lift()
        .flatMap(x -> MulF.of(lit(x), lit(3)).lift());

This is not executed yet.
Only a tree is built.

10.4 map and flatMap Build the AST

In normal monads:

  • map transforms values
  • flatMap executes the next step

In Free:

  • map wraps the continuation
  • flatMap creates a new tree node (FlatMapped)

Thus a program like:

expr.flatMap(f).flatMap(g).flatMap(h)

becomes a right-associated tree:

FlatMapped(
  sub = expr,
  k   = x -> FlatMapped(
            sub = f(x),
            k   = y -> FlatMapped(
                       sub = g(y),
                       k   = h
                   )
        )
)

A future interpreter can traverse and normalize this tree however it wants.

10.5 Interpreting Free: Step-by-Step Evaluation

The interpreter receives:

  • a Free program
  • an F → A function describing what a single instruction means

Evaluation is:

  1. Pattern-match on Pure, Suspend, or FlatMapped
  2. Handle each case
  3. Perform tail-recursive stepping with a small stack

Pseudo-logic:

while (true) {
    switch (node) {
        case Pure(a) -> return a;
        case Suspend(fa) -> return interpret(fa);
        case FlatMapped(sub, k) -> {
            if (sub is Pure)
                node = k.apply(sub.value());
            else if (sub is Suspend)
                node = k.apply(interpret(sub.fa()));
            else // sub is FlatMapped
                node = re-associate to right
        }
    }
}

This evaluator:

  • never grows the call stack
  • normalizes left-nested binds
  • provides predictable evaluation order

10.6 Why Free Matters for DSL Design

Free achieves something extremely valuable:

The DSL designer defines only syntax.
The interpreter author defines semantics later.

Meaning:

  • Want evaluation? Implement ExprF → Integer.
  • Want optimization? Implement ExprF → ExprF.
  • Want code generation? Implement ExprF → String.
  • Want type checking? Implement ExprF → Either<TypeError, Type>.

All from the same Free program.

This separation is the foundation of compiler design:

  • AST → Optimization passes → Codegen

And Free naturally embodies this pipeline in Java.

10.7 When Should You Use Free?

Use Free when:

  • You want a DSL whose semantics may change
  • You want multiple backends (evaluation, optimization, SQL gen, etc.)
  • You want to record the program structure
  • You want programs as data instead of executable logic

Avoid Free when:

  • Only one simple effect is needed
  • Performance is the primary concern
  • You do not need an explicit AST

10.8 Summary

Key points:

  1. Free builds program structure, not semantics.
  2. Pure, Suspend, and FlatMapped form the entire AST.
  3. liftF embeds DSL instructions into Free.
  4. map and flatMap build trees instead of executing logic.
  5. Interpreters supply meaning afterward.
  6. Free is ideal for DSLs, IRs, and compiler-like architectures.

Chapter 11 will apply these ideas to our Expr DSL.

Chapter 11 — Designing an Expr DSL Using Free

In Chapter 10 we built the conceptual foundation of the Free monad.
Now we will put that abstraction to work by designing a small arithmetic DSL.
This chapter demonstrates how Free enables a pure, declarative, and fully interpretable representation of computations — a miniature example of how real‑world compilers and IR pipelines are structured.

The goal is not to build a powerful expression language.
Instead, it is to show how:

  1. A DSL is defined using a functor (ExprF)
  2. DSL instructions are lifted into Free<ExprF, A>
  3. Programs become data structures (ASTs)
  4. Interpreters and optimizers operate on those structures

This is the smallest possible version of a compiler pipeline written in Java.

11.1 Defining the Expression Functor ExprF<A>

The functor ExprF<A> represents one step of computation in our DSL.
We model four arithmetic operations and a literal:

public sealed interface ExprF<A>
    permits ConstF, AddF, SubF, MulF, DivF, SumF {

    ExprF<?> map(Function<Object, Object> f);
}

Each instruction is a simple record:

public record ConstF(Integer value) implements ExprF<Integer> {}

public record AddF<A>(A left, A right) implements ExprF<Integer> {}

public record SubF<A>(A left, A right) implements ExprF<Integer> {}

public record MulF<A>(A left, A right) implements ExprF<Integer> {}

public record DivF<A>(A left, A right) implements ExprF<Integer> {}

// A variadic node (e.g., addition of many terms)
public record SumF<A>(List<A> values) implements ExprF<Integer> {}

Each constructor contains references to subexpressions, but not interpretations.

The map method exists only because Free requires ExprF to behave like a functor.
This method rewrites the child nodes but does not evaluate anything.

11.2 Lifting Instructions Into Free

Every DSL instruction must be lifted into a Free program:

static <A> Free<ExprF, A> liftF(ExprF<A> fa) {
    return Free.liftF(fa);
}

We then define smart constructors for convenience:

static Free<ExprF, Integer> lit(int n) {
    return liftF(new ConstF(n));
}

static Free<ExprF, Integer> add(Free<ExprF, Integer> a,
                                Free<ExprF, Integer> b) {
    return a.flatMap(x -> b.flatMap(y ->
            liftF(new AddF<>(x, y))));
}

static Free<ExprF, Integer> sum(List<Free<ExprF, Integer>> xs) {
    return sequence(xs).flatMap(vals ->
            liftF(new SumF<>(vals)));
}

These smart constructors do not compute anything.
They merely build nodes in a program tree.

11.3 Programs Are Now Pure Data (ASTs)

A simple program:

var expr =
    add(lit(1), lit(2))
        .flatMap(x -> mul(lit(x), lit(3)));

This does not run arithmetic.
It constructs a deeply nested Free<ExprF, Integer> value.
A future interpreter will decide how this tree should execute.

Free has now turned program logic into data.

This is the essence of DSL design.

11.4 Visualizing the AST

Our previous example desugars into:

FlatMapped(
  sub = Suspend(AddF(ConstF(1), ConstF(2))),
  k   = x -> Suspend(MulF(ConstF(x), ConstF(3))))

Free ensures:

  • The order of operations is explicit
  • The AST is structurally normalized
  • No Java-side side‑effects occur during construction

This is precisely the kind of structure you want before writing an interpreter or optimizer.

11.5 Building Utility: sequence / traverse

Many DSLs require combining lists of subcomputations.
We implement sequence using the Free monad’s own structure:

static <A> Free<ExprF, List<A>> sequence(List<Free<ExprF, A>> xs) {
    Free<ExprF, List<A>> acc = Free.pure(new ArrayList<>());

    for (var x : xs) {
        acc = acc.flatMap(list ->
              x.flatMap(v -> {
                  list.add(v); // Although this uses a mutable list internally,
                               // the mutation is not observable
                               // outside the construction process.
                  return Free.pure(list);
              })
        );
    }
    return acc;
}

This lets us express a variadic SumF node easily.

11.6 What We Have Achieved

By defining:

  • a functor (ExprF)
  • a lifting function (liftF)
  • smart constructors (e.g., lit, add, sum)
  • program combinators (flatMap, sequence)

…we have built a real DSL inside Java.

This DSL:

  • captures structure independently of meaning
  • builds an AST naturally through monadic composition
  • supports multiple interpreters (evaluation, optimization, codegen)
  • mirrors compiler architecture on a small scale
  • demonstrates the conceptual power of Free monads

In the next chapter, we provide these interpreters — thereby giving our DSL meaning.

11.7 Summary

  1. ExprF<A> defines one step of a computation.
  2. Free turns these steps into a composable program.
  3. Smart constructors make DSL usage ergonomic.
  4. Programs become first‑class data (ASTs).
  5. This separation of structure and semantics is the core of DSL/IR design.

Chapter 12 will interpret, optimize, and compile this DSL.

Chapter 12 — Interpretation, Optimization, and Code Generation

In Chapters 10 and 11, we built:

  • a functor describing expression syntax (ExprF)
  • a Free monad creating programs as ASTs
  • a set of smart constructors (const, add, mul, …)

We now complete the compiler pipeline by giving our DSL meaning.

This chapter implements:

  1. Evaluation (Interpreter)
  2. Optimization (Constant Folding)
  3. Code Generation (pretty-printing / Java-like source)

These three phases demonstrate how a Free-based DSL naturally supports
multiple semantics without changing the DSL itself.

12.1 Revisiting the ExprF Constructors

Our expression language now consists of:

public sealed interface ExprF<A>
    permits ConstF, AddF, SubF, MulF, DivF, SumF {
    ExprF<?> map(Function<Object,Object> f);
}

public record ConstF(Integer value) implements ExprF<Integer> {}

public record AddF<A>(A left, A right) implements ExprF<Integer> {}
public record SubF<A>(A left, A right) implements ExprF<Integer> {}
public record MulF<A>(A left, A right) implements ExprF<Integer> {}
public record DivF<A>(A left, A right) implements ExprF<Integer> {}

public record SumF<A>(List<A> values) implements ExprF<Integer> {}

These constructors describe syntax only.
They say nothing about how expressions should be evaluated or optimized.

This is exactly what makes Free powerful.

12.2 Interpreter: Evaluating ExprF into Integer

public final class ExprInterpreter {

    public static Integer eval(Free<ExprF, Integer> program) {
        return step(program);
    }

    private static Integer step(Free<ExprF, Integer> node) {
        while (true) {
            if (node instanceof Free.Pure<ExprF, Integer> p) {
                return p.value();
            }

            if (node instanceof Free.Suspend<ExprF, Integer> s) {
                return evalF(s.fa());
            }

            if (node instanceof Free.FlatMapped<ExprF, ?, Integer> fm) {
                var sub = fm.sub();
                var k = fm.k();

                if (sub instanceof Free.Pure<ExprF, ?> sp)
                    node = k.apply(sp.value());

                else if (sub instanceof Free.Suspend<ExprF, ?> ss)
                    node = k.apply(evalF(ss.fa()));

                else if (sub instanceof Free.FlatMapped<ExprF, ?, ?> sfm)
                    node = sfm.sub().flatMap(
                        x -> sfm.k().apply(x).flatMap(fm.k())
                    );

                else
                    throw new IllegalStateException("Unexpected Free node");
            }
        }
    }

    private static Integer evalF(ExprF<?> f) {
        return switch (f) {
            case ConstF c -> c.value();
            case AddF<?> a -> ((Integer) a.left()) + ((Integer) a.right());
            case SubF<?> a -> ((Integer) a.left()) - ((Integer) a.right());
            case MulF<?> a -> ((Integer) a.left()) * ((Integer) a.right());
            case DivF<?> a -> ((Integer) a.left()) / ((Integer) a.right());
            case SumF<?> s -> ((List<Integer>) s.values())
                                .stream().reduce(0, Integer::sum);
        };
    }
}

What this shows

  • Evaluation semantics are defined after DSL definition.
  • DSL programs remain pure data structures.
  • Interpreters are replaceable and composable.

This is exactly the separation found in real-world compilers.

12.3 Optimization: Constant Folding

public final class ExprOptimizer {

    public static Free<ExprF, Integer> optimize(Free<ExprF, Integer> program) {
        return program.resume()
            .fold(
                ExprOptimizer::optimizeF,
                Free::pure
            );
    }

    private static Free<ExprF, Integer> optimizeF(ExprF<?> f) {
        return switch (f) {
            case ConstF c -> Free.pure(c.value());

            case AddF<?> a -> {
                var l = (Integer) a.left();
                var r = (Integer) a.right();
                yield Free.pure(l + r);
            }

            case MulF<?> m -> {
                var l = (Integer) m.left();
                var r = (Integer) m.right();
                yield Free.pure(l * r);
            }

            default -> Free.liftF((ExprF<Integer>) f);
        };
    }
}

Observations

  • Optimization is purely structural.
  • Side-effect–free design makes rewrites trivial.
  • More passes can be added without touching the DSL.

This is how compilers like LLVM organize transform pipelines.

12.4 Code Generation: Turning ExprF into a String

public final class ExprCodegen {

    public static String toSource(Free<ExprF, Integer> program) {
        return render(program);
    }

    private static String render(Free<ExprF, Integer> node) {
        if (node instanceof Free.Pure<ExprF, Integer> p)
            return p.value().toString();

        if (node instanceof Free.Suspend<ExprF, Integer> s)
            return renderF(s.fa());

        if (node instanceof Free.FlatMapped<ExprF, ?, Integer> fm) {
            throw new IllegalStateException(
                "FlatMapped should be normalized before codegen"
            );
        }

        throw new IllegalStateException("Unexpected Free node");
    }

    private static String renderF(ExprF<?> f) {
        return switch (f) {
            case ConstF c -> c.value().toString();
            case AddF<?> a -> "(" + a.left() + " + " + a.right() + ")";
            case SubF<?> a -> "(" + a.left() + " - " + a.right() + ")";
            case MulF<?> a -> "(" + a.left() + " * " + a.right() + ")";
            case DivF<?> a -> "(" + a.left() + " / " + a.right() + ")";
            case SumF<?> s ->
                    "(" + String.join(" + ",
                        ((List<Integer>) s.values())
                            .stream().map(Object::toString).toList()
                    ) + ")";
        };
    }
}

Highlights

  • The backend is replaceable.
  • No changes needed in the AST.
  • The same DSL can target SQL, JSON, or bytecode-like IR.

12.5 Example: Full Pipeline

var expr =
    add(const_(1), const_(2))
        .flatMap(x -> mul(const_(x), const_(3)));

System.out.println(ExprInterpreter.eval(expr));
System.out.println(ExprCodegen.toSource(expr));
System.out.println(
    ExprInterpreter.eval(
        ExprOptimizer.optimize(expr)
    )
);

Output

9
((1 + 2) * 3)
9

12.6 Summary

This chapter demonstrated the full lifecycle of a Free-based DSL:

PhasePurpose
InterpreterEvaluate the expression
OptimizationSimplify the AST
Code generationEmit textual representation

The key takeaway:

Free allows the DSL’s structure and meaning to evolve independently.

This pattern appears in real compilers, database engines, IR pipelines, and DSL interpreters.

Note on Java’s Type System

The implementation of Free in this chapter necessarily uses @SuppressWarnings({"rawtypes", "unchecked"}) in several places. This is not a flaw in Free itself, but a direct consequence of a fundamental limitation in Java’s type system:

  • Java does not support higher-kinded types (HKT)
  • therefore, types such as Free<F, A> cannot preserve the shape of A inside nested combinators like flatMap
  • Java erases the essential type information that Scala or Haskell retain

Free monads heavily rely on HKTs to express nested computations with accurate typing. In Java, we must sacrifice some type precision and manually maintain invariants using casts.

This chapter keeps the implementation correct and safe, but at the cost of noise.

Free, Interpreter, Optimizer, and Codegen can be implemented in Java, but not without noise: explicit casts, erased type parameters, and suppressed warnings are unavoidable due to the absence of higher-kinded types.

One may choose to ignore this noise and continue in Java for ecosystem stability, or embrace a language like Scala where these constructs are natural and fully type-safe. The choice depends on whether the goal leans more toward engineering pragmatism or language expressiveness. Both paths are valid — they simply serve different purposes.

Chapter 13 — Why FP Matters Beyond Syntax

Functional Programming is often introduced through terminology — immutability, monads, purity, recursion. But its deepest contribution is conceptual:

Functional Programming is not about syntax — it is about building structures in which programs become data, and meaning becomes explicit.

This chapter brings that perspective into focus.

13.1 FP as a Design Philosophy

FP is often introduced as a collection of patterns — immutability, purity, monads, combinators.

But the essence is simpler:

FP forces the programmer to externalize semantics.

When effects are explicit (IO), when state transitions are modeled as values (State), when branching is a data structure rather than a statement (Either), the program becomes something that can be:

  • analyzed
  • interpreted
  • optimized
  • transformed
  • or executed in multiple ways

This is the core meaning of “Structure Creates Freedom.”

A structured program is more reusable, more testable, and more predictable than one whose semantics are buried inside mutation and side effects.

13.2 What FP-in-Java Reveals About Language Boundaries

Attempting FP in Java (even with Java 21 features) is an instructive experiment.

We learned that:

  • Java can represent ADTs (sealed interfaces, records).
  • Java can encode the fundamental monads.
  • Java can build an interpreter and a Free DSL.

But:

  • higher‑kinded types do not exist
  • type inference is minimal
  • expressive DSLs require workarounds that Scala or Haskell do not

This leads to an important conceptual discovery:

Language boundaries are not defined by what you can express,
but by what you can express without noise.

Java’s boundary is not expressiveness — it is ergonomics.

The FP core works, but the noise grows as the abstraction level rises. Free, DSLs, and optimizers highlight this boundary sharply.

13.3 When Programs Become Data

The culmination of FP techniques is the realization that:

Programs are data, and interpreters are evaluators for those data.

This book’s Expr DSL demonstrated precisely this:

  • A program is constructed from ADT nodes.
  • Free lifts the nodes into a compositional AST.
  • An interpreter consumes the AST and produces a result.
  • An optimizer consumes the same AST and produces a new AST.
  • A code generator consumes the AST and emits another representation
    (e.g., SQL, bytecode, internal instructions).

This is not FP for elegance.
This is FP as the foundation for compiler design, query engines, agent frameworks.

Once programs become data:

  • we separate what is built from how it is executed
  • we gain replayability, debuggability, determinism
  • we can build optimizers and compilers without changing user code
  • we create systems whose behavior can be reasoned about, stored, transmitted, or regenerated

This is the deepest link between FP and system design.

13.4 Closing Perspective

FP in Java was never about stylistic preference.
It was an investigation:

  • What happens when we make semantics explicit?
  • What new capabilities arise when effects become values?
  • How far can we push the JVM without HKTs?
  • At what point do language boundaries matter?
  • How does a DSL naturally evolve into a structured, language-neutral form of a program?

The experiments in this book demonstrate:

FP becomes valuable precisely when programs must be treated as data.

This principle underlies compilers, distributed systems, data processing pipelines, and modern agent frameworks.