Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: How to test multiple values in case condition?

Tags:

elixir

Is there a shorter way to write this:

case testvalue do   200 ->     true   404 ->     true   _ ->     false end 

It returns true for 200 or 404 and false for everything else. It would be nice to write it with an OR condition but this leads to an error:

case testvalue do   200 || 400 ->     true   _ ->     false end 
like image 359
Ole Spaarmann Avatar asked Aug 25 '16 08:08

Ole Spaarmann


2 Answers

There's no direct syntax for or in the middle of patterns but you can use a guard:

case testvalue do   n when n in [200, 400] ->     true   _ ->     false end 

You can also use or in guards. This will work too but is more verbose:

case testvalue do   n when n == 200 or n == 400 ->     true   _ ->     false end 

Both will run equally fast as in inside guards is converted into comparisons + or, as mentioned in the docs.

like image 126
Dogbert Avatar answered Sep 29 '22 01:09

Dogbert


From my experience, it makes more sense in elixir to handle the cases with functions / pattern matching, it's more readable when your code base grows.

I would do something like that:

defp valid_http_response?(200), do: true defp valid_http_response?(400), do: true defp valid_http_response?(_), do: false 

I agree it doesn't really make sense now, but in the future you will be happier :)

like image 22
Jeremie Ges Avatar answered Sep 28 '22 23:09

Jeremie Ges