Created
February 28, 2016 23:22
-
-
Save m4rw3r/4e1675c26a2a21b5b41a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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