Examples

Click through for semantically highlighted source.

Association lists

Lookup, extension, update, deletion, and a small phone-book example over lists of pairs.

librarylists

Bidirectional Type Checking & Local Type Inference

Bidirectional type checking system following Dunfield & Krishnaswami and Pierce & Turner. Separates typing into Checking mode (Γ ⊢ e ⇐ τ) and Synthesis/Inference mode (Γ ⊢ e ⇒ τ). Enables clean unannotated λ-abstractions, first-class annotations, constructors (pairs, sums), let-bindings, and subsumption with subtyping (e.g. Nat <: Int).

bidirectionaltype-inferencesubsumptionlocal-inferencehoas

The CEK Abstract Machine

Implementation of the CEK (Control, Environment, Kontinuation) abstract machine of Felleisen and Friedman. Evaluates higher-order functional programs without term substitution by using explicit variable environments and continuation stacks. Includes step transitions, machine run to completion, and equivalence checking against standard big-step substitution evaluation.

abstract-machinecekoperational-semanticscontinuationsenvironments

0-CFA Control Flow Analysis for Higher-Order Programs

0-CFA (0th-order Control Flow Analysis) for higher-order functional programs formulated as abstract interpretation. Computes abstract closure values, models closure environments to capture lexical variable flows across nested higher-order applications, and statically reconstructs the interprocedural call graph.

cfastatic-analysisabstract-interpretationflow-analysiscall-graph

Closure Conversion & Defunctionalization

Closure conversion and defunctionalization compiler transformations. Converts higher-order functions with free variables into closed code pointers paired with explicit environment tuples. Demonstrates compilation of open lambda terms into first-order representations suitable for low-level execution, and verifies operational equivalence with the source program.

compilerclosure-conversiondefunctionalizationcode-generation

Coinduction & Bisimulation via Hypothetical Reasoning

Computing greatest fixpoints and verifying bisimulations on infinite streams and circular state graphs using hypothetical implications (=>) as coinductive hypotheses.

coinductionbisimulationstreamsgreatest-fixpointhypothetical

Combinatory Logic & Bracket Abstraction

SKI combinatory logic, bracket abstraction compiling HOAS lambda abstractions into SKI combinator graphs using higher-order patterns, and combinator graph reduction.

combinatorsbracket-abstractionskicompilationhoas

Control Combinators & Meta-Level Search Control

Fundamental control combinators (once, ifte, call, unless, ignore, repeat_n, and_then, or_else) built from Prolog cut (!), failure, and first-class goal variables of type o. Demonstrates how higher-order logic programming seamlessly manipulates goals as first-class citizens.

librarycutextra-logicalhigher-ordercontrol

CPS and A-Normal Form (ANF) Transformations

Continuation-Passing Style (CPS) and A-Normal Form (ANF) transformations using HOAS and meta-continuations to eliminate administrative redexes and flatten nested subexpressions.

cpsanfcompilertransformationhoas

Definite Clause Grammars (DCG)

Definite Clause Grammars implemented using difference lists, showcasing natural language parsing with subject-verb number agreement, and an arithmetic expression parser building ASTs with operator precedence.

dcggrammarparsingdifference-listsnlp

HOAS and de Bruijn Conversion

Bidirectional conversion between Higher-Order Abstract Syntax (HOAS) and first-order de Bruijn indexed terms using hypothetical reasoning, along with shifting, substitution, and evaluation on de Bruijn terms.

hoasdebruijnsyntaxrepresentationhypothetical

Dependent Types & Mini-LF (λΠ-Calculus)

Implementation of the λΠ-calculus (the type-theoretic core of LF and Martin-Löf Type Theory) with dependent function types (Π(x:A). B(x)), indexed type families (length-indexed vectors vec A n), definitional term conversion in types, and dependent type checking with hypothetical contexts.

dependent-typeslflambda-pivectortype-familieshoas

Dungeon Adventure

Interactive text-based dungeon adventure. Explore chambers, collect keys, search for hidden treasures using PRNG, unlock the ancient vault, and escape!

gameadventureinteractive-fictionlogicpuzzles

System F<: (Bounded Quantification & Subtyping)

System F<: with kernel subtyping and bounded universal quantification (∀X <: U. T), representing the formal core of the POPLmark Challenge. Features contravariant arrow subtyping, reflexive and transitive subtyping, higher-order type-level binders, syntax-directed subsumption, and hypothetical subtyping contexts (pi x\ sub x Bound => ...).

f-subsubtypingbounded-quantificationpoplmarkhoas

First-Order Logic Sequent Calculus Prover

