Lesson 7 of 17
Case Expressions
Case Expressions
Gleam does not have if/else statements in the traditional sense. Instead, it uses case expressions for all branching logic:
case value {
pattern1 -> expression1
pattern2 -> expression2
_ -> default_expression
}
Matching on Values
You can match on specific values:
fn describe_day(day: Int) -> String {
case day {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
_ -> "Unknown"
}
}
The _ wildcard matches anything and acts as the default case.
Matching on Booleans
Since Gleam has no if/else, you use case with booleans:
let message = case temperature > 30 {
True -> "It's hot!"
False -> "It's fine."
}
Case Is an Expression
Every case returns a value, so you can bind the result to a variable:
let grade = case score {
score if score >= 90 -> "A"
score if score >= 80 -> "B"
score if score >= 70 -> "C"
_ -> "F"
}
Multiple Patterns
You can match multiple values at once using a tuple pattern:
case x, y {
0, 0 -> "origin"
0, _ -> "y-axis"
_, 0 -> "x-axis"
_, _ -> "elsewhere"
}
Guards
You can add conditions to patterns with if:
case number {
n if n > 0 -> "positive"
n if n < 0 -> "negative"
_ -> "zero"
}
Your Task
Using the recursion concepts from the previous lesson, write a FizzBuzz program.
Write a function called fizzbuzz that takes an Int and returns:
"FizzBuzz"if divisible by both 3 and 5"Fizz"if divisible by 3"Buzz"if divisible by 5- The number as a string otherwise
Use a recursive loop helper to print the result for numbers 1 through 15, each on a separate line.
Gleam runtime loading...
Loading...
Click "Run" to execute your code.