Skip to content

Quick Start

Moshi (模式) is a Julia package for algebraic data types, pattern matching, and trait derivation. This guide gets you from zero to a working example in a few minutes.

From the Julia REPL, press ] to enter Pkg mode:

pkg> add Moshi

Import @data and define a sum type with several variants:

using Moshi.Data: @data
@data Message begin
Quit()
struct Move
x::Int
y::Int
end
Write(String)
ChangeColor(Int, Int, Int)
end
msg = Message.Move(3, 4)

Variants can be singletons (Quit()), named structs (Move), or tuple-like constructors (Write, ChangeColor).

Note: even a singleton variant is constructed with ()Message.Quit is the variant type, while Message.Quit() is the value. See Singleton Variant.

@match destructures values and returns the right-hand side of the first matching arm:

using Moshi.Match: @match
describe(msg) = @match msg begin
Message.Quit() => "quit"
Message.Move(; x, y) => "move to ($x, $y)"
Message.Write(text) => text
Message.ChangeColor(r, g, b) => (r, g, b)
end
describe(msg) # "move to (3, 4)"

If you have used MLStyle, the syntax will feel familiar. Moshi also supports matching on arrays, tuples, and more — see Builtin Patterns.

Use @derive to implement Show, Hash, and Eq from your type definition:

using Moshi.Derive: @derive
@derive Message[Show, Hash, Eq]

Works on both @data types and ordinary Julia structs.

Topic Guide
ADT concepts Algebraic Data Types
@data syntax ADT Syntax
@match patterns Pattern Matching Intro
@derive traits Derive Intro
API docs Moshi.Data, Moshi.Match, Moshi.Derive

Moshi is named after the Chinese word 模式 (móshì, “pattern”). Pattern matching design draws from MLStyle. The ADT encoding is inspired by SumTypes, Expronicon, and this Julia discussion on generated structs.