Sun Apr 22 09:38:40 EDT 2012
Real-world programming in Haskell
A beginner's critique on using Haskell for real-world programming
(i.e. not just writing a compiler or other data -> data converter).
Haskell is great for refactoring code in small increments. However,
introducing state is often a fairly large structural change. I found
this to be a non-trivial learning step.
Contrary to what is advertised often, adding state to a functional
algorithm isn't easy: it's a large syntactical change touching a lot
of code. Once the framework of state is in place (Monad or
Applicative or Arrow ...), THEN it becomes easy to pick-and-choose the
side effect. However, going from pure to side-effect isn't always
The pattern I've seen is that state is usually necessary to make the
leaf nodes of a tree processing algorithm share some information. In
an imperative language this is a no-brainer. In a pure functional
language this is a truly big change which has to be anticipated,
i.e. better always think that state is going to be part of the
As seen on HN,
"Functional programming" in the real world isn't about dogmatically
eliminating mutable state. It's about managing it. It's about
As always, abstraction is your friend. The basic idea in pure
functional programming seems to be that "recursion is a low-level
operation". You should always abstract recursion behind an operator.
This way, moving from pure to side-effects is a lot easier.
One way I've found useful to do this is by using Traversable (or
Foldable) instances. Traversable gives you a "map with side-effects",
i.e. the good old for loop with local loop state.
Once a for loop is present, ad-hoc, local monad contraptions can be
used to perform any kind of side-effect during traversal.
This is a nice approach, but requires some getting used to.
The big revelation while working with this kind of approach is that
making all connections explicit shows quite clearly how imperative
programming often relies on "arbitrary connections" hidden in access
to global state, breaking modularity.