Automated theorem prover for first-order logic using Gentzen's sequent calculus LK/LJ, leveraging meta-level eigenvariables (pi) for universal quantifiers on the right and existential quantifiers on the left.

logicsequent-calculusfirst-ordereigenvariablesautomated-theorem-proving

Game Library

Standard library for building text-based games in lambda-Prolog: PRNG operations, string conversions, 2D matrix utilities, and ASCII board renderers.

gameslibraryprngasciirenderinggrid

The Archmage's Grimoire

Tactical spellcrafting roguelike running on the lambda-Prolog game shell. Features higher-order abstract syntax (HOAS) spells, beta-reduction over targets, hypothetical battlefield auras (=>), higher-order pattern matching counterspells, and a modular dual-pane ASCII interface.

gamehoashigher-orderroguelikecombatmagicbeta

Hidden Accumulator & Scoped Helper Predicates

Demonstrates information hiding and local helper encapsulation using hereditary Harrop implication (=>) and local declarations. Implements a linear-time tail-recursive list reversal where the accumulator predicate (rv) exists only during the execution of reverse and is completely hidden from caller modules.

sigmaimplicationhierarchyinformation-hidinghypothetical

Hoare Logic & Dijkstra's Weakest Precondition Calculus

Axiomatic program verification for an imperative While language using Hoare triples {P} C {Q} and Dijkstra's backward predicate transformer (Weakest Precondition wp). Automatically generates and discharges verification conditions (VCs) for loop invariants, assignment backward substitution, and state assertions.

hoare-logicprogram-verificationweakest-preconditionvcgformal-methods

Untyped λ-calculus

HOAS encoding of the untyped λ-calculus: evaluation, copy/subst, one-step β, size, Church numerals, and the I/K/S combinators.

libraryhoasbeta

Higher-Order Pattern Unification & Symbolic Calculus

Second-order symbolic differentiation and algebraic simplification exploiting higher-order patterns (Lλ) where meta-variables denote functions and eigenvariables enable reasoning under binders.

hopusymbolicdifferentiationsimplificationhigher-order

Hypothetical reasoning

Graph reachability by hypothetically adding edges with =>. A triangle lemma, a detour through a fresh node, and the fact that installed clauses do not leak past the implication.

implicationhierarchy

Hypothetical Scoping & Interpreter

Interpreter for an imperative/functional expression and statement language demonstrating block scoping, lexical variable shadowing, and local environments modeled directly through hypothetical implications (=>).

interpreterscopehypotheticalimperativeshadowing

