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
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With