HNHacker News
TopNewBestAskShowJobs

tmhedberg

1,130 karma · joined March 15, 2011

submissionscomments
tmhedberg··on Linus on kernel changes breaking user programs (from 2012/12/23)
ENOENT isn't a new error code. It's the standard errno value that indicates an attempt to access a nonexistent file or directory on all POSIX platforms.

The problem is that it was being misappropriated in a nonsensical way, returned by an ioctl call. ioctl can only be called on already-open file descriptors, so it makes no sense for it to complain that the file doesn't exist. If the file pointed to by the file descriptor didn't exist, the file descriptor wouldn't have been able to be opened in the first place (errno would have been set to ENOENT by the call to open).

tmhedberg··on Why learning Haskell makes you a better programmer
Who is arguing that the monad as a means of composition is superior to all others? Or that Haskell doesn't emphasize the power of composition of high-order functions? Function composition is one of the most important tools in a Haskell programmer's toolbox. Monads are just another one of those.

The thing is, most popular languages these days support higher-order functions. It's nothing to write home about. Monads get a lot of attention specifically because they are a fairly unique idea that is not supported out-of-the-box in other languages. People who are advocating (or evangelizing, if that's your perspective) for a particular thing are going to focus primarily on the specific aspects of that thing that make it stand out from the crowd. For Haskell, that means things like monads, algebraic data types, non-strict evaluation, functional purity, etc.

There is one question, before you press "down-vote" few times - what is the sequence of machine instructions your monad compiles into?

I can't understand what you're getting at here. What difference does it make what code the compiler emits, unless I am trying to aggressively optimize low-level performance? If it does what I intend it to do, and is reasonably fast at doing it, I don't care about the specific instructions. How is that relevant?

tmhedberg··on Why learning Haskell makes you a better programmer
For what it's worth, I would suggest just writing code as a means of building your intuition. Don't worry about understanding every last detail; just hack away at it and intuition will come as a natural consequence of your persistence. At least that has been my experience. (Honestly, this is probably true of most things that are challenging to learn, not just unusual programming languages.)

I felt much the same way as you when I first decided to dig into Haskell and went through a period of some frustration in which I felt that, although I was more or less understanding the literal text of the books and documentation I was reading, I was lacking a feel for the "big picture" of how it all fit together. I could explain specific details of how the language worked but I couldn't really visualize how to put together a complete, useful program in it.

For whatever reason, something about Haskell really intrigued me despite my frustration, and I kept at it. There was never any major epiphany where everything just clicked, though there were a few minor moments of enlightenment, as when I discovered that the neat pattern I had started using in some of my code actually had a name and a well known type class: "Applicative". I also recall reading a particular article about monads (and manually working through its examples) that made me suddenly realize how utterly simple they were, despite the ridiculous hype.

After writing enough Haskell code, it eventually dawned on me that I "got it". I wasn't struggling anymore. Haskell had, without my noticing it, become my default, natural way of thinking and reasoning about code, and it just made sense in a deeply fundamental way. I could no longer even see why I'd been confused in the first place.

Professionally, I've used mostly Java and Ruby, and have never written a single line of Haskell for pay. But like the author of this article, I've found that it shapes the way I write code in other languages, even those far removed from pure FP, in significant ways. My mental design process when writing new code at work usually takes place in terms of Haskell's data types and abstractions, and then gets translated into whatever language I'm actually using once I feel like I have a good handle on the direction that I'm heading. This usually results in nice, clean designs, consisting mostly of pure, composable functions and immutable data with as little shared state as I can get away with, arranged, when necessary, around an imperative, IO-driven core. Basically the same way I'd structure actual Haskell code.

If you're intrigued enough to keep at it, then patience is all you need, and you'll get there. It's pretty fun when you do.

tmhedberg··on Monads in Python (with nice syntax)
Alternatively, we replaced some easy to follow procedural code with a manual, verbose, and error-prone abstraction. I have no idea what is going on with the author's decorated classes, generators, etc.

