[][src]Crate monadic

Haskell style "monadic" macro where monad sources should be expressions of type instances of IntoIterator.

Each monad expression is flat_mapped with the lambda expression having the monad result variable as argument and the rest as its body, into a lazy FlatMap expression that is also an instance of IntoIterator, and can be collected into any instance of FromIterator.

To use pure to lift a value, a monad implementation must be used, beeing Option::pure(x) the least costly option, or just Some(x).

use monadic::{monadic, Monad};
use num::Integer;

   let xs = monadic!{ 
       x <- 1..5;
       y <- 1..x;
       guard x.is_odd();
       let z = y - 1;
       Vec::pure((x,z)) 
   }.collect::<Vec<(i32,i32)>>();
    
   println!("result: {:?}", xs); 

    
   let ys = monadic!{ 
    
       &x <- &vec![1,2,3,4];  // with item refs (&x) in the lambda argument position
       guard x.is_odd() ;
       let z = x + 1 ;
       Option::pure((*x, z)) 
        
   }.collect::<Vec<(i32,i32)>>();
    
   println!("result: {:?}", ys); 

 // test:

 fn it_works() {
       let xs = (1..5).collect::<Vec<i32>>();
       // expected
       let zs = (&xs).into_iter().filter(|&v| v < &4).map(|v| v*2).collect::<Vec<i32>>();
       // monadic
       let ys = monadic!{
          v <- &xs;
          guard v < &4;
          Option::pure( v * 2)
       }.collect::<Vec<i32>>();
        
       assert_eq!(ys, zs);
   }

Re-exports

pub use monad::Monad;

Modules

monad

Macros

monadic

converting monadic blocs of IntoIterator's as monads à la Haskell