Enjoying Haskell

I’ve been reading about Haskell quite a bit during the last months, writing some actual code, and liking the language more and more. After many years favouring dynamically typed languages, i’m beginning to really appreciate Haskell’s type system and the benefits it brings to the table.

A common argument from the static typing camp is that the compiler is catching a whole class of bugs for you, to which dynamic types answer that a good test suite (which you need anyway for any serious development) will catch those relatively trivial bugs for you. I tend to agree with the dynamic faction on this issue, but then i think that the strength of static typing (coupled with good type inference) is not at all about the compiler catching typing bugs but, rather, as enforcing useful constraints. When you write Haskell, you have to think hard about your data types and the functions using them; and the compiler will keep complaining and, most importantly, the code will feel awkward and somehow ad hoc until you find a good set of types to solve your problem.

The limits to your freedom imposed by the type system entail, in my experience, a boost in the amount of thought and imagination that i put in my design and implementation, in much the same way as the constraints imposed by metric and rhythm to poetic writing boost creativity and actually help producing a beautiful text. Or, in fact, in the same way as any kind of constraint in any creative endeavour helps (paradoxically, at first sight) in attaining beauty, or, at least, in having fun during the process.

In my experience, the process of writing a program or library in any language is always a struggle to find the right way of expressing the solution to a problem, as the culmination of a series of approximations. The code feels better, more expressive and easy-flowing with each rewrite, until something just clicks and i get this feeling that i’ve finally captured the essence of the problem (a litmus test being that then it’s natural to extend the solution to cases i hadn’t thought of when writing the solution, as if, somehow, the new solutions were already there, waiting for you to discover them). And i’m finding that the powerful type system offered by Haskell (think not only of vanilla Hindley-Milner, but also of extensions such as GADTs or type families) is helping me reaching the (local) optimum quicker, that satisfying constraints means i’m closer to the final solution when my code compiles for the first time. You often hear Haskell programmers saying something similar (“once my code compiles, it works”), and i think it’s mostly true, except that the real reason is not that the compiler is catching trivial typing bugs, but, rather, that the constraints imposed by the type system are making you think harder and find the right solution. Same thing with monads, and the clean separation they provide for stateful computations: again, you must think carefully about the right combination of monads and pure code to solve the problem, and most of the time your code will simply not type check if you don’t get the solution right.

There are two more ways that Haskell’s type system is helping me writing better programs. Two ways that are especially poignant when the code becomes sizeable enough. The first one is self-documentation: seeing the type of my functions (or asking the interpreter for them) instantly informs me of almost everything i need to know to use them; in fact, when writing in dynamic languages i keep annotating function signatures with this same information, only that there i’m all by myself to ensure that this information is right. PLT contract system is but a recognition of the usefulness of typing in this regard, although i much prefer the terseness and notational elegance of Haskell’s type signatures over the much more verbose and, to my eyes, somewhat clunky notation used by PLT (which is not really PLT’s fault, being as it is a very schemish notation). Let me stress here that having a REPL such as ghci is a god-send (and, to me, a necessity for really enjoying the language): it will tell me the type of an expression in much the same way as decent Lisp or Scheme environments will report a function’s signature.

The second way Haskell’s lending a helping hand with non-trivial code base is refactoring. As i mentioned above, i rewrite my programs several times as a rule, and rewrites almost always involve modifying data structures or adding new ones. As i grow older, i find it more and more difficult to keep in my head all the places and ways a given data structure is used in my programs, and with dynamic languages i’m often falling back to grepping the source code to find them. And again, their plasticity often works against me, in that they let me use those data structures in crooked ways, or forget to take into account new fields or constructors for a modified data type. Haskell’s compiler has proved an invaluable ally to my refactorings and, by comparison, modifying and maintaining my bigger dynamic programs is not as fun as it used to be.

As an aside, types are not the only thing i’m finding enjoyable about Haskell. Its astonishing capabilities to express very abstract problems with a remarkable economy of expression (due, in part, to its highly tuned syntax) are extremely useful. To my mind, they mimic the process by which in math we solve harder and harder problems by abstracting more and more, cramming together more relevant information in less space (some cognitive science writers will tell you that thought and even consciousness consists on our ability to compress information). That means that i can express my solutions by capturing them in very high level description: initially, that makes them harder to understand, but once i feel comfortable with the basic concepts and operations, they scale up much, much better than more verbose, less sophisticated ones. Using these new hard-earned concepts, i can solve much harder problems without adding to the complexity of the code in a significant way (one could say, using a loose analogy, that the solutions grow logarithmically with complexity instead of polynomically or exponentially). A direct consequence of this expressiveness is that some well-written Haskell programs are, hands down, the most beautiful pieces of code i’ve ever seen (just pick a random post at, say, a Neighbohood of Infinity and you’ll see what i mean; or read Richard Bird’s Sodoku solver and compare his solution with one written in your favourite programming language).

Finally, let me say that i find programming in Haskell more difficult than programming in any other language i’ve used, with perhaps the only exception of Prolog. Sometimes, considerably so. And that’s perfectly fine with me. For one thing, it makes it more interesting and rewarding. In addition, i’m convinced that that’s the price to pay for being able to solve harder problems. I take issue with the frequent pleas to the effect that programming should be effortless or trivial: writing good programs is hard, and mastering the tools for doing it well takes, as with any other engineering or scientific discipline, hard work (why, i don’t heard anyone complaining that building bridges or computing the effects of gravitational lensing is too difficult). There’s no silver bullet.

