|
![](/i/fill.gif) |
On 20/04/2012 03:21 PM, Warp wrote:
> Invisible<voi### [at] dev null> wrote:
>> One Haskell VFAQ is "What is a monad?"
>
> Would it be extremely wrong to say that a monad is like a barrier?
Not really. Monads aren't particularly related to threading.
More like... I can write this in C:
{
foo();
bar();
baz();
}
Obviously, this calls three functions, one after the other.
In Haskell, I can write this:
do
foo
bar
baz
What /this/ does is that between each of the function calls you can see,
it invisibly inserts a new call to this magical "bind function" that I
keep talking about. So it's like writing
{
foo();
bind();
bar();
bind();
baz();
}
In fact, it's not even like that, because each time bind() is called,
the entire rest of the code block is passed to it as an argument. And
that means that bind() can decide to /not run it/, or to /run it
multiple times/ or whatever else it feels like doing.
So, it's actually something like this:
foo();
bind(
bar();
bind(
baz();
);
);
[Obviously, if that were actually valid syntax in some known programming
language.]
Actually, it's even more complicated than that, because each call to
bind() gets the result from the previous function call as an argument
too. So it's more like
ResultInfo i1 = foo();
bind(i1,
ResultInfo i2 = bar();
bind(i2,
baz();
);
);
Each function, even if it doesn't "return anything", is actually
returning some kind of data structure representing the actions that the
function took. And bind() can look at that data and decide whether or
not it feels like running the rest of the code block.
So when I say that "a monad is a programmable semicolon", what I /mean/
is that everywhere there's a semicolon, the compiler is calling a
user-defined function, which can make the code do quirky, unexpected things.
When you say it like /that/, suddenly it's not so surprising that
monadic code can be configured to run lines multiple times, or pass
secret data around invisibly, or whatever.
Post a reply to this message
|
![](/i/fill.gif) |