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(|| Some(222)); println!("{:?}", v2); }
In this example, the normal Option constructors, Some or None, take the place of the monadic naming convention, return. There are two semi-monads implemented here, one associated...