Struct morphism::Morphism
[−]
[src]
pub struct Morphism<'a, A, B = A> { // some fields omitted }
A suspended chain of closures that behave as a function from type
A
to type B
.
When B = A
the parameter B
can be omitted: Morphism<'a, A>
is equivalent to Morphism<'a, A, A>
. This is convenient for
providing annotations with Morphism::new()
.
Methods
impl Morphism<'static, Void>
fn new<'a, A>() -> Morphism<'a, A>
Create the identity chain.
Example
use morphism::Morphism; assert_eq!(Morphism::new::<u64>().run(42u64), 42u64);
impl<'a, B, C> Morphism<'a, B, C>
unsafe fn unsafe_push_front<A, F>(&mut self, f: F) where F: Fn(A) -> B + 'a
fn head<A, F>(self, f: F) -> Morphism<'a, A, C> where F: Fn(A) -> B + 'a
Attach a closure to the front of the closure chain. This corresponds to closure composition at the domain (pre-composition).
Example
use morphism::Morphism; let f = Morphism::new::<Option<String>>() .head(|x: Option<u64>| x.map(|y| y.to_string())) .head(|x: Option<u64>| x.map(|y| y - 42u64)) .head(|x: u64| Some(x + 42u64 + 42u64)); assert_eq!(f.run(0u64), Some("42".to_string()));
fn push_front<F>(&mut self, f: F) where F: Fn(B) -> B + 'a
Mutate a given Morphism<B, C>
by pushing a closure of type
Fn(B) -> B
onto the front of the chain.
Example
use morphism::Morphism; let mut f = Morphism::new::<u64>(); for i in (0..10u64) { (&mut f).push_front(move |x| x + i); } assert_eq!(f.run(0u64), 45u64);
impl<'a, A, B> Morphism<'a, A, B>
unsafe fn unsafe_push_back<C, F>(&mut self, f: F) where F: Fn(B) -> C + 'a
fn tail<C, F>(self, f: F) -> Morphism<'a, A, C> where F: Fn(B) -> C + 'a
Attach a closure to the back of the closure chain. This corresponds to closure composition at the codomain (post-composition).
Example
use morphism::Morphism; let f = Morphism::new::<u64>() .tail(|x| Some(x + 42u64 + 42u64)) .tail(|x| x.map(|y| y - 42u64)) .tail(|x| x.map(|y| y.to_string())); assert_eq!(f.run(0u64), Some("42".to_string()));
fn push_back<F>(&mut self, f: F) where F: Fn(B) -> B + 'a
Mutate a given Morphism<A, B>
by pushing a closure of type
Fn(B) -> B
onto the back of the chain.
Example
use morphism::Morphism; let mut f = Morphism::new::<u64>(); for i in (0..10u64) { (&mut f).push_back(move |x| x + i); } assert_eq!(f.run(0u64), 45u64);
fn then<C>(self, other: Morphism<'a, B, C>) -> Morphism<'a, A, C>
Compose one Morphism
with another.
Example
use morphism::Morphism; let mut f = Morphism::new::<u64>(); for _ in (0..100000u64) { f = f.tail(|x| x + 42u64); } // the type changes to Morphism<u64, Option<u64>> so rebind f let f = f.tail(|x| Some(x)); let mut g = Morphism::new::<Option<u64>>(); for _ in (0..99999u64) { g = g.tail(|x| x.map(|y| y - 42u64)); } // the type changes to Morphism<Option<u64>, String> so rebind g let g = g.tail(|x| x.map(|y| y + 1000u64).unwrap().to_string()); assert_eq!(f.then(g).run(0u64), "1042".to_string());
fn run(&self, x: A) -> B
Given an argument, run the chain of closures in a loop and return the final result.