Tuesday, January 30, 2007

A Haskell Epiphanette

A link on reddit led me to this:


I think it’s important/useful to point out that “program flow” in a pure functional language is really a matter of data dependency. The compiler is only free to arbitrarily order computations if there are no data dependencies. Furthermore, monads are not special in any way (they are after all just a useful set of combinators; … they only wind up sequencing computations because they set up a data dependency between the two arguments of the bind operator.
-Jeff [bold added by me]

I’m a newbie to Haskell, and like all Haskell newbies, I’m still working through the Monad fog. On the surface, they appeared to me to be not much more than a way to cheat - to write in an imperative style in Haskell. So, I thought, if in the long run all you are really doing in Haskell is writing a bunch of commands, just as you would in C++ or any other imperative language, then what’s the point? Although you could argue that the net result is the same, i.e., you are effectively giving the computer a specific set of instructions to carry out, and in what order (basically), the quote above gave me a new perspective. Sometimes it just takes a little kick…:-)

3 comments:

Anonymous said...

Monads aren't cheating, they're just short cut for:
f :: regular -> parameters -> state -> (results, new_state)

without all the manual and error prone state flow wiring.

עמיר ליבנה בר-און said...

The monad that is usually used for sequencing of operations is IO, which represents real-world actions. This is the way you tag outside libraries and interfaces. For example, the part of your program that uses GTK, or accesses files and databases will have to be in the IO monad. This kind of code will also be very similar between Haskell and every other programming language.

However, the core part of most Haskell program is not in the IO monad, It is algorithmic code, in pure functional style. This gives you laziness, strong equations on your program, automatic code generation using type-classes, and the monad transformer library - which contains the really interesting monads.

This library allow you to specify very selectively which non-pure actions you want. For example, you can declare that a function is pure, except being able to use non-deterministic computation and generation of random numbers. Or a function that can write to a log file, and also raise exceptions, but access no network connections.

To learn these advanced features, you first need to know the basics - getting code to compile, print hello, et cetera. Happily, many tutorials in the Haskell wiki are available, just for that purpose. Have fun learning!

Cale Gibbard said...

The anonymous poster described the state monad only. There are plenty of other monads out there with more interesting control mechanisms.