Does the cond control structure allow multiple cases to be matched?

时间:2018-02-03 08:39:13

标签: elixir

Is there something like a fallthrough feature for Elixir cond statements that would allow me to match for multiple cases? I want to do this to avoid repeating the same line of code. I also want to avoid a long chained logical OR || (disjunctive) statement in an if block. Right now, I'm repeating code like so:

cond do
  top == nil -> eval(rest, [operator | output_queue], opstack)
  top == "(" -> eval(rest, [operator | output_queue], opstack)
  compare_to(operator, top) < 0 -> # keep popping
  _-> # some catchall
end 

1 个答案:

答案 0 :(得分:1)

I also want to avoid a long chained logical OR || (disjunctive) statement in an if block.

You don't need to switch to if to make use of || -- cond, unlike case, accepts any expression and you can join top == nil and top == "(" with || to get what you want:

cond do
  top == nil || top == "(" -> eval(rest, [operator | output_queue], opstack)
  compare_to(operator, top) < 0 -> # keep popping
  _-> # some catchall
end