All that said, please don’t read the above as an apostasy letter announcing the embracement of a new religion. There’s still much to be said in favour of dynamic languages, specially those in the Lisp family, whose malleability (fostered by their macro systems) is also a strength, in that they allow you to replicate some of the virtues i’ve been extolling in this post. Haskell lacks the power of homoiconicity, its template mechanisms feeling all but cranky, and that’s a serious drawback in some contexts (i have yet to decide how serious, as i have yet to decide how much i’m missing in reflection capabilities). As always, it is a matter of trade-offs and, fortunately, nobody will charge you for high treason for using the language better fit to the problem at hand, or so i hope.

About these ads

13 Responses to “Enjoying Haskell”

  1. Enric Says:

    Dear Jao,

    Bright, as usual. But …. Prolog??? Ok, it’s kinda weird doing mental backtracking to know whether to put the cut operator or not, admitted… but difficult??? Could you please develop it further, please?

    Thanks and regards from enriqueeee …. (yes, still alive and -hopefully- kicking!! :)

    • jao Says:

      Hi Enric,

      Well, yes, to me it was difficult to switch gears to a purely declarative style. There’s a gap between imperative and functional programming, but there’s still some common ground (after all, well engineered imperative programming tends to be as functional as possible), but my feeling is that the gap is much wider when you have to program in a purely declarative way. To me, it needed, and still needs, some mental adjustment, and it doesn’t flow easily as yet (although it’s true that the reason might be just lack of practice: i rarely use prolog).

      (Glad to see you’re still alive and kicking, hopefully, not in my direction :))

  2. eggmatters Says:

    I remember programming Haskell in my senior year of comp sci. I had never even heard of functional programming. It seems so easy at first. Then – where are the control flow statements? Then – how do you preserve state? Very mind boggling but wow, you sure can facilitate some elegant solutions if you’re IQ is high enough.

  3. A very good programming blog « The Agnostic Coder Says:

    [...] Lots of insightful and thought provoking posts. I particularly enjoyed the latest post about Enjoying Haskell. It’s an interesting post about static vs dynamic typing, which can be easily extrapolated [...]

  4. chris Says:

    There is of course Template Haskell for meta-programming, but a much better way to solve most of your metaprogramming problems is by using Generic Programming (which isn’t related to generic programming in Java). It allows you to program on structural values. It’s too complex to explain in one comment, but luckily, there’s a lot of literature about it.

  5. Curt Sampson Says:

    Along with Dijkstra, I disagree with the dynamic typing folks on the testing issue. “The first moral of the story is that program testing can be used very
    effectively to show the presence of bugs but never to show their
    absence.”

  6. beroal Says:

    “A common argument from the static typing camp is that the compiler is catching a whole class of bugs for you, to which dynamic types answer that a good test suite (which you need anyway for any serious development) will catch those relatively trivial bugs for you.”

    I think it’s a fallacy. If a type system is robust enough that you verified your program, you don’t need a test suit. It looks like a circular argument: you need to test because your language has dynamic typing, and if you test, you don’t need static typing. Testing and static typing replace each other, are alternative ways to the same goal.

    • Curt Sampson Says:

      “Testing and static typing replace each other, are alternative ways to the same goal.”

      While they are certainly different ways *toward* the same goal, they are not different ways *to* the same goal, except in rare cases. When your code passes the type checker, you have a proof that certain problems can never occur. Testing doesn’t give you that proof; as Dijkstra pointed out, testing only shows that certain specific errors don’t exist, not that other errors can’t happen. In statically typed languages there’s an exception for this when you do exhaustive testing (testing every possible input and output), of course, but dynamic languages don’t even get that, since any possible value in the entire universe is a possible input, and there are few functions for which all of these values are valid inputs. (Exercise: what functions are these? Here’s a hint to help solve the problem: think about the types you’d write for these functions in Haskell.)

    • Colin Fleming Says:

      “If a type system is robust enough that you verified your program, you don’t need a test suit.”

      I absolutely do not agree with this. Static typing removes a (very) large class of problems that you would have to test for in a dynamic program, but it certainly doesn’t remove the need for testing. Quickcheck is amazing.

      Jao, I agree about static typing helping refactoring, as well – and not just of code that age makes it harder to keep track of, but of code bases that you’re not very familiar with.

      • beroal Says:

        ““If a type system is robust enough that you verified your program, you don’t need a test suit.”

        I absolutely do not agree with this. Static typing removes a (very) large class of problems that you would have to test for in a dynamic program, but it certainly doesn’t remove the need for testing.”

        Yes, it’s hard to believe. The Haskell type system is not the whole picture. Look into dependent types and verification. They do remove the need for testing, at least in theory.

  7. Eric Says:

    I have recently been using Haskell and agree that it is hard to develop in BUT very rewarding. I view it as software engineering exercise. Just as we need physical exercise, I believe that good developers continuously stretch themselves to keep their minds in shape. Haskell helps me do this.

  8. Robert Says:

    “As i grow older, i find it more and more difficult to keep in my head all the places and ways a given data structure is used in my programs, and with dynamic languages i’m often falling back to grepping the source code to find them. And again, their plasticity often works against me, in that they let me use those data structures in crooked ways, or forget to take into account new fields or constructors for a modified data type. Haskell’s compiler has proved an invaluable ally to my refactorings and, by comparison, modifying and maintaining my bigger dynamic programs is not as fun as it used to be.”

    Amen to that one!

    I expressed a similar sentiment the other day. When I get deep into the weeds I become a Haskell type checker junkie.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 42 other followers

%d bloggers like this: