[erlang-questions] chained functions

Joe Armstrong <>
Wed Jan 25 13:16:08 CET 2012


I think you are asking the wrong question. If a function returns
{ok,Val} | {error,Reason}
then I think to myself "the caller of this function expects things to
go wrong and is
committed to handling *both* return values.

So they would *never* write w(x(y(z(....))) because this does not cater for both
return values.

With the "let it crash" philosophy one would make w,x,y, .. return a
value OR call exit(...).
With this convention things do nest in the "happy" case without using
a staircase.

At the top level try or catch is used to catch the error.

Alternatively you could say

  ok({ok,X}) -> X;
  ok{error,E}) -> exit(E).

and then

   w(ok(x(ok(y(ok(z(X))))))

Not pretty but it does the job

/Joe


On Tue, Jan 24, 2012 at 8:31 PM, Reynaldo Baquerizo
<> wrote:
>
> A friend of mine asked:
>
> ##
> If you have functions that return {ok, Result} | {error, Reason}
> how do you chained them? So that you have:
>
> w(x(y(z(...))))
>
> without building a staircasing. Something that would be done in Haskell
> with monads.
> ##
>
> I would probably go for:
>
> x({ok, Value}) ->
>  NewValue = <do something with Value>,
>  {ok, NewValue};
> x({error, Reason}) ->
>  {error, Reason}.
>
> in each function
>
> which brings me other question, when do you tag return values?
>
> I tend to only use tagged return values with impure functions, were an
> error is more likely due to side effects.
>
> --
> Reynaldo
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list