It's complicated and fairly ugly to do this in any language which has no first-class support for the monad abstraction. I wouldn't use this code in a "real world" setting, and I doubt even the author would argue that you should. Many of Haskell's unique language features make monads "go down smoothly" in a way that most other languages will only be able to roughly imitate without extensions like user-definable operators, type classes, `do` notation, return type and higher-ranked polymorphism, etc.

How do you create a new monad pattern and debug it? All code is imperfect; it feels like we're just shifting some of the logic around to a different place.

Nearly all forms of abstraction in any programming language can be characterized as "shifting some of the logic around to a different place". The entire point of abstraction is to hide away complexity behind abstract interfaces so that we can build more and more complex systems without having to mentally wrangle with the entire stack of complexity all at once. For instance, most people writing code in a high-level language don't spend much time mentally compiling the code they're writing down to machine instructions; we trust that the language interpreter or compiler will take care of that complexity well enough for us so that we can focus on the bigger picture. Monads just ratchet up this level of abstraction one notch higher than most languages take it.

Monads are the very same sort of thing that lets us jump to other locations via function calls, or encapsulate shared mutable state in a class (in OOP languages). The only thing that makes them different is that the "call stack" and "class" abstractions are given first-class support in the majority of popular languages, while monads are not.

Furthermore, in a strongly typed language with support for monads, the implicit flow control in a series of monadic statements is made obvious by its type. When encountering a `do` block of type `Maybe x`, there is no ambiguity surrounding the fact that each statement in the block may fail, and if it does, will short-circuit the remainder of the computation. This is not so much "hidden" control flow as it is "syntactically unencumbered". It would take a significant lapse of attention to forget about the monadic context of the computation and its implications (and if you did forget, the compiler would tell you about it). No one complains that when you encounter a statement like `foo.bar()` in an OO language, you can't know exactly which definition of `bar` is being called without walking up the inheritance chain to find it. There is implicit "magic" taking place here as well, in the form of dynamic method dispatch, but because most programmers encounter this particular sort of implicit behavior every day, it doesn't seem so strange or dangerous.

This is apples and oranges. Functions and loops are straight-forward, monadic bind (in this framework) involves indirecting through a bunch of complicated Python magic.

Functions and loops seem more straightforward to you because you are used to using them in the languages you use regularly and are most comfortable with. To a reasonably experienced Haskell user, there is nothing about monads that is not equally straightforward or obvious. More than anything else, it's a question of familiarity.

I won't argue that the Python implementation isn't complicated or somewhat "magical". I just don't think that's a result of monads' inherent complexity; rather, it is the result of the fact that Python isn't designed for working with this particular kind of abstraction. Any implementation of it in a language like Python is bound to be a bit kludgey and difficult to follow.

tmhedberg··on Concurrent Sieve of Eratosthenes in Go
Looks good, thanks. :)
tmhedberg··on Concurrent Sieve of Eratosthenes in Go
Just for fun, I translated it to Haskell: https://gist.github.com/4105055
tmhedberg··on This machine separates your Skittles into color groups so you don't have to
Couldn't they just mix all the colors together in roughly equal proportions (by weight, for instance) before packaging them into packets, and just rely on the statistical improbability of a noticeable imbalance in colors? I doubt there is actually a machine that counts out the Skittles by color and makes sure each bag gets the right number of each.
tmhedberg··on Hey, C Is a Functional Language Too
Why would you do this instead of declaring it as `int main(void)`?
tmhedberg··on FTC files suit against "Rachel from Cardholder Services"
Since Citi would never allow marketing company run their tracking service on citi.com and since users won't be eager to click on n23uiahsf8das9fda.somethingelse.com link, they don't have much choice.

They do have a choice. They could choose not to "track" their customers in this way.

tmhedberg··on Haskell in Production: The good, the bad, and the ugly
Maybe is a monad, which means Maybe computations can be chained together with `>>=` (or using `do` notation) without checking for `Nothing`. You can easily produce a large composition of potentially-failing computations while completely ignoring the possibility of failure.

