[erlang-questions] style question - best way to test multiple non-guard conditions sequentially
Wed Jun 19 23:50:20 CEST 2013
I am solving this problem in following way:
maybe_cond1(false, …) ->
maybe_cond1(true, …) ->
% do cond1.
maybe_cond2(false, …) ->
maybe_cond2(true, …) ->
% do cond2.
maybe_cond3(false, …) ->
% do failure
maybe_cond3(true, …) ->
% do cond3.
this approach allows you to have as many conditions as you like.
The code can be simplified by using lists:fold and closers e.g.
lists:foldl(fun assert/2, false, [fun cond1/0, fun cond2/0, fun cond3/0]).
assert(_, true) ->
assert(Fun, false) ->
case is_cond1() of
% do condition 1
but I do prefer the first approach.
On Jun 19, 2013, at 9:23 PM, Jonathan Leivent <jleivent@REDACTED> 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. 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 -> ...
> 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
> erlang-questions mailing list
More information about the erlang-questions