[erlang-questions] style question - best way to test multiple non-guard conditions sequentially

Richard A. O'Keefe <>
Thu Jun 20 04:15:23 CEST 2013


On 20/06/2013, at 6:23 AM, Jonathan Leivent wrote:

> Suppose one has multiple conditions that are not guards that need to be tested sequentially (meaning, only test condition N+1 after condition N tests false) in a function.

Ah hah!  You want the long-ago-proposed 'cond' form.

pick([{Test,Act}|Rest]) ->
    case Test()
      of true  -> Act()
       ; false -> f(Rest)
    end.
> fun(...) ->
>  C1 = cond1(...),
>  C2 = C1 orelse cond2(...),
>  C3 = C2 orelse cond3(...),
>  if C1 -> ...;
>     C2 -> ...;
>     C3 -> ...;
>     true -> ...
>  end.

fun(...) ->
    pick([
        {fun () -> cond1... end,
         fun () -> action1... end},
        {fun () -> cond2... end,
         fun () -> action2... end},
        {fun () -> cond3... end,
         fun () -> action3... end},
        {fun () -> true end,
         fun () -> action4... end}).

Choose your own name for this.

However, I cannot help feeling that in each specific instance
of this there would be something better to write instead.  So
how about showing us a real example?
> 
> I guess this also implies the question: why does Erlang require the conditions in an if statement to be guards?

Because back when Erlang was invented, there were no conditions that
were not guard tests *only*.  For example, X > Y was not an expression.
There were no andalso or orelse.

Ah, the good old days, before Erlang tried to turn into something else
but got stuck half way.

I really must finish writing up the '-guard' declaration EEP.




More information about the erlang-questions mailing list