Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"or" condition in Elixir in pattern matching

Tags:

elixir

How can I do, if I can, pattern matching with "or" condition? I need this because I have some different conditions for which action is the same?

case something123 do
  :a -> func1()
  :b -> func1()
  :c -> func1()
  :d -> func2()
end
like image 341
Kooooro Avatar asked Dec 15 '16 04:12

Kooooro


2 Answers

You can use in and lists:

case something123 do
  x when x in [:a, :b, :c] -> func1()
  :d -> func2()
end

x in [:a, :b, :c] expands to x == :a or x == :b or x == :c when the in macro detects it's being called from a guard statement and the RHS is a literal list (because you can't call remote functions from guards).

like image 102
Dogbert Avatar answered Nov 15 '22 10:11

Dogbert


You can also use cond to do it.

cond do
  something123 == :a or something123 == :b something123 == :c ->
    func1()
  something123 == :d ->
    func2()
end
like image 33
vfsoraki Avatar answered Nov 15 '22 09:11

vfsoraki