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`, `ClonableFn`, `SendClonableFn`, `ParFoldable` (Function wrappers and thread-safe operations)
26//! - **Helper Functions:** Standard FP utilities:
27//! - `compose`, `constant`, `flip`, `identity`
28//! - **Data Types:** Implementations for standard and custom types:
29//! - `Option`, `Result`, `Vec`, `String`
30//! - `Identity`, `Lazy`, `Pair`
31//! - `Endofunction`, `Endomorphism`, `SendEndofunction`
32//! - `RcFn`, `ArcFn`
33//! - `OnceCell`, `OnceLock`
34//!
35//! ## How it Works
36//!
37//! ### Higher-Kinded Types (HKT)
38//!
39//! 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).
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.
81//!
82//! ### Thread Safety and Parallelism
83//!
84//! The library supports thread-safe operations through the `SendClonableFn` extension trait and parallel folding via `ParFoldable`.
85//!
86//! - **`SendClonableFn`**: Extends `ClonableFn` to provide `Send + Sync` function wrappers. Implemented by `ArcFnBrand`.
87//! - **`ParFoldable`**: Provides `par_fold_map` and `par_fold_right` for parallel execution.
88//! - **Rayon Support**: `VecBrand` supports parallel execution using `rayon` when the `rayon` feature is enabled.
89//!
90//! ```
91//! use fp_library::{brands::*, functions::*};
92//!
93//! let v = vec![1, 2, 3, 4, 5];
94//! // Create a thread-safe function wrapper
95//! let f = send_clonable_fn_new::<ArcFnBrand, _, _>(|x: i32| x.to_string());
96//! // Fold in parallel (if rayon feature is enabled)
97//! let result = par_fold_map::<ArcFnBrand, VecBrand, _, _>(f, v);
98//! assert_eq!(result, "12345".to_string());
99//! ```
100//!
101//! ## Example: Using `Functor` with `Option`
102//!
103//! ```
104//! use fp_library::{brands::*, functions::*};
105//!
106//! let x = Some(5);
107//! // Map a function over the `Option` using the `Functor` type class
108//! let y = map::<OptionBrand, _, _, _>(|i| i * 2, x);
109//! assert_eq!(y, Some(10));
110//! ```
111//!
112//! ## Crate Features
113//!
114//! - **`rayon`**: Enables parallel folding operations (`ParFoldable`) and parallel execution support for `VecBrand` using the [rayon](https://github.com/rayon-rs/rayon) library.
115
116extern crate fp_macros;
117
118pub mod brands;
119pub mod classes;
120pub mod functions;
121pub mod kinds;
122pub mod types;
123
124pub use fp_macros::Apply;
125pub use fp_macros::Kind;
126pub use fp_macros::def_kind;
127pub use fp_macros::impl_kind;