Using the monad pattern

A monad defines return and bind operations for a type. The return operation is like a constructor to make the monad. The bind operation incorporates new information and returns a new monad. There are also several laws that monads should obey. Rather than quote the laws, we'll just say that monads should behave well when daisy chained like the following:

MyMonad::return(value)  //We start with a new MyMonad<A>        .bind(|x| x+x)  //We take a step into MyMonad<B>        .bind(|y| y*y); //Similarly we get to MyMonad<C>

In Rust, there are several semi-monads that appear in standard libraries:

fn main(){   let v1 = Some(2).and_then(|x| Some(x+x)).and_then(|y| Some(y*y));   println!("{:?}", v1); let v2 = None.or_else(|| None).or_else(|| ...

Get Hands-On Functional Programming in Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.