Elixir, lesson 4
A program often has to pick one of several paths: is the password long enough, did the player win, is it a weekend? Elixir gives you three tools for this, and each one is an expression that returns a value.
| Operator | Meaning |
|---|---|
== / != | equal / not equal |
<, <=, >, >= | ordering |
=== / !== |
2 exercises to try what you just read.
| strictly equal, also checks integer vs float |
1 == 1.0 is true, but 1 === 1.0 is false. For everyday comparisons == is what you want.
Combine conditions with and, or and not. They expect real booleans on the left, which
catches mistakes early. Their cousins &&, || and ! accept any value: in Elixir only false
and nil count as false, and everything else (including 0 and "") counts as true.
if and elseUse if for a simple yes/no choice. Because it is an expression, you can bind its result:
For longer branches, use the block form:
cond: the first true condition winsWhen you have more than two choices, cond is cleaner than nested ifs. Elixir checks each
condition from top to bottom and runs the first one that is true. End with true -> as a
catch-all, because cond raises an error if nothing matches.
case: match on shape, with guardscase compares a value against patterns. A pattern can be a literal like 0, a structure
like {:ok, value}, or a name that matches anything. Add a guard with when to require an
extra condition.
The _ at the end matches anything, like an "else". Reach for case when the decision depends
on the shape of a value, and cond when it depends on a list of conditions.
Read a test score and print its letter grade:
90 to 100: A80 to 89: B70 to 79: C60 to 69: D0 to 59: F0 or above 100: InvalidInput: one line with a whole number. Output: the grade on one line. For 85, print B.
A year is a leap year if it is divisible by 4, except years divisible by 100, which are not, unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.
Input: one line with a year. Output: leap or common.
age = 20
member = true
IO.puts(age >= 18 and member) # true
IO.puts(not member) # falsetemp = 31
advice = if temp > 25, do: "Wear a hat", else: "Bring a jacket"
IO.puts(advice)if temp > 25 do
IO.puts("It's hot!")
else
IO.puts("It's fine.")
endspeed = 72
label =
cond do
speed > 120 -> "way too fast"
speed > 50 -> "fast"
true -> "relaxed"
end
IO.puts(label) # fastcase Integer.parse("17") do
{n, ""} when n < 0 -> IO.puts("negative")
{n, ""} -> IO.puts("the number #{n}")
_ -> IO.puts("not a number")
end