The case analysis you give as an example is only required at the point when you want to extract the final result into a different monadic context, and even then you would typically use the `maybe` or `fromMaybe` functions to make it more concise.

Only a novice Haskell user would write:

    case comp1 of
        Nothing -> handleFailure
        Just r1 ->
            case comp2 r1 of
                Nothing -> handleFailure
                Just r2 ->
                    case comp3 r2 of
                        Nothing -> handleFailure
                        Just r2 -> handleResult r3
which is indeed, just as bad as explicit null checking in C or Java, with runaway indentation to boot. But anyone who understands Haskell's rich abstractions would instead write:

    maybe handleFailure handleResult $ comp1 >>= comp2 >>= comp3
The fact that you can't forget the "null check" without the compiler telling you about it is a nice convenience afforded by the strong type system, but it's far from the only benefit.
tmhedberg··on Functional programming with Python
I don't know much category theory either; my argument is based solely on my knowledge of Haskell.

Maybe I'm being obtuse, but I don't quite understand what you mean when you say "mconcat with a map". But to see why mconcat isn't as general as a fold, you need only to take a look at the types:

    mconcat :: Monoid a => [a] -> a
    foldl :: (a -> b -> a) -> a -> [b] -> a
mconcat is constrained to only operating on monoidal types, whereas foldl has no such constraint. Likewise, mconcat must always yield a result of the same type as the list elements, while foldl is capable of accumulating a result of any type.

mconcat can be implemented in terms of a fold, e.g.

    mconcat = foldl mappend mempty
Such a partially applied foldl is obviously less general than an unapplied foldl, as its first 2 arguments are fixed. There is no way to implement foldl (or even foldl1) in terms of mconcat.

There are plenty of uses for folds that don't involve monoids, and therefore can't be implemented with mconcat plus a Monoid instance. As a trivial example, take

    Prelude> foldl (/) 400 [4, 4, 5]
    5.0
There is no "quotient monoid", because a monoid is defined as a type with an associative binary operation and an identity element with respect to that operation. Division has a right identity (1), but it isn't associative, so it can't be used as a monoidal operation like addition and multiplication can. But foldl still works fine in this case, as the above example shows, where mconcat would not (unless you write a Monoid instance that violates the monoid laws).

Associativity notwithstanding, it's also not adequate to say that 2 monoid instances should be enough for any type. Maybe that is true in some or even most cases, but it is certainly not true in the general case. Haskell has newtypes to mitigate this problem, essentially enabling an arbitrary number of Monoid instances to be defined per type, but Python only lets you write one __add__ and one __mul__ for a given class. On top of that, I don't believe Python even has a product function that folds __mul__ over a list the way sum folds __add__, so really the limit is 1, not 2.

Anyway it's all moot because, as someone pointed out, reduce hasn't been removed from Python, just relegated to a library. :) I think it's a fundamental enough operation that it should be built in, but obviously Guido and I have differing opinions on FP.

tmhedberg··on Functional programming with Python
If __add__ is taken to be any associative operation of a monoid, then Python's sum is merely equivalent to Haskell's mconcat, which is not nearly as general as reduce/foldl. Plus, unless you implement something akin to newtype wrappers for alternative monoid instances (hardly Pythonic), you're going to be restricted to a single foldable function for any given type.

I think you were right the first time; removing reduce from Python is very lame.

tmhedberg··on Linus on keeping a clean git history (2009)
Why do I get prompted to enter a commit message when I'm just doing a git pull?

Because `git pull` == `git fetch` + `git merge`. If there are upstream commits you are fetching that are not ancestors of your head commit, then pulling involves merging the divergent history, thus creating a new merge commit. And a merge commit, like any commit, needs a message.

Why do I have to explicitly add every file I want to commit each time?

