Skip to content

Instantly share code, notes, and snippets.

@m4rw3r
Created February 28, 2016 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m4rw3r/4e1675c26a2a21b5b41a to your computer and use it in GitHub Desktop.
Save m4rw3r/4e1675c26a2a21b5b41a to your computer and use it in GitHub Desktop.
extern crate rsz;
use rsz::{FunctorMut, HKT, MonadMut, Unit};
// Let's say that this type requires to run the closure multiple times,
// so we can only implement the mutable monads.
pub struct Foo<T> {
inner: T,
}
impl<T, U> HKT<U> for Foo<T> {
type Result = Foo<U>;
}
impl<T, U> FunctorMut<U> for Foo<T> {
fn map<F>(self, mut f: F) -> Self::Result
where F: FnMut(T) -> U {
Foo { inner: f(self.inner) }
}
}
impl<T> Unit for Foo<T> {
type Inner = T;
fn unit(t: Self::Inner) -> Self {
Foo { inner: t }
}
}
impl<T, U> MonadMut<U> for Foo<T> {
fn bind<F>(self, mut f: F) -> Foo<U>
where F: FnMut(T) -> Foo<U> {
f(self.inner)
}
}
#[test]
fn test_monad() {
let a = Foo { inner: 23u32 };
let b = a.bind(|x| Unit::unit(x as f64 * 2.0));
assert_eq!(b.inner, 46f64);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment