[erlang-questions] chained functions

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Wed Jan 25 12:04:12 CET 2012

On 1/25/12 10:06 AM, Robert Virding wrote:
> I personally am ok with "staircasing" so I don't see the problem. :-) This probably comes from working with it for a long time. Also I find that very often the handling of returns values is more complex than just chaining things through. I also feel there is a benefit in being very explicit with values being returned so you see what is happening.
But in Erlang, it isn't often the case of "staircasing" at all as well!

In Haskell, you often program defensively, so your code will look like

case f x of
   Nothing -> <error>
   Just x    -> case g x of
                 Nothing -> <error>
                 Just x -> ...

And this is a problem because it is irritating to write. So you monad it:

do x <- f x
    x <- g x

And then you run it and get either a valid result or that some error 
happened along the way. Where the error happened is now lost on you for 
the Maybe-Monad but a proper Error Monad can tell you what is wrong as well.

But this is Erlang, and Erlang runs everything inside such an Error 
monad by default:

{ok, X1} = f(X),
{ok, X2} = g(X1),

So there is no staircasing going on and an error results in a crash by 
default. Now you may think that the crash is a bad idea, but often it is 
the only sensible thing to do first. Don't handle a lot of nasty corner 
cases before you know that they occur in production code and occur with 
a frequency that hurts you. You can always do some explicit handling of 
the error case if necessary later.

Jesper Louis Andersen
   Erlang Solutions Ltd., Copenhagen, DK

More information about the erlang-questions mailing list