[Haskell-beginners] Monads in javascript

Patrick LeBoutillier patrick.leboutillier at gmail.com
Sat Jul 16 13:54:16 CEST 2011


Martin,

> z' = [1,2,3] >>= (\y1->[y1+1] >>= (\y2->return (y1*y2)))

I'm not a Haskell expert, but I think the idea here is that the second
lambda is defined *inside* the first one. I think that's the only way
that it can access the first lambda's argument.

I don't know much Javascript, but here is a small Perl snippet that
(kinda) implements the list monad and your example:


use strict ;
use Data::Dumper ;

sub bindM {
        my $xs = shift ;
        my $fx2ys = shift ;

        # maps and concats in one shot
        my @ys = map {@{$fx2ys->($_)}} @{$xs} ;
        return \@ys ;
}

sub returnM {
        my $x = shift ;

        return [$x] ;
}

sub z {
        my $arg = [1,2,3] ;

        bindM($arg, sub {
                my $y1 = shift ;
                bindM([$y1 + 1], sub {
                        my $y2 = shift ;
                        returnM($y1 * $y2) ;
                }) ;
        }) ;
}

print Dumper(z()), "\n" ;


Since $y1 is local to te first lambda, you have to define the second one inside.


Patrick



>
> works again, which misled me to believe that (>>=) associates to the right.
>
> In javascript a lambda would look like this
>
> f = function(y1) {return [y1+1]}
>
> I cannot see how I could possible write a function (>>=) which chains such
> lambdas such that I can still access the arguments outside the function
> bodies. It is like there are always parentheses around the lambdas. Well there
> actually are braces in javascript, but it can't be just the syntax.
>
> So what is javascript missing? Is it because in haskell a lambda is just an
> expression wheras in javascript it is something special?
>
>
>
>
> --
> Martin
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



-- 
=====================
Patrick LeBoutillier
Rosemère, Québec, Canada



More information about the Beginners mailing list