M4 · Trees and RecursionSession 8-9BehavioralReshaped in KotlinOutline

Intent. Represent a grammar as a class hierarchy and evaluate sentences written in it.

In Kotlin. A sealed AST plus a recursive eval function falls out naturally.

Composite applied to a grammar. Build the sentence as a tree of expression nodes and evaluate recursively. Rare in application code and unavoidable the moment you need a filter language, a rules engine, or a query DSL of your own.

Structure

classDiagram
    class Expression {
        <<interface>>
        +interpret(ctx)
    }
    class NumberLiteral {
        -value
        +interpret(ctx)
    }
    class Add {
        -left: Expression
        -right: Expression
        +interpret(ctx)
    }
    class And {
        -left: Expression
        -right: Expression
        +interpret(ctx)
    }
    Expression <|.. NumberLiteral
    Expression <|.. Add
    Expression <|.. And
    Add o--> Expression : recurses

Telling It Apart

Patterns whose structure looks the same but whose intent does not. See the Confusing Pairs reference.

  • Composite — Treat individual objects and compositions of objects uniformly.