gleam
gleam copied to clipboard
Error showing how to use `case` instead of `if`
Related:
- If statement discussion: https://github.com/gleam-lang/gleam/discussions/2158#discussioncomment-10455378
- Reply to comment on making it convert if to case: https://github.com/gleam-lang/gleam/discussions/2158#discussioncomment-10455378
A simple lint which would convert a more conventional if
statement into a case
expression.
Examples:
if alpha > beta {
alpha
} else {
beta
}
this would give a helpful error, explaining that if
does not exist and you should use case
instead:
error: `if` is invalid
┌─ /src/main.gleam:1:1
│
6 │ if alpha > beta {
│ ^^
`if` is not valid gleam.
Hint: You can do this with Case instead:
case alpha > beta {
True -> alpha
False -> beta
}
See: https://tour.gleam.run/flow-control/case-expressions/
I imagine the algorithum for this is fairly simple. If an if statement is found, extract the expression beginning after it until the curly brace, the code within the if {}
block, and the code within the else {}
block, and subsitute them here:
case <<CONDITION>> {
// if its single line you can remove the block
True -> { <<CODE_IF>> }
False -> { <<CODE_ELSE>> }
}
This solution only works for boolean expressions, but thats fine because an if
is inherently boolean. Im sure the error message itself can be improved a lot too, I just wrote something to get the idea down.