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

Jonathan Leivent jleivent@REDACTED
Wed Jun 19 20:23:49 CEST 2013


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.  Using a case or if in a simplistic way 
would then produce considerable nesting, especially as the number of 
conditions increases above 2 or 3.

Is there some way in Erlang to write such code without either breaking 
up the function clause or using high degrees of nesting?

The closest I can come is something like:

fun(...) ->
   C1 = cond1(...),
   C2 = C1 orelse cond2(...),
   C3 = C2 orelse cond3(...),
   if C1 -> ...;
      C2 -> ...;
      C3 -> ...;
      true -> ...
   end.

Which works, but looks rather cryptic.  It also seems like it is doing 
all of the branching at least twice.

I guess this also implies the question: why does Erlang require the 
conditions in an if statement to be guards?

-- Jonathan



More information about the erlang-questions mailing list