Because Git has an intermediate staging area (the "index") between your working directory and the committed history. This is a great feature; one of the most useful aspects of Git, in fact. The side effect is that you must add your changes to the index before committing, but this is a small price to pay for the huge increase in flexibility the index affords.

Why can't it just default to "everything under the current dir" like svn does?

You can do `git add .` to add everything in the current directory without naming it all explicitly. Or you can use the `git commit -a` shortcut (and similar -A and -u options) to add and commit in a single command. This is hardly a significant increase in effort over `svn commit`.

tmhedberg··on To understand the command line...
Pretty much any question about why things are done a particular way in Unix can be answered the same way: "for historical reasons".

I'm a full-time Linux user, so that's not intended as a dig against Unix, but merely an observation. Each of the traditional Unix utilities evolved from some earlier tool, and carries with it to this day both the quirks of its predecessors and many artifacts of the design constraints of the time. Some argue that this diminishes usability, and they may have a point. But I find that it gives Unix a certain charming character that I've grown quite fond of. I suspect this sentiment is fairly pervasive, and probably contributes substantially to Unix's resistance to change over time. Maybe it isn't the simplest thing to learn from scratch, but it's robust and highly dependable once you've learned it.

tmhedberg··on The Homely Mutt
As when Knuth stopped releasing new versions of TeX because it reached a point where it was "done", software that has been around for long enough can eventually mature to the point where there's nothing left to add without expanding the scope of the project beyond its original definition.

Mutt may simply be at that point. I use Mutt as my primary MUA in a very similar manner to the author of the article, and I can't really say that there are any features that I want that it lacks. Of course, I can't speak for everyone on that point; for instance, some people actually want to send and receive HTML email, and Mutt can't easily deal with that. But for some of us, lack of HTML support is itself a feature, and when you really have to, piping a text/html MIME part to a browser for rendering is really easy to accomplish.

I know essentially nothing about Sparrow, but I suspect that it is a much newer product than Mutt, has had far less time to mature, and as such simply requires a more frequent release schedule than a project with Mutt's long history.

Basically, a comparison between most recent release dates doesn't necessarily mean what you think it means.

tmhedberg··on John Carmack on Static Code Analysis
GHC will warn about partial functions/inexhaustive patterns if you compile with -Wall (or even just -fwarn-incomplete-patterns, but -Wall is recommended). I've often wondered if it would be feasible to eliminate the partial functions from the Prelude and turn partiality into an outright error (not that this would ever happen, as it would break a lot of code).

Regarding other code smells that the compiler can't catch: one thing I have come to really appreciate about the design of Haskell is that in the vast majority of cases, the path of least resistance is also the path of greatest clarity, correctness, etc. I mean, sure, you can write your entire program in IO, but it would be supremely irritating to do so. It's just simpler and easier to do it the "right" way, via composition of small, independent, pure functions.

When using other languages (for me, this usually means Java, Python, or JavaScript), I feel like I am constantly having to remind myself not to be lazy and to do things the way that I know to be right. Don't catch an overly broad class of exceptions. Don't rely on shared mutable state when an extra function argument will suffice. Avoid using null pointers to represent failure. Be sure not to use type-coercive comparison operators. And so on. These languages give you so many ropes with which to hang yourself, and even the standard libraries make idiomatic usage of them. Programming defensively feels like working completely against the grain.

Haskell, with its strong immutability and airtight type system, has shown me that it is possible for a language to guide programmers safely through the minefield without placing a severe additional burden of vigilance on their shoulders. It would be interesting to see a more conventional, imperative style language that followed similar principles. Or perhaps the "everything is in the IO monad all the time" nature of imperative code is just fundamentally at odds with code correctness, and we'll always have to fight against it.

tmhedberg··on An Apology of Sorts: Functional Languages Are (Still) Overrated
I'm not sure what you mean by "FP isn't meant to tie two huge, horrible systems together". Is any language or programming paradigm really designed with that usage in mind?

