Grafting Functional Support on Top of an Imperative Language
Simen Kjaeraas
simen.kjaras at gmail.com
Fri Apr 4 17:54:26 PDT 2008
On Sat, 05 Apr 2008 02:03:29 +0200, Bill Baxter
<dnewsgroup at billbaxter.com> wrote:
> Simen Kjaeraas wrote:
>> On Sat, 05 Apr 2008 01:09:14 +0200, Jason House
>> <jason.james.house at gmail.com> wrote:
>>
>>> bearophile wrote:
>>>> P. 31: >writeln(i);<
>>>>
>>>> Can you put (temporary) debugging writeln/putr inside a pure function?
>>>
>>> That's always bothered me about this stuff. I don't want to lose
>>> debugging/logging ability!
>> Just use multiple return types, and have the caller do the printing.
>> --Simen
>
>
> Monads!
>
> Or at least I think that's what I read somewhere. I can't understand
> the buggers for the life of me. I think maybe it's just a fancy word
> for "loophole". If someone here has a good explanation for what a monad
> is and how it allows mutable state in FP without making thing non-FP,
> I'd love to hear it. Because I just don't get it.
>
> --bb
I read a bit on Wikipedia about monads, and they seem to me to be a fancy
way to do multiple return values. I'm not sure if they're usable
(hackable) in D at the moment, or if we need to wait for AST macros before
we can use them as they should. But one example, the 'maybe' monad, seems
to me a bit like this:
struct Maybe(T)
{
bool Nothing;
T data;
static Maybe!(U) opCall(U)(lazy U u)
{
typeof(return) tmp;
try
{
data = u();
tmp.Nothing = false;
}
catch (object o)
{
tmp.Nothing = true; // something went wrong, data is invalid
}
}
T opAdd(T rhs)
{
if (Nothing)
return rhs; // act as if data is nonexistant
else
return data + rhs;
}
// other operators overloaded in similar ways
}
Disclaimer: This might or might not work. It might contain some value of
truth, and it might not. It is merely my understanding after a half-hour
of reading at 2:30 in the morning, and so should be sanity-checked before
use.
-- Simen
More information about the Digitalmars-d
mailing list