fp_library/lib.rs
1#![warn(missing_docs)]
2
3//! A functional programming library for Rust featuring your favourite higher-kinded types and type classes.
4//!
5//! ## Motivation
6//!
7//! Rust is a multi-paradigm language with strong functional programming features like iterators, closures, and algebraic data types. However, it lacks native support for **Higher-Kinded Types (HKT)**, which limits the ability to write generic code that abstracts over type constructors (e.g., writing a function that works for any `Monad`, whether it's `Option`, `Result`, or `Vec`).
8//!
9//! `fp-library` aims to bridge this gap by providing:
10//!
11//! 1. A robust encoding of HKTs in stable Rust.
12//! 2. A comprehensive set of standard type classes (`Functor`, `Monad`, `Traversable`, etc.).
13//! 3. Zero-cost abstractions that respect Rust's performance characteristics.
14//!
15//! ## Features
16//!
17//! - **Higher-Kinded Types (HKT):** Implemented using lightweight higher-kinded polymorphism (type-level defunctionalization/brands).
18//! - **Macros:** Procedural macros (`def_kind!`, `impl_kind!`, `Apply!`) to simplify HKT boilerplate and type application.
19//! - **Type Classes:** A comprehensive collection of standard type classes including:
20//! - **Core:** `Functor`, `Applicative`, `Monad`, `Semigroup`, `Monoid`, `Foldable`, `Traversable`
21//! - **Collections:** `Compactable`, `Filterable`, `Witherable`
22//! - **Category Theory:** `Category`, `Semigroupoid`
23//! - **Utilities:** `Pointed`, `Lift`, `ApplyFirst`, `ApplySecond`, `Semiapplicative`, `Semimonad`
24//! - **Advanced/Internal:** `MonadRec`, `RefFunctor`, `Defer`, `SendDefer`
25//! - **Function & Pointer Abstractions:** `Function`, `CloneableFn`, `SendCloneableFn`, `ParFoldable`, `Pointer`, `RefCountedPointer`, `SendRefCountedPointer`
26//! - **Helper Functions:** Standard FP utilities:
27//! - `compose`, `constant`, `flip`, `identity`
28//! - **Data Types:** Implementations for standard and custom types:
29//! - **Standard Library:** `Option`, `Result`, `Vec`, `String`
30//! - **Laziness, Memoization & Stack Safety:** `Lazy`, `Thunk`, `Trampoline`, `Free`
31//! - **Generic Containers:** `Identity`, `Pair`
32//! - **Function Wrappers:** `Endofunction`, `Endomorphism`, `SendEndofunction`
33//! - **Marker Types:** `RcBrand`, `ArcBrand`, `FnBrand`
34//!
35//! ## How it Works
36//!
37//! ### Higher-Kinded Types (HKT)
38//!
39//! Since Rust doesn't support HKTs directly (i.e., it's not possible to use `Option` in `impl Functor for Option`, instead of `Option<T>`), this library uses **Lightweight Higher-Kinded Polymorphism** (also known as the "Brand" pattern or type-level defunctionalization).
40//!
41//! Each type constructor has a corresponding `Brand` type (e.g., `OptionBrand` for `Option`). These brands implement the `Kind` traits, which map the brand and generic arguments back to the concrete type. The library provides macros to simplify this process.
42//!
43//! ```rust
44//! use fp_library::{impl_kind, kinds::*};
45//!
46//! pub struct OptionBrand;
47//!
48//! impl_kind! {
49//! for OptionBrand {
50//! type Of<'a, A: 'a>: 'a = Option<A>;
51//! }
52//! }
53//! ```
54//!
55//! ### Zero-Cost Abstractions & Uncurried Semantics
56//!
57//! Unlike many functional programming libraries that strictly adhere to curried functions (e.g., `map(f)(fa)`), `fp-library` adopts **uncurried semantics** (e.g., `map(f, fa)`) for its core abstractions.
58//!
59//! **Why?**
60//! Traditional currying in Rust often requires:
61//!
62//! - Creating intermediate closures for each partial application.
63//! - Heap-allocating these closures (boxing) or wrapping them in reference counters (`Rc`/`Arc`) to satisfy type system constraints.
64//! - Dynamic dispatch (`dyn Fn`), which inhibits compiler optimizations like inlining.
65//!
66//! By using uncurried functions with `impl Fn` or generic bounds, `fp-library` achieves **zero-cost abstractions**:
67//!
68//! - **No Heap Allocation:** Operations like `map` and `bind` do not allocate intermediate closures.
69//! - **Static Dispatch:** The compiler can fully monomorphize generic functions, enabling aggressive inlining and optimization.
70//! - **Ownership Friendly:** Better integration with Rust's ownership and borrowing system.
71//!
72//! This approach ensures that using high-level functional abstractions incurs no runtime penalty compared to hand-written imperative code.
73//!
74//! **Exceptions:**
75//! While the library strives for zero-cost abstractions, some operations inherently require dynamic dispatch or heap allocation due to Rust's type system:
76//!
77//! - **Functions as Data:** When functions are stored in data structures (e.g., inside a `Vec` for `Semiapplicative::apply`, or in `Lazy` thunks), they must often be "type-erased" (wrapped in `Rc<dyn Fn>` or `Arc<dyn Fn>`). This is because every closure in Rust has a unique, anonymous type. To store multiple different closures in the same container, or to compose functions dynamically (like in `Endofunction`), they must be coerced to a common trait object.
78//! - **Lazy Evaluation:** The `Lazy` type relies on storing a thunk that can be cloned and evaluated later, which typically requires reference counting and dynamic dispatch.
79//!
80//! For these specific cases, the library provides `Brand` types (like `RcFnBrand` and `ArcFnBrand`) to let you choose the appropriate wrapper (single-threaded vs. thread-safe) while keeping the rest of your code zero-cost. The library uses a unified `Pointer` hierarchy to abstract over these choices.
81//!
82//! ### Lazy Evaluation & Effect System
83//!
84//! Rust is an eagerly evaluated language. To enable functional patterns like deferred execution and safe recursion, `fp-library` provides a granular set of types that let you opt-in to specific behaviors without paying for unnecessary overhead.
85//!
86//! | Type | Primary Use Case | Stack Safe? | Memoized? | Lifetimes? | HKT Traits |
87//! | :------------------ | :-------------------------------------------------------------------------------------------------------------------------- | :----------------------------- | :-------- | :----------- | :----------------------------------- |
88//! | **`Thunk<'a, A>`** | **Glue Code & Borrowing.** Lightweight deferred computation. Best for short chains and working with references. | ⚠️ Partial (`tail_rec_m` only) | ❌ No | ✅ `'a` | ✅ `Functor`, `Applicative`, `Monad` |
89//! | **`Trampoline<A>`** | **Deep Recursion & Pipelines.** Heavy-duty computation. Uses a trampoline to guarantee stack safety for infinite recursion. | ✅ Yes | ❌ No | ❌ `'static` | ❌ No |
90//! | **`Lazy<'a, A>`** | **Caching.** Wraps a computation to ensure it runs at most once. | N/A | ✅ Yes | ✅ `'a` | ✅ `RefFunctor` |
91//!
92//! #### The "Why" of Three Types
93//!
94//! Unlike lazy languages (e.g., Haskell) where the runtime handles everything, Rust requires us to choose our trade-offs:
95//!
96//! 1. **`Thunk` vs `Trampoline`**: `Thunk` is faster and supports borrowing (`&'a T`). Its `tail_rec_m` is stack-safe, but deep `bind` chains will overflow the stack. `Trampoline` guarantees stack safety for all operations via a trampoline (the `Free` monad) but requires types to be `'static` and `Send`. A key distinction is that `Thunk` implements `Functor`, `Applicative`, and `Monad` directly, making it suitable for generic programming, while `Trampoline` does not.
97//! 2. **Computation vs Caching**: `Thunk` and `Trampoline` describe _computations_—they re-run every time you call `.evaluate()`. If you have an expensive operation (like a DB call), convert it to a `Lazy` to cache the result.
98//!
99//! #### Workflow Example: Expression Evaluator
100//!
101//! A robust pattern is to use `TryTrampoline` for stack-safe, fallible recursion, `TryLazy` to memoize expensive results, and `TryThunk` to create lightweight views.
102//!
103//! Consider an expression evaluator that handles division errors and deep recursion:
104//!
105//! ```rust
106//! use fp_library::types::*;
107//!
108//! #[derive(Clone)]
109//! enum Expr {
110//! Val(i32),
111//! Add(Box<Expr>, Box<Expr>),
112//! Div(Box<Expr>, Box<Expr>),
113//! }
114//!
115//! // 1. Stack-safe recursion with error handling (TryTrampoline)
116//! fn eval(expr: &Expr) -> TryTrampoline<i32, String> {
117//! let expr = expr.clone(); // Capture owned data for 'static closure
118//! TryTrampoline::defer(move || match expr {
119//! Expr::Val(n) => TryTrampoline::ok(n),
120//! Expr::Add(lhs, rhs) => {
121//! eval(&lhs).bind(move |l| eval(&rhs).map(move |r| l + r))
122//! }
123//! Expr::Div(lhs, rhs) => {
124//! eval(&lhs).bind(move |l| {
125//! eval(&rhs).bind(move |r| {
126//! if r == 0 {
127//! TryTrampoline::err("Division by zero".to_string())
128//! } else {
129//! TryTrampoline::ok(l / r)
130//! }
131//! })
132//! })
133//! }
134//! })
135//! }
136//!
137//! // Usage
138//! fn main() {
139//! let expr = Expr::Div(Box::new(Expr::Val(100)), Box::new(Expr::Val(2)));
140//!
141//! // 2. Memoize result (TryLazy)
142//! // The evaluation runs at most once, even if accessed multiple times.
143//! let result = RcTryLazy::new(move || eval(&expr).evaluate());
144//!
145//! // 3. Create deferred view (TryThunk)
146//! // Borrow the cached result to format it.
147//! let view: TryThunk<String, String> = TryThunk::new(|| {
148//! let val = result.evaluate().map_err(|e| e.clone())?;
149//! Ok(format!("Result: {}", val))
150//! });
151//!
152//! assert_eq!(view.evaluate(), Ok("Result: 50".to_string()));
153//! }
154//! ```
155//!
156//! ### Thread Safety and Parallelism
157//!
158//! The library supports thread-safe operations through the `SendCloneableFn` extension trait and parallel folding via `ParFoldable`.
159//!
160//! - **`SendCloneableFn`**: Extends `CloneableFn` to provide `Send + Sync` function wrappers. Implemented by `ArcFnBrand`.
161//! - **`ParFoldable`**: Provides `par_fold_map` and `par_fold_right` for parallel execution.
162//! - **Rayon Support**: `VecBrand` supports parallel execution using `rayon` when the `rayon` feature is enabled.
163//!
164//! ```
165//! use fp_library::{brands::*, functions::*};
166//!
167//! let v = vec![1, 2, 3, 4, 5];
168//! // Create a thread-safe function wrapper
169//! let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
170//! // Fold in parallel (if rayon feature is enabled)
171//! let result = par_fold_map::<ArcFnBrand, VecBrand, _, _>(f, v);
172//! assert_eq!(result, "12345".to_string());
173//! ```
174//!
175//! ## Example: Using `Functor` with `Option`
176//!
177//! ```
178//! use fp_library::{brands::*, functions::*};
179//!
180//! let x = Some(5);
181//! // Map a function over the `Option` using the `Functor` type class
182//! let y = map::<OptionBrand, _, _, _>(|i| i * 2, x);
183//! assert_eq!(y, Some(10));
184//! ```
185//!
186//! ## Crate Features
187//!
188//! - **`rayon`**: Enables parallel folding operations (`ParFoldable`) and parallel execution support for `VecBrand` using the [rayon](https://github.com/rayon-rs/rayon) library.
189
190extern crate fp_macros;
191
192pub mod brands;
193pub mod classes;
194pub mod functions;
195pub mod kinds;
196pub mod types;
197
198pub use fp_macros::Apply;
199pub use fp_macros::Kind;
200pub use fp_macros::def_kind;
201pub use fp_macros::impl_kind;