Skip to main content

Applicative

Trait Applicative 

Source
pub trait Applicative:
    Pointed
    + Semiapplicative
    + ApplyFirst
    + ApplySecond { }
Expand description

A type class for applicative functors, allowing for values to be wrapped in a context and for functions within a context to be applied to values within a context.

class (Pointed f, Semiapplicative f) => Applicative f

§Laws

Applicative instances must satisfy the following laws:

  • Identity: apply(pure(identity), v) = v.
  • Composition: apply(apply(map(|f| |g| compose(f, g), u), v), w) = apply(u, apply(v, w)).
  • Homomorphism: apply(pure(f), pure(x)) = pure(f(x)).
  • Interchange: apply(u, pure(y)) = apply(pure(|f| f(y)), u).

§Examples

Applicative laws for Option:

use fp_library::{
	brands::*,
	classes::*,
	functions::*,
};

// Identity: apply(pure(identity), v) = v
let v = Some(5);
let id_fn = pure::<OptionBrand, _>(cloneable_fn_new::<RcFnBrand, _, _>(identity::<i32>));
assert_eq!(apply::<RcFnBrand, OptionBrand, _, _>(id_fn, v), v);

// Homomorphism: apply(pure(f), pure(x)) = pure(f(x))
let f = |x: i32| x * 2;
assert_eq!(
	apply::<RcFnBrand, OptionBrand, _, _>(
		pure::<OptionBrand, _>(cloneable_fn_new::<RcFnBrand, _, _>(f)),
		pure::<OptionBrand, _>(5),
	),
	pure::<OptionBrand, _>(f(5)),
);

// Interchange: apply(u, pure(y)) = apply(pure(|f| f(y)), u)
let u = Some(cloneable_fn_new::<RcFnBrand, _, _>(|x: i32| x + 1));
let y = 5i32;
let left = apply::<RcFnBrand, OptionBrand, _, _>(u.clone(), pure::<OptionBrand, _>(y));
let apply_y = pure::<OptionBrand, _>(cloneable_fn_new::<RcFnBrand, _, _>(
	move |f: std::rc::Rc<dyn Fn(i32) -> i32>| f(y),
));
let right = apply::<RcFnBrand, OptionBrand, _, _>(apply_y, u);
assert_eq!(left, right);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<Brand> Applicative for Brand

Blanket implementation of Applicative.

§Type Parameters
  • Brand: The brand type.