Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created December 1, 2020 02:53
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 rust-play/61caef82814783feadc33a3b865fe8b3 to your computer and use it in GitHub Desktop.
Save rust-play/61caef82814783feadc33a3b865fe8b3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![feature(generic_associated_types)]
trait Monad /* : Applicative (for pure/return, doesn't matter for this example) */ {
// Self is like the "f a" in haskell
/// extract the "a" from "f a"
type Unplug;
/// exchange the "a" in "f a" in the type of Self with B
type Plug<B>: Monad;
fn bind<B, F>(self, f: F) -> Self::Plug<B>
where
F: Fn(Self::Unplug) -> Self::Plug<B>;
}
impl<A> Monad for Option<A> {
type Unplug = A;
type Plug<B> = Option<B>;
fn bind<B, F>(self, f: F) -> Option<B>
where
F: Fn(A) -> Option<B>,
{
self.and_then(f)
}
}
fn main() {
let x = Some(1).bind(|x| Some(x * 2));
println!("{:?}", x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment