[Haskell-beginners] Monads in javascript
Ertugrul Soeylemez
es at ertes.de
Wed Jul 13 00:03:44 CEST 2011
Martin Drautzburg <Martin.Drautzburg at web.de> wrote:
> I found some implementations of Monads in javascript, but they all do
> not allow capturing the intermediate results. My question is: "what is
> the ultimate cause for this"?
>
> In haskell the second argument to (>>=) is a function a->Mb which can
> be written as a lambda expression, e.g.
> \x->[x].
> In javascript such a function would be written as
> function(x) {return[x]}.
>
> Did I get this right: in haskell the chain of >>= is constructed from
> the end?
Composition by (>>=) is by definition associative, so it really doesn't
matter how you set your parentheses.
> So chaining a->Mb and b->Mc gives you a->Mc, which is again suitable
> as a second argument to (>>=), right?
Yes, but beware that you may be confusing (>>=) with (>=>).
> So why can't I do this is javascipt? Or can I?
I don't see why that should be a problem. Note that there are many
different ways to represent monads. Haskell represents them in terms of
'fmap', 'return' and (>>=).
> The reason I am asking this is because I am trying to beautify
> callbacks. An asynchronous ajax call needs a function argument, which
> will be executed once the call completes. But what if I want to take
> the results of the first call, do something with them and pass it to a
> second ajax call, where I would again have to pass another function
> argument. I would end up with a deeply nested structure of lambdas,
> something like
>
> f(a,b,...function(...){
> ...
> g(... function(...)
>
> I had some hopes that chaining functions monad-style would ease my
> pain. I might be on the wrong track though, feel free to tell me so.
You probably are, because the usefulness of monads depends a good deal
on syntax. ECMA-based languages like JavaScript, ActionScript, Haxe,
etc. have a terrible syntax for anonymous functions.
To give you an alternative, this really sounds like you're looking for a
continuation-based solution. Continuation passing style could really
solve your problem elegantly even in JavaScript.
Greets,
Ertugrul
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/
More information about the Beginners
mailing list