Deep Causality HAFT
HAFT: Higher-Order Abstract Functional Traits
deep_causality_haft is a sub-crate of the deep_causality project, providing traits for Higher-Kinded Types (HKTs) in
Rust. This enables writing generic, abstract code that can operate over different container types like Option<T> and
Result<T, E>.
What are Higher-Kinded Types?
In Rust, types like Option<T> and Vec<T> are generic over a type T. We can think of Option and Vec as "type
constructors": they take a type and produce a new type.
A Higher-Kinded Type is an abstraction over these type constructors. It allows us to write functions that are generic
not just over a type, but over the shape or kind of a type constructor. For example, we can write a function that
works with any type constructor that can be mapped over (a Functor), without caring if it's an Option, a Result,
or something else.
This crate provides the fundamental traits (HKT, HKT2, HKT3, HKT4, HKT5) and functional traits (Functor,
Applicative, Monad, Foldable, Traversable) to enable this pattern.
Usage
This crate uses a "witness" pattern to represent HKTs. For each type constructor (like Option), we define a
zero-sized "witness" type (like OptionWitness) that implements the HKT trait. These witness types are zero-sized
and incur no runtime overhead, making them zero-cost abstractions. This crates also comes with default
witness pattern implementations for commonly used Rust types such as:
- Option -> OptionWitness
- Result -> ResultWitness
- Box -> BoxWitness
- Vec -> VecWitness
Each of those withness types implements the following traits and methods:
- Applicative:
pure<T>(value: T)andapply<A, B, Func>(f_ab:HKT, f_a:HKT) - Functor:
fmap<A, B, Func>(m_a: HKT, f: Func) - Foldable:
fold<A, B, Func>(fa: HKT, init: B, f: Func) - Monad:
bind<A, B, Func>(m_a:HKT, f: Func)
Witness types that only implement Functor and Fold:
- BTreeMap -> BTreeMapWitness
- HashMap -> HashMapWitness
- VecDeque -> VecDequeWitness
Example: Using Functor and HKT in a generic function
use *;
When you run the example via:
cargo run --example haft_functor_example
You will see:
Original Option: Some(5)
Doubled Option: Some(10)
Original Result: Ok(5)
Doubled Result: Ok(10)
Original Box: 7
Doubled Box: 14
Original Vec: [1, 2, 3]
Doubled Vec: [2, 4, 6]
Original VecDec: [2, 4, 6]
Doubled VecDec: [4, 8, 12]
When combined with the deep_causality_num crate, you can abstract even further:
use ;
use ;
This level of abstraction helps in domains like numerical computing where you often deal with various data structures holding different numeric types. It allows for highly expressive and maintainable code that preserves high performance characteristics.
Example: Using Functor with Option
Here's how you can use the Functor trait with Option via its witness type, OptionWitness.
use ;
Example: Using Functor with Result
Here's how you can use the Functor trait with Result<T, E> via its witness type, ResultWitness<E>. HKT2 is used
here because Result has two generic parameters, and we are fixing the error type E.
use ;
Example: Using Foldable with Vec
I
Here's how you can use the Foldable trait with Vec via its witness type, VecWitness.
use ;
Type-Encoded Effect System
use *;
use ;
// 1. Start with a pure value, lifting it into the effect context
let initial_effect: = pure;
// 2. Define a collection of step functions
// Each function takes an i32 and returns an effectful i32
let step_functions: = vec!;
// 3. Execute all step functions in sequence
println!;
let mut current_effect = initial_effect;
for in step_functions.into_iter.enumerate
println!;
When you run the example via:
cargo run --example haft_effect_system_example
You will see:
Initial effect (pure 10): MyCustomEffectType5 { value: 10, f1: None, f2: [], f3: [], f4: [] }
Process Steps:
Log (Step 1): Operation A: Multiplied by 2
Log (Step 2): Operation B: Added 5
Log (Step 3): Operation C: Multiplied by 3
Sequenced outcome: 75
... (Truncated)
The Effect3, Effect4, Effect5 and MonadEffect3, MonadEffect4, MonadEffect5 traits provide a powerful
mechanism for building a type-encoded effect system. This allows you to manage side-effects (like errors and
logging) in a structured, safe, and composable way, which is particularly useful for building complex data processing
pipelines. It leverages Rust's powerful type system to ensure that these effects are explicitly handled
and tracked throughout your program.
Here's a breakdown of how it works:
-
Effects as Types: Instead of side-effects occurring implicitly, this system represents them explicitly as generic type parameters on a container type. For instance, you might have a custom effect type like
MyCustomEffectType<T, E, W>, where:Tis the primary value of the computation.Erepresents an error type.Wrepresents a warning or log type. By making these effects part of the type signature, the presence of potential side-effects becomes explicit and verifiable by the compiler.
-
Higher-Kinded Type (HKT) Witnesses: To make these effect types generic over their primary value
Twhile keeping the effect types (E,W, etc.) fixed, the system utilizes Higher-Kinded Types (HKTs). Traits likeEffect3,Effect4, andEffect5are used to "fix" a certain number of generic parameters of an underlying HKT type (e.g.,HKT3,HKT4,HKT5). This allows you to define a "witness" type (e.g.,MyEffectHktWitness<E, W>) that represents the shape of your effect container with specific, fixed effect types, leaving one parameter (T) open for the actual value. -
Monadic Logic for Effects (
MonadEffecttraits): The core logic for how these effects are handled and combined is defined throughMonadEffecttraits (e.g.,MonadEffect3,MonadEffect4,MonadEffect5). These traits provide:pure: A method to lift a "pure" value (a value without any side-effects) into the effectful context.bind: The central sequencing operation. It allows you to chain computations where each step might produce new effects. The implementation ofbinddictates how effects from different steps are combined. For example, in the providedMyCustomEffectType, thebindimplementation ensures that if an error occurs at any point, it propagates, and warnings from all steps are accumulated.
-
Specialized Effect Handling (
LoggableEffecttraits): The system can be extended with specialized traits for specific types of effects. For example,LoggableEffect3,LoggableEffect4, andLoggableEffect5provide alogfunction. This function allows you to add a log message (of a specific fixed type, likeE::Fixed2forLoggableEffect3) to the effect container without altering the primary value or causing an error. -
Compiler-Enforced Safety: A significant advantage of this system is that because effects are part of the type signature, the Rust compiler statically verifies that all effects are handled correctly. This means that if a function is declared to produce a certain type of effect, the compiler ensures that the effect is either explicitly handled or propagated. This prevents common bugs related to unhandled errors or forgotten logging, leading to more robust and predictable code.
Unbound HKTs & Functional Traits (Arity 2-5)
This crate also supports "Unbound" Higher-Kinded Types, where all generic parameters are free to vary. This enables advanced functional patterns from Category Theory that are crucial for complex systems modeling.
Unbound HKT Traits
HKT2Unbound-HKT5Unbound: Base traits for multi-arity type constructors (e.g.,Result<A, B>,(A, B, C)).Bifunctor: Maps over both types of a binary constructor simultaneously.- Usage: Evolving a coupled system (e.g.,
(Metric, Plasma)) where both components change type.
- Usage: Evolving a coupled system (e.g.,
Profunctor: Contravariant input, Covariant output.- Usage: Adapters, Optics, and State Machines where you pre-process input and post-process output.
Adjunction: Defines a dual relationship between two functors ($L \dashv R$).- Usage: Conservation laws, optimization (Primal/Dual), and Galois connections.
ParametricMonad: A Monad where the state type changes (Indexed Monad).- Usage: Modeling state transitions (e.g.,
Solid -> Liquid -> Gas) or protocol state machines.
- Usage: Modeling state transitions (e.g.,
Promonad: Models interaction or fusion of contexts.- Usage: Tensor products, force calculations (merging fields), and quantum entanglement.
RiemannMap: Models curvature and scattering (Arity 4).- Usage: General Relativity (Curvature Tensor), Particle Physics (Scattering Matrices).
CyberneticLoop: Models a complete feedback control loop (Arity 5).- Usage: Autonomous agents (OODA Loop), Control Theory, and Error Correction.
Example: Bifunctor
use ;
;
// Usage
let res: = Ok;
let new_res = bimap; // Result<f64, usize>
non-std support
The deep_causality_haft crate provides support for no-std environments. This is particularly useful for embedded systems or other contexts where the standard library is not available. Note, the std feature is enabled by default thus you need to opt-into non-std via feature flags.
To use this crate in a no-std environment, you need to disable the default std feature. You can optionally enable the alloc feature if you have an allocator available, which enables support for dynamic collections like Vec, Box, BTreeMap, etc.
Cargo Build and Test for no-std
1. Building for no-std with Allocator:
To build the crate for no-std while including support for dynamic collections (via alloc), use the following command:
2. Testing for no-std with Allocator:
To run tests in a no-std environment with allocator support, use:
3. Building for no-std without Allocator (Core/Algebra only):
If your no-std application does not have an allocator, you can build without the alloc feature. This restricts the crate to core HKT traits and algebraic structures that don't require dynamic memory.
4. Testing for no-std without Allocator:
Bazel Build
For regular (std) builds, run:
and
for tests. When you want to build for non-std, use
and
👨💻👩💻 Contribution
Contributions are welcomed especially related to documentation, example code, and fixes. If unsure where to start, just open an issue and ask.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in deep_causality by you, shall be licensed under the MIT licence, without any additional terms or conditions.
📜 Licence
This project is licensed under the MIT license.
👮️ Security
For details about security, please read the security policy.