Module frunk::coproduct [] [src]

Module that holds Coproduct data structures, traits, and implementations

Think of "Coproduct" as ad-hoc enums; allowing you to do something like this

// For simplicity, assign our Coproduct type to a type alias
// This is purely optional.
type I32Bool = Coprod!(i32, bool);
// Inject things into our Coproduct type
let co1 = I32Bool::inject(3);
let co2 = I32Bool::inject(true);

// Getting stuff
let get_from_1a: Option<&i32> = co1.get();
let get_from_1b: Option<&bool> = co1.get();
assert_eq!(get_from_1a, Some(&3));
assert_eq!(get_from_1b, None);

let get_from_2a: Option<&i32> = co2.get();
let get_from_2b: Option<&bool> = co2.get();
assert_eq!(get_from_2a, None);
assert_eq!(get_from_2b, Some(&true));

// *Taking* stuff (by value)
let take_from_1a: Option<i32> = co1.take();
assert_eq!(take_from_1a, Some(3));Run

Or, if you want to "fold" over all possible values of a coproduct

// In the below, we use unimplemented!() to make it obvious hat we know what type of
// item is inside our coproducts co1 and co2 but in real life, you should be writing
// complete functions for all the cases when folding coproducts
assert_eq!(
    co1.as_ref().fold(hlist![|&i| format!("i32 {}", i),
                             |&b| unimplemented!() /* we know this won't happen for co1 */ ]),
    "i32 3".to_string());
assert_eq!(
    co2.as_ref().fold(hlist![|&i| unimplemented!() /* we know this won't happen for co2 */,
                             |&b| String::from(if b { "t" } else { "f" })]),
    "t".to_string());

// There is also a value consuming-variant of fold

let folded = co1.fold(hlist![|i| format!("i32 {}", i),
                             |b| String::from(if b { "t" } else { "f" })]);
assert_eq!(folded, "i32 3".to_string());Run

Enums

CNil

Phantom type for signature purposes only (has no value)

Coproduct

Enum type representing a Coproduct. Think of this as a Result, but capable of supporting any arbitrary number of types instead of just 2.

Traits

CoprodInjector

Trait for injecting something into a coproduct

CoproductFoldable

Trait for implementing "folding" a Coproduct into a value.

CoproductSelector

Trait for retrieving a coproduct element reference by type.

CoproductTaker

Trait for retrieving a coproduct element by type.