But assuming that that is in fact the case, I wonder whether it would still be the case if we lived in a bizarro world in which FP had dominated and OOP was seen in the mainstream as an impractical oddity. I suspect that, to the extent that functional languages do not make for good "glue code", that is primarily due to the impedance mismatch between FP and the largely object-oriented systems that need tying together, rather than because of some inherent limitation of functional programming itself. If those large systems were constructed in a functional style, would functional glue be more effective?

tmhedberg··on GHC 7.6 is now live: poly kinds, dynamic use of cores, numeric type literals...
Did I suggest that it was a function? If so, I didn't intend to.
tmhedberg··on GHC 7.6 is now live: poly kinds, dynamic use of cores, numeric type literals...
I suppose that, in my personal experience, I just haven't written a lot of Haskell code that used multiple similar record types in the same namespace.

I don't have any evidence for this, but I feel like it's often a bit of a code smell when this problem crops up. It seems like it frequently happens when programmers used to OOP are trying to shoehorn an object oriented design into a language which is just fundamentally not object oriented. I'm not saying that that's the only situation in which this problem arises, nor that the complaint isn't a legitimate one, regardless. There is no question that the situation could be improved. And perhaps I've just gotten lucky so far and haven't come across a scenario in which this really causes difficulties.

That said, there are always ways to work around the issue. I will make no claims of elegance here, but it's really not that much trouble. For one, you can define the different record types in separate modules, and then import them qualified. That's easy enough to do; it's just annoying to have to use multiple files.

