Monads in D

Atila Neves via Digitalmars-d digitalmars-d at puremagic.com
Sat Jun 11 07:26:20 PDT 2016


I give you a facsimile of a Haskell do block:

     with(Maybe!int) {
         return_(5).bind!(a => return_(a + 
1)).shouldEqual(just(6));
         nothing.bind!(a => return_(a + 1)).shouldEqual(nothing);
         return_(8).bind!(a => nothing).bind!(a => return_(a + 
1)).shouldEqual(nothing);
     }

     with(Maybe!string) {
         return_("foo").bind!(a => return_(a ~ 
"bar")).shouldEqual(just("foobar"));
         nothing.bind!(a => return_(a ~ 
"bar")).shouldEqual(nothing);
         return_("foo").bind!(a => return_(a ~ "bar")).bind!(a => 
nothing).shouldEqual(nothing);
     }


Why? Because I could, I don't plan on using this for anything 
serious. I think "with" is my favourite D feature right now. I 
also wrote the Writer and State monads (not that D needs them):

https://github.com/atilaneves/felix

I tried overloading `>>>` for bind (closest overloadable operator 
to `>>=`) but it went horribly wrong. I always get problems when 
I try to pass lambdas as runtime values instead of template 
parameters.


Atila



More information about the Digitalmars-d mailing list