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.
Install
Section titled “Install”From the Julia REPL, press ] to enter Pkg mode:
pkg> add MoshiYour first ADT
Section titled “Your first ADT”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.Quitis the variant type, whileMessage.Quit()is the value. See Singleton Variant.
Pattern match on it
Section titled “Pattern match on it”@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.
Derive traits
Section titled “Derive traits”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.
Next steps
Section titled “Next steps”| 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 |
Acknowledgements
Section titled “Acknowledgements”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.