Functional programming for Mojo¶
FP Mojo is a functional programming library for Mojo. You can compose functions
into pipelines, map, filter, and fold over collections, handle failures with
typed Result values, and define algebraic and inductive data types from your
own structs. Pattern matching checks that every constructor is covered at
compile time. Functions and closures keep their native ownership conventions
and error types.
The library is verified with Mojo 1.1.0 on Linux x86-64 and macOS arm64.
pixi add fp_mojo "mojo==1.1.0" # after adding the modular-community channel
Apply functions with pipe, compose them with flow, and bind arguments with
partial. Intermediate types and callback errors are inferred.
Define algebraic and inductive data types, then handle their constructors with exhaustive pattern matching.
Compose Reader, State and Writer computations with Functor, Applicative and Monad operations. Combine effects with monad transformers.
Run a first program¶
Follow the package installation steps,
then save this program as quickstart.mojo beside your project's pixi.toml:
"""The smallest complete FP Mojo program."""
from fp.functions import identity, pipe
from std.testing import assert_equal
def twice(var value: Int) -> Int:
return value * 2
def main() raises:
var answer = pipe(21, twice)
assert_equal(answer, 42)
print(answer)
pixi run mojo run quickstart.mojo
The program prints 42. pipe(21, twice) calls twice once with 21 and
returns that Int result. Add stages to the same call and they run left to right:
pipe(value, parse, check, render). Each stage's result type, and the error
type of any stage that raises, is inferred. The
pipeline tutorial builds a longer pipeline and shows
how a failing stage stops it.
Choose where to start¶
| Your task | Start here |
|---|---|
| Learn through runnable programs | Tutorial |
| Choose between mapping, combination and bind | Functors, applicatives and monads |
| Compose configuration, state and logging | Reader, State and Writer |
| Understand borrowing, movement, and failure | Ownership and errors |
| Look up a function or type | API reference |
| Understand the implementation boundaries | Architecture |
| Browse every runnable example | Examples |
| Contribute | Development |