Marmot
A statically typed, expression-oriented functional language with algebraic data types, exhaustive pattern matching, typeclasses, and folder-based modules. Bindings stay fixed; reference cells hold changing state. Its compiler specializes generics and optimizes a typed SSA representation before emitting bytecode for the Marmot Virtual Machine. Workers run in separate VMs and communicate through typed channels.
Features
- 01
Static Type System
Bidirectional inference, generics, where constraints, and associated types. Generic functions specialize to concrete types during lowering.
- 02
Pattern Matching
Exhaustive matching with nested constructors, tuples, arrays with rest patterns, named record fields, integer ranges, alternatives, and guards.
- 03
Algebraic Data Types
Records and unions, transparent aliases, distinct newtypes, record update, and structural or container deriving.
- 04
Typeclasses
Constrained generics, associated types, and instance dispatch for operators, indexing, and iteration. The Transferable marker controls which types can cross worker boundaries.
- 05
Bindings & References
Bindings stay fixed. Explicit Ref<T> cells hold changing state: ref creates a cell, * reads it, and := writes it. Closures in the same worker share the cell.
- 06
Expressions & Iteration
Blocks, if, and match produce values. Tail calls reuse the current frame; for loops, ranges, comprehensions, and lazy Iter pipelines handle sequences.
- 07
Workers & Channels
Each worker has its own VM, heap, and globals. Transferable values cross by copy; typed bounded channels carry messages, and Join returns a Result.
- 08
Modules & Packages
Explicit imports, use declarations, exports, and module-qualified names. The project tool resolves packages from disk or GitHub releases, vendors them, and writes a lockfile.
Quick Start
Install from the Marmot checkout on Windows or Linux, then use the project tool to create, check, format, run, and test a project.
python scripts/dev.py doctorpython scripts/dev.py install --rebuild
On Windows, open a new terminal after installing. On Linux, use the line the installer prints to source env.sh.
marmot init hello-worldcd hello-worldmarmot check src/Mainmarmot fmtmarmot run src/Mainmarmot test
Put each standalone example in its own directory. The directory defines a module, and its immediate .mmt files share top-level definitions. One file per module can contain executable statements and value initializers, which run in source order. Imports such as import { IO } resolve by module name through the build plan. For a standalone compile, the compiler searches the entry module's parent and the directories in MARMOT_PATH.
import { IO }IO::PrintLine("Hello, Marmot!");
// Simple functiondef square = fn(x: Int) -> Int => x * x;// Generic functiondef identity = fn<T>(value: T) -> T => value;// Higher-order functiondef apply = fn<T, R>(f: fn(T) -> R, value: T) -> R => f(value);def nine = apply(square, 3);
// Product types (records)type Point = {x: Float,y: Float,};// Sum typestype Option<T> = None | Some(T);type Result<T, E> = Ok(T) | Err(E);def origin = Point(0.0, 0.0);def moved = { origin with x = 3.0 }; // a new Pointdef maybe = Option::Some(42);
alias gives an existing type another name. type Meters = Intcreates a distinct type with the same representation. Records and unions can derive Equatable, Hashable, Orderable, Convertable to Text, and Transferable. Unions of supported shapes can also derive Map, Bind, and Unwrap.
alias UserId = Int;type Meters = Int;def user: UserId = 42;def distance: Meters = 12 as Meters;def raw: Int = distance as Int;
import { Equatable, Hashable }type Point = { x: Int, y: Int } deriving (Equatable, Hashable);type Box<T> = Empty | Full(T) deriving (Map, Bind, Unwrap);def same = Point(1, 2) == Point(1, 2);def mapped = BoxMap(Box::Full(5), fn(n) => n + 1);def value = BoxUnwrap(mapped, 0); // 6
Pattern Matching
type Result<T, E> = Ok(T) | Err(E);def describe = fn(result: Result<Int, Text>) -> Text =>match result withcase Result::Ok(0) => "Success: zero"case Result::Ok(value) => "Success: " ++ (value as Text)case Result::Err(message) => "Error: " ++ message;
Patterns can name record fields, bind an array's remaining elements with ..tail, match integer ranges, combine alternatives with |, or retain the whole value with as. Guards filter a case at runtime; guarded cases do not establish exhaustive coverage.
type Point = { x: Int, y: Int };def axis = fn(point: Point) -> Text =>match point withcase Point { x = 0, .. } as on_axis =>"y=" ++ (on_axis.y as Text)case Point { .. } => "off the y axis";def first = fn(values: Array<Int>) -> Int =>match values withcase [head, ..] => headcase [] => 0;
def classify = fn(n: Int) -> Text =>match n withcase -5..0 | 0..6 => "small"case value if value > 100 => "large positive"case _ => "other";def small = classify(-3); // "small"def large = classify(101); // "large positive"
Typeclasses
A where clause requires an instance. That instance can determine an associated type, such as the type of item an iterator yields.
class Show<T> {show: fn(value: T) -> Text;};instance Show<Int> {def show = fn(value: Int) -> Text => value as Text;};def display = fn<T>(value: T) -> Text where Show<T> => Show::show(value);def message = display(42); // "42"
type Option<T> = None | Some(T);// Next yields the item and the rest of the sequence, so an// iterator is a value rather than something that advances in place.class Iterable<Iter> {type Item;Next: fn(iter: Iter) -> Option<(Item, Iter)>;};def NextValue = fn<Iter>(iter: Iter) -> Option<(Iterable::Item<Iter>, Iter)>where Iterable<Iter> => Iterable::Next(iter);
Advanced
def double = fn(x: Int) -> Int => x * 2;type Result<T, E> = Ok(T) | Err(E);def transform = fn(value: Int) -> Result<Int, Text> =>if value > 10then Result::Ok(value + 1)else Result::Err("too small");def result =5|> double|> fn(x) => { x + 1 }|> transform|> fn(result) => match result withcase Result::Ok(value) => valuecase Result::Err(_) => 0;
def ApplyTwice = fn(f: fn(Int) -> Int, x: Int) -> Int => f(f(x));// The lambda captures factor from the enclosing function.def ScaleTwice = fn(factor: Int, values: Array<Int>) -> Array<Int> =>[ApplyTwice(fn(x: Int) -> Int => x * factor, value) for value in values];def scaled = ScaleTwice(3, [1, 2, 3]); // [9, 18, 27]
Iter builds lazy sequence pipelines over Iterable sources. Stages run when a consumer such as ToArray or Fold asks for their elements.
import { Iter }def values = [1, 2, 3, 4, 5, 6];def evens = values|> Iter::OfArray|> Iter::Filter(fn(n: Int) -> Bool => (n % 2) == 0)|> Iter::Map(fn(n: Int) -> Int => n * 2)|> Iter::Take(2)|> Iter::ToArray; // [4, 8]
References & Recursion
A def binds a name once. Changing state lives in a Ref<T>: aliases and closures within a worker see writes to the same cell. Reference creation, reading, and writing need no import; a write evaluates to Unit. A Marmot call in tail position can reuse the current frame, including through blocks, if branches, and match arms.
def counter = ref 0;def Next = fn() -> Int => {counter := (*counter) + 1;*counter};def first = Next(); // 1def second = Next(); // 2def current = *counter; // 2
def SumTo = fn(n: Int, total: Int) -> Int =>if n == 0 then total else SumTo(n - 1, total + n);def total = SumTo(1000, 0); // 500500def squares = [n * n for n in 0..1..5]; // [0, 1, 4, 9, 16]
Modules & Packages
An export list makes selected names public. Other names stay within the module. Each file declares its own imports, which allow access through a module prefix. Use use to bring selected names into that file's scope. A type keeps the identity of the module that defined it. The marmot tool reads project.marmot or package.marmot. It resolves dependencies from disk and configured GitHub release registries, vendors them into packages/, and writes marmot.lock. Native packages can ship prebuilt libraries or supply a [build].command. Packages and dynamic native FFI are experimental.
export { Double }def Double = fn(n: Int) -> Int => n * 2;
import { Arithmetic }use Arithmetic.{Double}def qualified = Arithmetic::Double(5);def local = Double(5);
Workers & Channels
Each worker runs on an OS thread with its own VM and heap. A worker starts with copies of the globals its code can read. Arguments and captures cross by copy, and a transferred Ref<T> becomes a separate cell. Workers can share channel handles. Send waits for space and returns false if the channel closes before it can send. Receive waits for a message and returns None() once the channel is closed and drained. Join returns Result<T, WorkerError>, with cancellation or failure in Err.Cancel requests a cooperative stop. Workers and channels require the native VM. The browser playground runs the WebAssembly build.
import{IO,Concurrency,Option,Result}use Option.{Option}use Result.{Result}def SumTo = fn(n: Int, total: Int) -> Int =>if n == 0 then total else SumTo(n - 1, total + n);// Spawn runs SumTo on its own worker; Join waits for the result.def worker = (1000, 0) |> Concurrency::Spawn(SumTo);def total =match Concurrency::Join(worker) withcase Result::Ok(value) => valuecase Result::Err(_) => 0;// ParallelMap splits the array into chunks, one worker each.def squares = Concurrency::ParallelMap([n for n in 0..1..8], fn(n: Int) -> Int => n * n, 4);// Channels carry typed values between workers.def channel : Channel<Int> = Concurrency::MakeChannel(4);Concurrency::Send(channel, total);def received =match Concurrency::Receive(channel) withcase Option::Some(value) => value as Textcase Option::None() => "closed";Concurrency::Close(channel);IO::PrintLine("total=" ++ (total as Text) ++ " received=" ++ received ++ " last square=" ++ (squares[7] as Text));
Typed Prelude
MarmotPrelude wraps the runtime FFI surface in Marmot-facing modules. File and process APIs prefer typed Result and Option over sentinel returns.
import{IO,System,Option,Result}use Option.{Option}use Result.{Result}def config_text =match IO::TryReadFile("app.conf") withcase Result::Ok(contents) => contentscase Result::Err(_) => "release=debug";def cache_dir =match System::TryGetEnv("MARMOT_CACHE_DIR") withcase Option::Some(path) => pathcase Option::None() => ".marmot-cache";
Standard Library
- 01
IO.mmtConsole output and typed file APIs: TryReadFile, TryWriteFile, TryAppendToFile, and binary-file helpers. - 02
System.mmtEnvironment lookup through Option; fallible directory and process operations through Result; platform and process information. - 03
DateTime.mmtLocalNow, UtcNow, FormatLocal, Unix milliseconds, and monotonic nanoseconds. - 04
TextUtil.mmtUTF-8 text helpers, splitting, trimming, replacement, and fallible ParseInt / ParseFloat conversions. - 05
ArrayUtil.mmtWithAppended, WithReplaced, Slice, and Reverse return new arrays. - 06
Iter.mmtLazy Map, Filter, and Take stages over Iterable sources; ToArray, Fold, and Count consume the pipeline. - 07
Map & SetPersistent hash-based collections. Updates return new collections; keys use Hashable and Equatable. - 08
Concurrency.mmtSpawn and join workers, create channels, and exchange messages with Send and Receive. ParallelMap splits work into chunks. - 09
Option, Result, ListCore algebraic data types and helpers. Result uses Ok and Err; Option uses Some and None.
Architecture
The three tools have separate jobs. marmotc checks or compiles source and writes .mmc; marmotvm runs or disassembles it. marmot manages projects and drives both. Project runs build into target/ and reuse the result while their inputs are unchanged.
marmotc check src/Mainmarmotc build src/Main -o hello.mmcmarmotvm run hello.mmcmarmotvm disassemble hello.mmcmarmotc check src/Main --emit-ir
- 01FrontendLexer → Module Manager → Parser → Type Checker → Static Analyzer
- 02LoweringChecked AST → MarmotIR, a typed SSA representation. Generics specialize and typeclass calls resolve to instance methods.
- 03OptimizerIR passes include inlining, contification, scalar replacement, constant propagation, global value numbering, and loop-invariant code motion. The central pass group repeats until unchanged, for at most eight rounds.
- 04BackendThe backend emits bytecode and the linker produces a .mmc artifact with a format marker. Dev and Debug verify the IR after lowering and each pass. Release verifies before emission.
- 05Runtimemarmotvm loads and executes .mmc bytecode with a non-moving, generational bitmap mark-sweep collector. Each worker owns its heap, stack, globals, and collector while sharing read-only bytecode.
- 06Project Toolmarmot, written in Rust, resolves projects and packages and passes an explicit build plan to marmotc. marmotc compiles; marmotvm runs.