Alternatively, you can keep the ugly prefixes on the record field names, but then use a type class to elide them away everywhere you refer to them. This technique only works when the similarly-named fields have the same type in each record, unless you use fundeps or associated types to attach additional type information to your class. For example:

    {-# LANGUAGE TypeFamilies #-}

    data Foo = Foo {foo_field1 :: Char, foo_field2 :: String}
    data Bar = Bar {bar_field1 :: Int, bar_field2 :: String}
    
    class MyRecord a where type Field1Type a
                           field1 :: a -> Field1Type a
                           field2 :: a -> String

    instance MyRecord Foo where type Field1Type Foo = Char
                                field1 = foo_field1
                                field2 = foo_field2

    instance MyRecord Bar where type Field1Type Bar = Int
                                field1 = bar_field1
                                field2 = bar_field2
You could even use Template Haskell to automatically generate the instances so you don't have to tediously type them out yourself, especially handy for records with a large number of fields.

So I'm not claiming that there's no problem to be solved. I would be happy to see a real solution to this that doesn't require any workarounds. I just don't think it's a big enough issue to keep me from using a language which is, in nearly all other respects, awesome. :)

tmhedberg··on GHC 7.6 is now live: poly kinds, dynamic use of cores, numeric type literals...
Also one thing that always gave me pause about Haskell was the record system, and the inability to have fields with the same name in the same module (especially when the fields are generated from a database). Has there been any progress on that front?

There have been a zillion proposals, but as far as I know, not much actual consensus or implementation work.

Anecdotally, I've never run into a situation where this was anything more than a minor annoyance. I don't doubt that it can be a problem under the right set of circumstances, but I think the issue gets more attention than its magnitude truly merits. People theorize a lot about the difficulties it can hypothetically cause, but in practice, it seldom actually manifests itself.

tmhedberg··on GHC 7.6 is now live: poly kinds, dynamic use of cores, numeric type literals...
Every new GHC release is like a little Christmas morning! The pace of new feature development impresses me.

I'm particularly interested in the new type-level literals (which seem like they will make it much less cumbersome to express certain static constraints) and the convenient new syntax for multi-way if expressions (I've long wanted Lisp's `cond` in Haskell) and case analysis on lambda arguments.

tmhedberg··on Linus Torvalds responds to what killed the Linux desktop
I don't really understand the fuss about the Python thing. `#!/usr/bin/python2` should work on pretty much any system, not just an Arch Linux system. Whatever happened to "explicit is better than implicit"?

If the Python community eventually wants Python 3 to become the default, they will all have to deal with this issue sooner or later; Arch is just opting for "sooner", as that's in line with the way Arch approaches all changes. The real problem is that there are two incompatible versions of Python, and most Python developers give too little thought to forward compatibility to include an extra '2' in their shebang lines in order to disambiguate their intentions. Just because python == python2 on most systems today does not mean the status quo will forever be the same, nor that it ought to be.

In any case, there is no problem making Python scripts work on Arch, even if they use the ambiguous shebang. All of the official packages work out of the box with no problem, of course, and anything unofficial (i.e. AUR packages) just needs a single, trivial sed command added to the PKGBUILD. Arch is not "maintaining a separate fork of each Python package". This is the opposite of true; in fact Arch packages are, on the whole, far closer to their upstream counterparts than the same packages from other distros, where it is common for huge divergences to be made from the upstream defaults. Hardly worth ranting about.

You come across as if the Arch developers viciously attacked your family or something. Maybe it's just a distro with different values than yours, man! Relax, there are lots of other choices! It's not supposed to appeal to everyone, but for those of us who align well with the Arch "philosophy", it's fantastic.

tmhedberg··on Neil Armstrong, Neal Stephenson, Neil Gaiman
Among other things, he managed to land Eagle with only seconds of fuel remaining, having manually maneuvered it to an alternative landing site after the computer had navigated to a primarly landing area covered with boulders. All this while several unexpected computer alarms were going off.

Maybe others could have done that as well, but Armstrong actually did it, staying calm under unimaginable pressure and averting disaster.

tmhedberg··on Is Haskell liberal or conservative?
I'm curious what sorts of things you have in mind when you refer to "pieces [of Haskell code] that require superhuman effort to type correctly"? In my own Haskell experience, except when playing with silly and mostly pointless tricks like doing computations in the type system, I've never really felt like Haskell's type checking has been a hindrance. It's more like those inflatable bumpers on bowling lanes: it only stops me from doing the things that I wouldn't want to do anyway, like forgetting to check for failure conditions or allowing mutable state/side effects to seep into parts of my code that I intended to be pure.

> However, it's often really painful to get that code to typecheck compared with the effort to get the same code correct in python or ruby.

I'd argue that in the overwhelming majority of cases, the Python or Ruby code is equally incorrect to the equivalent Haskell code that doesn't type check, it's just that Python and Ruby don't tell you about it upfront, you find out about it at runtime. Hopefully, "runtime" means "during testing" and not after your code is in production. Or if you want to put a more positive spin on it, Python and Ruby let you run the code in spite of its lack of correctness. If that's the kind of freedom you want, then a dynamically typed language (or even a weak statically typed language) will suit you well. As for me, I've been burned by that "freedom" enough times now that I can't think of it as anything but a negative.

tmhedberg··on Parser combinator library in C
The (* >) operator [1] (the space in the middle is just to circumvent HN's rather dumb comment formatting) sequences its two arguments, ignoring the one on the left. So

    string "0x" *> takeWhile1 hexadecimal
parses a literal string "0x", then one or more hexadecimal digits, and the result is just the hexadecimal digits.

[1] http://hackage.haskell.org/packages/archive/base/latest/doc/...

tmhedberg··on Thinking Functionally with Haskell
Have you tried Learn You a Haskell for Great Good (http://learnyouahaskell.com/)? It's not as comprehensive or full of practical examples as something like RWH, but as an introductory text, I think it does a better job than any other Haskell book I've come across at keeping challenging concepts understandable.
tmhedberg··on Thinking Functionally with Haskell
In fact, with compiler optimizations such as GHC's stream fusion, the intermediate result may never actually exist at all.
tmhedberg··on Introduction to monads in JavaScript
I concede on the pseudocode formatting point. Upon rereading, that is uglier than necessary.

The trouble with exceptions is that, unless you're referring to Java-style checked exceptions, there's nothing that forces you to handle them. You can still forget that the exception can occur, and then your code will blow up at runtime. And in one sense, exceptions are even worse than the repetitive if-then clauses: if statements at least handle the failure right there at the call site, whereas exceptions let you move your error handling code to some other place in the call stack, non-local to where the actual error might occur. There are advantages as well, for sure, but I see this as potentially very confusing.

Haskell has exceptions but most people prefer to avoid them, favoring the use of MonadError instances (such as Maybe) instead, since they make the potential failure highly explicit and impossible to forget about or ignore. And while I don't think using Maybe is at all the same as ignoring errors, I suppose I see how it could be construed that way. That's why there's Either as well, which allows you to associate some piece of data with the failure. So you could use the Either String monad to pass back an error message on failure, or Either [String] to pass a list of them, or Either (IO ()) to specify an action to be taken in response to the failure, or whatever you want. I guess that ends up being a lot like exceptions, except for the fact that you can't ignore or forget them, so your code is still verifiably safe at runtime, and there is nice syntactic sugar from the Monad class (do notation, >>= chaining, etc.) to make them concise and elegant to use without cluttering your code.

tmhedberg··on Introduction to monads in JavaScript
True, depending on your language, you can probably get the imperative version to be shorter than my pseudo-C implementation.

But that accumulating function you're passing to reduce? That's essentially just a JavaScript version of the bind (>>=) operator for Maybe. In fact, in Haskell, I'd express what you wrote as:

    foldl (>>=) x [foo, bar, baz, quux]
foldl is Haskell's version of reduce, so that's almost exactly the same as your code. You're using a monad to shorten your code, you're just not being obvious about it!
tmhedberg··on Introduction to monads in JavaScript
Let's say I have several functions I want to compose, feeding the result of one as the argument to the next. But each of these functions has some failure condition, which, if it occurs, causes the function to be unable to return a normal result. In an imperative language, I might represent that failure by returning a null reference, and I'd write something like this:

    fooResult = foo(x);
    if (fooResult == null) {
        return null;
    } else {
        barResult = bar(fooResult);
        if (barResult == null) {
            return null;
        } else {
            bazResult = baz(barResult);
            if (bazResult == null) {
                return null;
            } else {
                quuxResult = quux(bazResult);
                if (quuxResult == null) {
                    return null;
                } else {
                    return quuxResult;
                }
            }
        }
    }
I think that's a pretty common pattern: call a function and check whether it succeeded. If it did succeed, then pass its result to the next function and repeat. If it failed, then propagate the failure outwards, skipping the rest of the computation.

But that's pretty tedious and repetitive code to write. The signal to noise ratio is incredibly low. Not only that, but if I get lazy or forgetful and don't check for null in any one of those cases, my code could blow up at runtime. It would be nice if we could abstract out the pattern of error checking and propagation of errors so we didn't have to type so much boilerplate around the real meat of the computation, which is just the four function calls. Haskell's Maybe type serves precisely this purpose. The exact same code as above, in Haskell using the Maybe monad, would be:

    return x >>= foo >>= bar >>= baz >>= quux
That's it! Error propagation will happen automatically, and if no errors occur along the way, we'll get the same result at the end.

Now, you might think that there must be a lot going on behind the scenes to make that one-liner actually do what we want it to do. But there isn't really. Maybe comes for free in the standard libraries, and even if it didn't, we could trivially define it ourselves like this:

    data Maybe a = Nothing | Just a
    instance Monad Maybe where return = Just
                               Nothing >>= _ = Nothing
                               Just x >>= f = f x
That's the entire definition of the Maybe data type and its complete error propagation behavior. There's nothing more to it than that. And not only will it work in the specific example I gave, but in any situation where I have a chain of functions to call that might fail in some way. After writing that once (or not at all, since it's in the libraries), I can now apply that pattern anywhere I need it, in any program, to concisely express what took around 20 lines of onerous and error-prone repetition without the benefit of the monad.

That's how monads eliminate boilerplate, and one of the reasons why you might benefit from understanding them even if you're not a Haskell user.

← PreviousPage 3 of 6Next →