Call-by-Need & Lazy Evaluation (Launchbury's Semantics)

Call-by-need lazy operational semantics based on Launchbury's natural semantics for lazy evaluation. Models sharing and memoization via a heap of suspended thunks. When a shared variable is demanded, its thunk is evaluated and the heap is updated in-place with the normalized value, ensuring shared expressions are computed at most once.

lazy-evaluationcall-by-needheapthunksmemoizationsharing

Linear and Substructural Type System

A linear type system based on Girard's linear logic and Wadler's "Linear Types Can Change the World". Enforces resource tracking by ensuring that linear values (capabilities, file handles, channels) are consumed exactly once. Demonstrates context consumption, linear functions (A ⊸ B), multiplicative tensor pairs (A ⊗ B), and prevention of double-spend and leaks.

linear-logicsubstructuralresource-trackingcontext-splitting

Lists

Standard list library — constructors, membership, splits, zips, permutation, sorting, difference lists, and pair helpers.

librarylistshorn

Higher-order maps and folds

mapfun, mappred, foldr, foldl, filter, partition, take_while, qsort, and related combinators, plus a small census example.

libraryhigher-order

Modal Logic & Kripke Semantics

Propositional modal logic (Box and Diamond) evaluated over Kripke models where worlds, accessibility relations, and frame conditions (K, T, S4, S5) are modeled directly with hypothetical implication and universal goals.

logicmodalkripkeaccessibilityhypothetical

Integers

Integer helpers on the pervasive @int@ type: comparisons, gcd, exponentiation, factorial, Fibonacci, and a tiny expression evaluator.

libraryarithmetic

Natural Deduction & Curry-Howard Proof Terms

Intuitionistic propositional natural deduction where proof terms are verified via Curry-Howard isomorphism, using hypothetical reasoning to introduce assumptions and eigenvariables for local hypothesis scoping.

logicnatural-deductioncurry-howardproof-termsintuitionistic

Nomos: The Logic Magistrate

Rule-hacking jurisprudence puzzle game running on the lambda-Prolog game shell. Features dynamic axiomatic physics via hypothetical implication (=>), proof-theoretic consistency checks and universal entity conservation via pi, and second-order predicate quantification over game properties.

gamelogicjurisprudencepuzzleshypotheticalpinomic

Options

The option type — none / some — with map, default, and conversion from a succeeding goal.

librarydatatypes

The π-Calculus & Scope Extrusion

Encoding of the polyadic/monadic π-calculus following Dale Miller's foundational work on higher-order process calculi. Restriction (νx. P) and input prefixes (x(y). P) are represented via HOAS, using meta-level quantification (pi) for fresh channel creation. Features a labeled transition system (LTS), reaction semantics, and channel scope extrusion.

pi-calculusconcurrencyprocess-calculihoasscope-extrusion

Formulas and prenex form

Object-language formulas with HOAS binders, NNF, prenex form, size, occurrence, closedness, and instantiation.

libraryhoaspi

Result & Either Standard Library

Standard library module for Result/Either types: ok and err constructors, monadic bind (and_then), functor mapping (map_ok, map_err), safe unwrapping, list partitioning, and sequence aggregation.

resulteitherlibrarystdliberror-handling

Information Flow Control & Security Typing (Volpano-Smith)

Information flow control following the Volpano-Smith-Irvine sound type system. Enforces confidentiality and non-interference through a security lattice (Low ⊑ High). Prevents explicit flows (Low := High) as well as implicit flows through control structures (branching on High and assigning to Low) via a tracked program-counter security level (pc).

securityinformation-flownon-interferencelatticetype-systems

Separation Logic & Local Heap Reasoning

Separation logic following O'Hearn, Reynolds, and Yang for local reasoning about mutable heaps. Implements points-to assertions (l ↦ v), the empty heap assertion (emp), spatial separating conjunction (P ∗ Q) via disjoint heap partitioning, the Frame Rule, and verification of pointer mutations and swaps.

separation-logicheappoints-toseparating-conjunctionframe-rule

Binary Session Types & Protocol Verification

Binary session types following Honda, Vasconcelos, and Yoshida. Enforces structured communication protocols on bidirectional channels through session types: send (!T. S), receive (?T. S), internal choice / selection (+{left: S1, right: S2}), external choice / branching (&{left: S1, right: S2}), and termination (end). Implements protocol duality, process typing, and session fidelity verification.

session-typesconcurrencyprotocolsdualitycommunication-safety

Finite sets

Finite sets as lists without regard to order: algebra, tests, powerset (small), and conversion from lists.

librarylists

Small-Step Reduction & Evaluation Contexts

Small-step Structural Operational Semantics (SOS) with evaluation contexts E[·] following Wright & Felleisen. Features explicit redex decomposition and plug operations, multi-step transitive closure, stuck-state detection, and formal Wright-Felleisen progress and preservation verification.

small-stepsosevaluation-contextsprogresstype-safety

Simply-Typed λ-Calculus with Advanced Types

Full simply-typed lambda calculus with HOAS: base types, booleans, pairs, sums (either), unit, recursion via fix, big-step call-by-value evaluation, hypothetical typing contexts, and type preservation checking.

hoasevaluationstlctype-preservationhigher-order

Strings & String Operations

String concatenation, list joining with delimiters, recognition of empty strings, and evaluable string expressions using the built-in string concatenation operator (^) and arithmetic/string evaluator (is).

librarystringsbuiltinsstandard-library

System F (Polymorphic λ-Calculus)

Implementation of Girard-Reynolds System F (impredicative polymorphism) using Higher-Order Abstract Syntax (HOAS) for both term-level and type-level binders. Features universal type quantification (∀X. T), type abstraction (ΛX. e), type application (e [T]), Church encodings for booleans and polymorphic lists, call-by-value evaluation, and type preservation (subject reduction).

system-fpolymorphismhoastype-systemschurch-encoding

Tactics and tacticals

Tactics as relations on object-goals; tacticals then, orelse, try, repeat, first, progress, and complete compose them.

libraryhigher-ordersearch

Tic-Tac-Toe Game

Interactive Tic-Tac-Toe game running on the lambda-Prolog game shell. Features 2D ASCII grid rendering, turn alternation, rule checking, and automated AI opponent.

gamelogicboardadversarialinteractive

Binary trees

Binary trees and binary search trees: membership, size, height, traversals, mirror, map, and ordered insert/lookup.

librarytrees

Tutorial

A walk through λProlog: typed Horn clauses, lists, hypothetical implication, universal goals, and a first HOAS snippet.

introlistspiimplication

Simply-typed λ-calculus

STLC with HOAS: base types, pairs, booleans, type inference, and the types of the I/K combinators.

libraryhoaspiimplication