Rustica
Rustica is a comprehensive functional programming library for Rust, bringing powerful abstractions from category theory and functional programming to the Rust ecosystem. It provides a rich set of type classes, data types, and utilities commonly found in functional programming languages.
Overview
Rustica enables idiomatic functional programming in Rust by providing:
- Type Classes: Core abstractions like
Functor,Applicative, andMonad - Data Types: Common functional data structures like
Maybe,Either,Choice, andIO - Monad Transformers: Powerful composition with
StateT,ReaderT, and more - Composable APIs: Tools for function composition and transformation
- Pure Functional Style: Patterns for immutable data and explicit effect handling
- Error Handling: Functional error handling utilities that work across different types
Whether you're coming from Haskell, Scala, or other functional languages, or just want to explore functional programming in Rust, Rustica provides the tools you need.
Getting Started
Add Rustica to your Cargo.toml:
[]
= "0.7.1"
If you want to use async features, add the async feature:
[]
= { = "0.7.1", = ["async"] }
If you want to use persistent vector collections, add the pvec feature:
[]
= { = "0.7.1", = ["pvec"] }
You can combine multiple features as needed:
[]
= { = "0.7.1", = ["full"] }
Then import the prelude to get started:
use *;
Features
Type Classes
Rustica implements a wide range of type classes from category theory:
-
Basic Abstractions
Functor- For mapping over contained valuesApplicative- For applying functions in a contextMonad- For sequential computationsPure- For lifting values into a contextIdentity- For accessing values inside contextsAlternative- For choice between computations
-
Algebraic Structures
Semigroup- Types with an associative binary operationMonoid- Semigroups with an identity elementFoldable- For reducing structuresTraversable- For structure-preserving transformations
-
Advanced Concepts
Bifunctor- For mapping over two type parametersContravariant- For reversing function applicationCategory- For abstract compositionArrow- For generalized computationComonad- For context-aware computationsMonadError- For error handling in monadic contexts
Data Types
Rustica provides a rich collection of functional data types:
-
Core Types
Maybe<T>- For optional values (likeOption<T>)Either<L, R>- For values with two possibilitiesId<T>- The identity monadValidated<E, T>- For accumulating validation errorsChoice<T>- For representing non-deterministic computations with alternatives
-
Effect Types
IO<A>- For pure I/O operationsState<S, A>- For stateful computations with thread-safe implementationsReader<E, A>- For environment-based computationsWriter<W, A>- For logging operationsCont<R, A>- For continuation-based programmingAsyncMonad<A>- For asynchronous operations
-
Special Purpose
- Various wrapper types (
First,Last,Min,Max, etc.)
- Various wrapper types (
-
Persistent Collections
PersistentVector<T>- An efficient immutable vector with structural sharing and small vector optimization
-
Transformers
StateT<S, M, A>- State monad transformer for combining state with other effectsReaderT<E, M, A>- Reader monad transformer for combining environment with other effectsWriterT<W, M, A>- Writer monad transformer for combining logging with other effects- Bidirectional conversion between monads and their transformer versions
-
Optics
Lens- For focusing on parts of structuresPrism- For working with sum typesIsoLens- Lawful, composable lenses based on isomorphisms for deep focusingIsoPrism- Lawful, composable prisms based on isomorphisms for sum types
Error Handling Utilities
Rustica provides standardized error handling utilities that work across different functional types:
-
Core Functions
sequence- Combines a collection ofResultvalues into a singleResultcontaining a collectiontraverse- Applies a function that produces aResultto a collection, returning a singleResulttraverse_validated- Liketraversebut collects all errors instead of failing fast
-
Type Conversion
ResultExttrait - ExtendsResultwith methods liketo_validated()andto_either()WithErrortrait - Generic trait for any type that can represent error states- Conversion functions between
Result,Either, andValidated
-
Error Types
AppError<M, C>- A structured error type that provides both a message and optional context- Helper functions like
error()anderror_with_context()
Persistent Vector (pvec feature)
Rustica provides a high-performance, immutable persistent vector (RRB-Tree) for functional programming patterns.
Enable the feature
[]
= { = "0.7.1", = ["pvec"] }
Example Usage
use PersistentVector;
use pvec;
let v1: = pvec!;
let v2 = v1.push_back;
let v3 = v1.update;
assert_eq!;
assert_eq!;
assert_eq!;
Advanced: Chunk Size and Cache Policy
let vec = with_chunk_size;
let vec = vec.push_back.push_back;
assert_eq!;
CI/CD & Publishing
Rustica uses GitHub Actions for continuous integration, formatting, linting, and automated publishing to crates.io on tagged releases.
- Tests and formatting are run on every push and pull request.
- When a tag (e.g.
v0.7.1) is pushed, the version is checked and, if not already published, is automatically uploaded to crates.io.
Changelog
See CHANGELOG.md for a complete list of recent changes and enhancements.
Examples
Identity Monad (Id)
use *;
use Id;
use Identity;
// Create Id values
let x = new;
let y = new;
let z = new;
// Access the inner value using Identity trait's value() method
assert_eq!;
// Using Functor to map over Id
let doubled = x.fmap;
assert_eq!;
// Using Pure to lift a value into Id context
let pure_value = pure;
assert_eq!;
// Using Applicative to apply functions
// 1. Apply a function wrapped in Id
let add_one = new;
let result = x.apply;
assert_eq!;
// 2. Combine two Id values with lift2
let add = ;
let sum = x.lift2;
assert_eq!;
// 3. Combine three Id values with lift3
let multiply = ;
let product = x.lift3;
assert_eq!;
// Working with different types
let greeting = new;
let count = new;
let repeat = ;
let repeated = greeting.lift2;
assert_eq!;
// Chaining operations
let result = x
.fmap // 5 -> 6
.fmap // 6 -> 12
.fmap;
assert_eq!;
Continuation Monad (Cont)
use Cont;
// Create a simple continuation
let cont = return_cont;
// Run the continuation with a handler
let result = cont.clone.run;
assert_eq!;
// Chain continuations
let cont2 = cont.bind;
let result2 = cont2.run;
assert_eq!;
Control Flow Example
use Arc;
use Cont;
// A function that uses continuations to implement early return
// Run with different inputs
let result1 = safe_divide.run;
let result2 = safe_divide.run;
assert_eq!;
assert_eq!;
Additional Examples from Cont
use Cont;
// Create two continuations
let cont1 = return_cont;
let cont2 = return_cont;
// Run the continuations with an identity continuation
let result1 = cont1.run;
let result2 = cont2.run;
assert_eq!;
assert_eq!;
Inspiration
Rustica is inspired by functional programming libraries in other languages:
- Haskell's standard library
- Scala's Cats
- Kotlin's Arrow
- TypeScript's fp-ts
Contributing
Contributions are welcome! Check the TODO list for areas that need work.
License
Rustica is licensed under the Apache License, version 2.0. See the LICENSE file for details.
Documentation
For detailed documentation, please visit docs.rs/rustica