Skip to content

Instantly share code, notes, and snippets.

@aesmail
Created May 29, 2020 16:12
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aesmail/5eee252afb93528063e4eceef8c78f00 to your computer and use it in GitHub Desktop.
Save aesmail/5eee252afb93528063e4eceef8c78f00 to your computer and use it in GitHub Desktop.
Elixir deciding which control flow to use
# 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