[erlang-questions] Orelse and andalso as short-hand for case

Raimo Niskanen raimo+erlang-questions@REDACTED
Tue Jul 24 17:01:27 CEST 2018


On Sun, Jul 22, 2018 at 02:32:29PM +0200, Loïc Hoguin wrote:
> Neither.
> 
> The problem with this and the list comprehension equivalent
> 
>      [io:format("Message: ~s~n", [Msg]) || Msg /= undefined]
> 
> is that it will confuse people who never encountered it before.
> 
> But if one or both of these forms were teached to beginners and everyone 
> was using them, then there'd be no problem in using them anymore.
> 
> I'd love if they became more popular.

I do not mind writing nor reading

     Msg /= undefined andalso
         io:format("Message: ~s~n", [Msg]),

but find 

    [io:format("Message: ~s~n", [Msg]) ||
         Msg /= undefined]

a bit harder to read because the condition comes after the action.

I prefer in any case to use two lines with indentation to hint about
the flow control usage.

(Doesn't Dialyzer complain about the 'andalso' variant because it may
 return a 'false' that is ignored?)

Erlang does not have many "ugly tricks" like these, so if it can save
me from 4 uninteresting code lines i certainly do not mind:

    case Msg of
	undefined ->
	    ok;
	_ ->
	    io:format("Message: ~s~n", [Msg])
    end


> 
> Cheers,
> 
> On 07/22/2018 02:25 PM, Viktor Söderqvist wrote:
> > Hey everyone,
> > 
> > I've seen these short-circuit operators with a non-boolean second
> > operand, usually where the second operand is doing some side-effect and
> > the return value is not important. It seems to be a trend. Example:
> > 
> >      Msg /= undefined andalso io:format("Message: ~s~n", [Msg]),
> > 
> > I this good or bad style?
> > 
> 
> -- 
> Loïc Hoguin
> https://ninenines.eu

-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list