[erlang-questions] How to make a short circuit in erlang ?

Richard A. O'Keefe ok@REDACTED
Tue Mar 26 03:50:30 CET 2013

On 26/03/2013, at 3:31 PM, 饕餮 wrote:

> When in other language.We can use like:
> example(Something){
>     if( Something == false)
>         return;
>     //do something here;
> }

Brian Marick of www.exampler.com has two great stickers.
One I have fixed to my door is "To be less wrong than yesterday."
The other is "An example would be useful about now" (from memory).

Even in C and Java, "if (Something == false)" is bad style.
You should write "if (!Something)".  The only time that
==false or ==true make sense is when there is a third possibility.

> But in Erlang.I have to write like:
> example(Something) ->
>     if
>         Something == false ->
>             false;
>         true ->
>             %do something here
>     end.

I personally prefer

    example(Something) ->
        case Something
          of false -> false
           ; true  -> . . .

and then go looking for the third case that probably exists.
There is pattern matching in the head.
There are guards to be used.
In fact, "early-exit" (as it's known in the Smalltalk world)
is often an ersatz for guard tests.

So the chances are that you should either
 - be rewriting for clarity, or
 - using guards.

I think a *real* example would be illuminating.
> That's could make the multiple nested like:
> example(Something) ->
>     if
>         Something == false ->
>             false;
>         true ->
>             if
>                 Otherthing == false ->
>                     false
>                 true ->
>                     %do something here
>     end.
> Some code could make 5 or more nested in it.

No.  SHOW US A REAL EXAMPLE.  And nothing stops you writing

example(Foo, Bar, Ugh) ->
    case {Foo, Bar, Ugh}
      of {false, _, _} -> . . .
       ; {true, false, _} -> . . .
       ; {true, true, false} -> . . .
       ; {true, true, true} -> . . .

We need a real example.  (Did I already say that?)

> Is there any idea to make short circuit to reduce of the nested?

Give us a real example and *then* we can have an illuminating

It's a funny thing.  I use early exit a lot in Smalltalk, rather
less so in C, and in ML and Haskell it never occurs to me that I
don't actually have it.  Erlang is definitely close to the ML end
of things.

I just spent a day turning 63 SLOC of code I wanted to use for a
class example of the importance of comments into 21 lines, which
annoyingly needs a lot fewer comments.  Part of it was to not be
scared of introducing auxiliary functions (in Java, yet!).

More information about the erlang-questions mailing list