Grafting Functional Support on Top of an Imperative Language
Jarrett Billingsley
kb3ctd2 at yahoo.com
Fri Apr 4 20:15:51 PDT 2008
"Bill Baxter" <dnewsgroup at billbaxter.com> wrote in message
news:ft6fkf$1m9v$1 at digitalmars.com...
> 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'm not one to be listened to, but I think the idea behind monads is to wrap
an inherently impure action (like IO) in a functional shell. In an
imperative language, you do something like:
print("Enter your name: ")
name = readLine()
print("Hi, ", name)
Each of those function calls is impure, as they change the state of the
computer. A "pure" way of doing it is:
// we start with state defined at the beginning of the program
state = print(state, "Enter your name: ")
(state, name) = readLine(state)
state = print(state, "Hi, ", name)
(readLine returns two values.)
This creates an ordering of the execution of statements, which is one part
of the "imperative" problem that monads solve (since functional code does
not have any set ordering of execution).
I think a monad basically wraps up the ugliness of getting and passing the
state into a nicer-looking syntax, i.e.
do
putStr "Enter your name: "
name <- readLine -- this isn't named this, I don't think..
putStr "Hi, "
putStrLn name
which, in Haskell, is really just syntactic sugar which hides all the
horrible IO Monad manipulation.
But again, I'm not one to be listened to ;)
More information about the Digitalmars-d
mailing list