Created
May 29, 2020 16:12
-
-
Save aesmail/5eee252afb93528063e4eceef8c78f00 to your computer and use it in GitHub Desktop.
Elixir deciding which control flow to use
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# boolean values, use if | |
if expression, do: this(), else: that() | |
# non-boolean multi-value single expressions, use case | |
case expression do | |
value1 -> one() | |
value2 -> two() | |
value3 -> three() | |
_ -> anything_else() | |
end | |
# mutiple expressions, use cond | |
cond do | |
expression_one() -> one() | |
value1 == "this" -> "yes" | |
expression_two() -> two() | |
end | |
# complex, nested conditions with type and/or value checks, use function pattern matching: | |
result = can_rent?(value) | |
def can_rent?(%App.User{age: age}) when age >= 30, do: true | |
def can_rent?(%App.Company{email: email, approved: true}) when is_binary(email), do: true | |
def can_rent?(%App.Employee{level: "senior"}), do: true | |
def can_rent?(_), do: false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment