fp_library/lib.rs
1#![warn(missing_docs)]
2#![allow(clippy::tabs_in_doc_comments)]
3
4//! A functional programming library for Rust featuring your favourite higher-kinded types and type classes.
5//!
6//! ## Motivation
7//!
8//! 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`).
9//!
10//! `fp-library` aims to bridge this gap by providing:
11//!
12//! 1. A robust encoding of HKTs in stable Rust.
13//! 2. A comprehensive set of standard type classes (`Functor`, `Monad`, `Traversable`, etc.).
14//! 3. Zero-cost abstractions that respect Rust's performance characteristics.
15//!
16//! ## Features
17//!
18//! - **Higher-Kinded Types (HKT):** Implemented using lightweight higher-kinded polymorphism (type-level defunctionalization/brands).
19//! - **Macros:** Procedural macros (`trait_kind!`, `impl_kind!`, `Apply!`) to simplify HKT boilerplate and type application.
20//! - **Type Classes:** A comprehensive collection of standard type classes including:
21//! - **Core:** `Functor`, `Applicative`, `Monad`, `Semigroup`, `Monoid`, `Foldable`, `Traversable`
22//! - **Collections:** `Compactable`, `Filterable`, `Witherable`
23//! - **Category Theory:** `Category`, `Semigroupoid`, `Profunctor`, `Strong`, `Choice`
24//! - **Utilities:** `Pointed`, `Lift`, `ApplyFirst`, `ApplySecond`, `Semiapplicative`, `Semimonad`
25//! - **Advanced/Internal:** `MonadRec`, `RefFunctor`, `Defer`, `SendDefer`
26//! - **Function & Pointer Abstractions:** `Function`, `CloneableFn`, `SendCloneableFn`, `ParFoldable`, `Pointer`, `RefCountedPointer`, `SendRefCountedPointer`
27//! - **Optics:** Composable data accessors for elegant field access and updates:
28//! - **Lens:** Fully polymorphic focus (S -> T, A -> B) - Matches PureScript `Lens`
29//! - **LensPrime:** Monomorphic focus on a field (S -> S, A -> A) - Matches PureScript `Lens'`
30//! - **Prism:** Focus on a variant within a sum type
31//! - Based on profunctor encoding for type-safe composition
32//! - **Helper Functions:** Standard FP utilities:
33//! - `compose`, `constant`, `flip`, `identity`
34//! - **Data Types:** Implementations for standard and custom types:
35//! - **Standard Library:** `Option`, `Result`, `Vec`, `String`
36//! - **Laziness, Memoization & Stack Safety:** `Lazy`, `Thunk`, `Trampoline`, `Free`
37//! - **Generic Containers:** `Identity`, `Pair`
38//! - **Function Wrappers:** `Endofunction`, `Endomorphism`, `SendEndofunction`
39//! - **Marker Types:** `RcBrand`, `ArcBrand`, `FnBrand`
40//!
41//! ## How it Works
42//!
43//! ### Higher-Kinded Types (HKT)
44//!
45//! 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).
46//!
47//! 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.
48//!
49//! ```rust
50//! use fp_library::{
51//! impl_kind,
52//! kinds::*,
53//! };
54//!
55//! pub struct OptionBrand;
56//!
57//! impl_kind! {
58//! for OptionBrand {
59//! type Of<'a, A: 'a>: 'a = Option<A>;
60//! }
61//! }
62//! ```
63//!
64//! ### Zero-Cost Abstractions & Uncurried Semantics
65//!
66//! 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.
67//!
68//! **Why?**
69//! Traditional currying in Rust often requires:
70//!
71//! - Creating intermediate closures for each partial application.
72//! - Heap-allocating these closures (boxing) or wrapping them in reference counters (`Rc`/`Arc`) to satisfy type system constraints.
73//! - Dynamic dispatch (`dyn Fn`), which inhibits compiler optimizations like inlining.
74//!
75//! By using uncurried functions with `impl Fn` or generic bounds, `fp-library` achieves **zero-cost abstractions**:
76//!
77//! - **No Heap Allocation:** Operations like `map` and `bind` do not allocate intermediate closures.
78//! - **Static Dispatch:** The compiler can fully monomorphize generic functions, enabling aggressive inlining and optimization.
79//! - **Ownership Friendly:** Better integration with Rust's ownership and borrowing system.
80//!
81//! This approach ensures that using high-level functional abstractions incurs no runtime penalty compared to hand-written imperative code.
82//!
83//! **Exceptions:**
84//! While the library strives for zero-cost abstractions, some operations inherently require dynamic dispatch or heap allocation due to Rust's type system:
85//!
86//! - **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.
87//! - **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.
88//!
89//! 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.
90//!
91//! ### Lazy Evaluation & Effect System
92//!
93//! 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.
94//!
95//! | Type | Primary Use Case | Stack Safe? | Memoized? | Lifetimes? | HKT Traits |
96//! | :------------------ | :-------------------------------------------------------------------------------------------------------------------------- | :----------------------------- | :-------- | :----------- | :----------------------------------- |
97//! | **`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` |
98//! | **`Trampoline<A>`** | **Deep Recursion & Pipelines.** Heavy-duty computation. Uses a trampoline to guarantee stack safety for infinite recursion. | ✅ Yes | ❌ No | ❌ `'static` | ❌ No |
99//! | **`Lazy<'a, A>`** | **Caching.** Wraps a computation to ensure it runs at most once. | N/A | ✅ Yes | ✅ `'a` | ✅ `RefFunctor` |
100//!
101//! #### The "Why" of Three Types
102//!
103//! Unlike lazy languages (e.g., Haskell) where the runtime handles everything, Rust requires us to choose our trade-offs:
104//!
105//! 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.
106//! 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.
107//!
108//! #### Workflow Example: Expression Evaluator
109//!
110//! A robust pattern is to use `TryTrampoline` for stack-safe, fallible recursion, `TryLazy` to memoize expensive results, and `TryThunk` to create lightweight views.
111//!
112//! Consider an expression evaluator that handles division errors and deep recursion:
113//!
114//! ```rust
115//! use fp_library::types::*;
116//!
117//! #[derive(Clone)]
118//! enum Expr {
119//! Val(i32),
120//! Add(Box<Expr>, Box<Expr>),
121//! Div(Box<Expr>, Box<Expr>),
122//! }
123//!
124//! // 1. Stack-safe recursion with error handling (TryTrampoline)
125//! fn eval(expr: &Expr) -> TryTrampoline<i32, String> {
126//! let expr = expr.clone(); // Capture owned data for 'static closure
127//! TryTrampoline::defer(move || match expr {
128//! Expr::Val(n) => TryTrampoline::ok(n),
129//! Expr::Add(lhs, rhs) => eval(&lhs).bind(move |l| eval(&rhs).map(move |r| l + r)),
130//! Expr::Div(lhs, rhs) => eval(&lhs).bind(move |l| {
131//! eval(&rhs).bind(move |r| {
132//! if r == 0 {
133//! TryTrampoline::err("Division by zero".to_string())
134//! } else {
135//! TryTrampoline::ok(l / r)
136//! }
137//! })
138//! }),
139//! })
140//! }
141//!
142//! // Usage
143//! fn main() {
144//! let expr = Expr::Div(Box::new(Expr::Val(100)), Box::new(Expr::Val(2)));
145//!
146//! // 2. Memoize result (TryLazy)
147//! // The evaluation runs at most once, even if accessed multiple times.
148//! let result = RcTryLazy::new(move || eval(&expr).evaluate());
149//!
150//! // 3. Create deferred view (TryThunk)
151//! // Borrow the cached result to format it.
152//! let view: TryThunk<String, String> = TryThunk::new(|| {
153//! let val = result.evaluate().map_err(|e| e.clone())?;
154//! Ok(format!("Result: {}", val))
155//! });
156//!
157//! assert_eq!(view.evaluate(), Ok("Result: 50".to_string()));
158//! }
159//! ```
160//!
161//! ### Thread Safety and Parallelism
162//!
163//! The library supports thread-safe operations through the `SendCloneableFn` extension trait and parallel folding via `ParFoldable`.
164//!
165//! - **`SendCloneableFn`**: Extends `CloneableFn` to provide `Send + Sync` function wrappers. Implemented by `ArcFnBrand`.
166//! - **`ParFoldable`**: Provides `par_fold_map` and `par_fold_right` for parallel execution.
167//! - **Rayon Support**: `VecBrand` supports parallel execution using `rayon` when the `rayon` feature is enabled.
168//!
169//! ```
170//! use fp_library::{
171//! brands::*,
172//! functions::*,
173//! };
174//!
175//! let v = vec![1, 2, 3, 4, 5];
176//! // Create a thread-safe function wrapper
177//! let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
178//! // Fold in parallel (if rayon feature is enabled)
179//! let result = par_fold_map::<ArcFnBrand, VecBrand, _, _>(f, v);
180//! assert_eq!(result, "12345".to_string());
181//! ```
182//!
183//! ## Example: Using `Functor` with `Option`
184//!
185//! ```
186//! use fp_library::{
187//! brands::*,
188//! functions::*,
189//! };
190//!
191//! let x = Some(5);
192//! // Map a function over the `Option` using the `Functor` type class
193//! let y = map::<OptionBrand, _, _>(|i| i * 2, x);
194//! assert_eq!(y, Some(10));
195//! ```
196//!
197//! ## Crate Features
198//!
199//! - **`rayon`**: Enables parallel folding operations (`ParFoldable`) and parallel execution support for `VecBrand` using the [rayon](https://github.com/rayon-rs/rayon) library.
200//! - **`serde`**: Enables serialization and deserialization support for pure data types using the [serde](https://github.com/serde-rs/serde) library.
201
202extern crate fp_macros;
203
204pub mod brands;
205pub mod classes;
206pub mod functions;
207pub mod kinds;
208pub mod types;
209
210pub use fp_macros::*;