Skip to content

Getting Started

Moshi (模式) is a Julia package for defining and working with algebraic data types (ADTs) and pattern matching. It also provides a derive macro similar to Rust’s derive macro for deriving traits (a set of interface functions) for ADTs or Julia structs.

The Name and Acknowledgement

The name “Moshi” is derived from the Chinese word “模式” (móshì) which means “pattern”. The design of pattern matching is inspired by its predecessor MLStyle, which tries to bring pattern matching and algebraic data types from ML family languages to Julia.

The generic algebraic data type is highly inspired by previous work done in Julia ecosystem:

Installation

You can install Moshi using the Julia package manager. From the Julia REPL, type ] to enter the Pkg REPL mode and run:

pkg> add Moshi

Quick Example

Here is a quick example of defining a simple algebraic data type:

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

For pattern matching, if you already used MLStyle, the syntax is very similar:

using Moshi.Match: @match
@match [1.0, 2, 3] begin
[1, xs::Float64...] => xs
end
@match (1, 2.0, "a") begin
(1, x::Int, y::String) => x
(1, x::Real, y::String) => y
end

Further Reading

To understand how Moshi works, you can check the following sections: