[Haskell-cafe] On the verge of ... giving up!
Richard A. O'Keefe
ok at cs.otago.ac.nz
Sun Oct 14 22:54:08 EDT 2007
On 15 Oct 2007, at 2:59 am, Vimal wrote:
> I like the quote found on this site: http://patryshev.com/monad/m-
> Monads in programming seem to be the most mysterious notion of the
> I find two reasons for this:
> * lack of familiarity with category theory;
> * many authors carefully bypass any mention of categories.
> It's like talking about electricity without using calculus.
> Good enough to replace a fuse, not good enough to design an amplifier.
It is true that Haskell Monads are inspired by category theory.
It is also true that all the operations you need for something to
be a category theoretic monad are available for Haskell Monads.
You don't need to know that. Many Haskell programmers not only
don't understand anything much about categories, they will never
understand anything much about categories, and it doesn't matter.
(After years of study, I can now get *to* chapter 3 in the typical
"introduction to category theory* book, but not *through* it.)
The really amazing thing about the IO Monad in Haskell is that
there *isn't* any magic going on. An level of understanding
adequate for using the I/O and State monads stuff (that is,
adequate for practically anything analogous to what you might
do in another language) goes like this:
A type constructor that belongs to the Monad class can be used
to sequence actions over some kind of hidden state. Each of these
actions has an effect and a value. For example, getChar has the
effect of reading a character from standard input, and the character
it read as its value. For example, putChar x has the effect of
writing a character to standard output, and () as its value because
there isn't anything else useful to return. All monad instances
fail msg msg is an error message; this reports
return value an action with value as its value and
act1 >> act2 the effect of (act1 then act2) and the
value of act. THIS IS JUST LIKE SEMICOLON
IN TRADITIONAL LANGUAGES.
act1 >>= actf2 the effect of (act1 then (act2f x))
with the value of act2f x, where x is
the value of act1.
Each monad also typically comes with a function that takes an action and
an initial state and performs the action and returns its value. That
function's name usually starts with "run". For the IO monad, the hidden
state is "the state of the world, including I/O devices", and the "run"
step is done just outside your 'main' function. In order to have an
I/O action performed you should ensure that it is chained into the
sequence actions starting from main and linked by >> and >>= .
That's really all you have to know. The I/O actions in Haskell look
uncommonly like C, and if you can do I/O in C you *can* do I/O in
Haskell without even knowing how to spell 'Category Theory'.
More information about the Haskell-Cafe