fp_library/
lib.rs

1//! A functional programming library for Rust featuring your favourite higher-kinded types and type classes.
2//!
3//! ## Motivation
4//!
5//! 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`).
6//!
7//! `fp-library` aims to bridge this gap by providing:
8//!
9//! 1.  A robust encoding of HKTs in stable Rust.
10//! 2.  A comprehensive set of standard type classes (`Functor`, `Monad`, `Traversable`, etc.).
11//! 3.  Zero-cost abstractions that respect Rust's performance characteristics.
12//!
13//! ## Features
14//!
15//! - **Higher-Kinded Types (HKT):** Implemented using lightweight higher-kinded polymorphism (type-level defunctionalization/brands).
16//! - **Macros:** Procedural macros (`def_kind!`, `impl_kind!`, `Apply!`) to simplify HKT boilerplate and type application.
17//! - **Type Classes:** A comprehensive collection of standard type classes including:
18//!   - `Functor`, `Applicative`, `Monad`
19//!   - `Semigroup`, `Monoid`
20//!   - `Foldable`, `Traversable`
21//!   - `Compactable`, `Filterable`, `Witherable`
22//!   - `Category`, `Semigroupoid`
23//!   - `Pointed`, `Lift`, `Defer`, `Once`
24//!   - `ApplyFirst`, `ApplySecond`, `Semiapplicative`, `Semimonad`
25//!   - `Function`, `CloneableFn`, `SendCloneableFn`, `ParFoldable` (Function wrappers and thread-safe operations)
26//!   - `Pointer`, `RefCountedPointer`, `SendRefCountedPointer` (Pointer abstraction)
27//!   - `TrySemigroup`, `TryMonoid`, `SendDefer`
28//! - **Helper Functions:** Standard FP utilities:
29//!   - `compose`, `constant`, `flip`, `identity`
30//! - **Data Types:** Implementations for standard and custom types:
31//!   - `Option`, `Result`, `Vec`, `String`
32//!   - `Identity`, `Lazy`, `Pair`
33//!   - `Endofunction`, `Endomorphism`, `SendEndofunction`
34//!   - `RcBrand`, `ArcBrand`, `FnBrand`
35//!   - `OnceCell`, `OnceLock`
36//!
37//! ## How it Works
38//!
39//! ### Higher-Kinded Types (HKT)
40//!
41//! Since Rust doesn't support HKTs directly (e.g., `trait Functor<F<_>>`), this library uses **Lightweight Higher-Kinded Polymorphism** (also known as the "Brand" pattern or type-level defunctionalization).
42//!
43//! 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.
44//!
45//! ```rust
46//! use fp_library::{impl_kind, kinds::*};
47//!
48//! pub struct OptionBrand;
49//!
50//! impl_kind! {
51//!     for OptionBrand {
52//!         type Of<'a, A: 'a>: 'a = Option<A>;
53//!     }
54//! }
55//! ```
56//!
57//! ### Zero-Cost Abstractions & Uncurried Semantics
58//!
59//! 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.
60//!
61//! **Why?**
62//! Traditional currying in Rust often requires:
63//!
64//! - Creating intermediate closures for each partial application.
65//! - Heap-allocating these closures (boxing) or wrapping them in reference counters (`Rc`/`Arc`) to satisfy type system constraints.
66//! - Dynamic dispatch (`dyn Fn`), which inhibits compiler optimizations like inlining.
67//!
68//! By using uncurried functions with `impl Fn` or generic bounds, `fp-library` achieves **zero-cost abstractions**:
69//!
70//! - **No Heap Allocation:** Operations like `map` and `bind` do not allocate intermediate closures.
71//! - **Static Dispatch:** The compiler can fully monomorphize generic functions, enabling aggressive inlining and optimization.
72//! - **Ownership Friendly:** Better integration with Rust's ownership and borrowing system.
73//!
74//! This approach ensures that using high-level functional abstractions incurs no runtime penalty compared to hand-written imperative code.
75//!
76//! **Exceptions:**
77//! While the library strives for zero-cost abstractions, some operations inherently require dynamic dispatch or heap allocation due to Rust's type system:
78//!
79//! - **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.
80//! - **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.
81//!
82//! 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.
83//!
84//! ### Thread Safety and Parallelism
85//!
86//! The library supports thread-safe operations through the `SendCloneableFn` extension trait and parallel folding via `ParFoldable`.
87//!
88//! - **`SendCloneableFn`**: Extends `CloneableFn` to provide `Send + Sync` function wrappers. Implemented by `ArcFnBrand`.
89//! - **`ParFoldable`**: Provides `par_fold_map` and `par_fold_right` for parallel execution.
90//! - **Rayon Support**: `VecBrand` supports parallel execution using `rayon` when the `rayon` feature is enabled.
91//!
92//! ```
93//! use fp_library::{brands::*, functions::*};
94//!
95//! let v = vec![1, 2, 3, 4, 5];
96//! // Create a thread-safe function wrapper
97//! let f = send_cloneable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
98//! // Fold in parallel (if rayon feature is enabled)
99//! let result = par_fold_map::<ArcFnBrand, VecBrand, _, _>(f, v);
100//! assert_eq!(result, "12345".to_string());
101//! ```
102//!
103//! ## Example: Using `Functor` with `Option`
104//!
105//! ```
106//! use fp_library::{brands::*, functions::*};
107//!
108//! let x = Some(5);
109//! // Map a function over the `Option` using the `Functor` type class
110//! let y = map::<OptionBrand, _, _, _>(|i| i * 2, x);
111//! assert_eq!(y, Some(10));
112//! ```
113//!
114//! ## Crate Features
115//!
116//! - **`rayon`**: Enables parallel folding operations (`ParFoldable`) and parallel execution support for `VecBrand` using the [rayon](https://github.com/rayon-rs/rayon) library.
117
118extern crate fp_macros;
119
120pub mod brands;
121pub mod classes;
122pub mod functions;
123pub mod kinds;
124pub mod types;
125
126pub use fp_macros::Apply;
127pub use fp_macros::Kind;
128pub use fp_macros::def_kind;
129pub use fp_macros::impl_kind;