The Interpreter of the Progenitor
Evaluate a domain-specific language of mystical logic.
✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Interpreter
ARCANUM SCHOOL: Divination // Rune Translation
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// CODEX INCANTATION //
datatype expr =
Num of int
| Add of expr * expr
| Multiply of expr * expr
fun eval (Num n) = n
| eval (Add (e1, e2)) = eval e1 + eval e2
| eval (Multiply (e1, e2)) = eval e1 * eval e2
(* A magical formula: (3 + 4) * 2 *)
val formula = Multiply(Add(Num 3, Num 4), Num 2)
val powerLevel = eval formula
The Interpreter pattern is the very soul of functional programming languages like SML. Abstract Syntax Trees (ASTs) are trivially expressed via algebraic datatype declarations. A simple recursive eval function patterned-matches over the datatype to resolve the grammar, granting life to embedded domain-specific languages and esoteric rune scripts.
Runic Tags:
#datatypes
#abstract syntax trees
#evaluation