If-Else & Loops
RES@val external isMorning: bool = "isMorning"
@val external showMenu: bool = "showMenu"
@val external displayMenu: unit => unit = "displayMenu"
@val external startValueInclusive: int = "startValueInclusive"
@val external endValueInclusive: int = "endValueInclusive"
@val external testCondition: bool = "testCondition"
ReScript supports if, else, ternary expression (a ? b : c), for and while.
The switch pattern supports a default case. Read more about pattern-matching & destructuring.
If-Else & Ternary
ReScript's if is an expression; it evaluates to its body's content:
Note: an if-else expression without the final else branch implicitly gives () (aka the unit type). So this:
is basically the same as:
Here's another way to look at it. This is clearly wrong:
RESlet result = if showMenu {
1 + 2
}
It'll give a type error, saying basically that the implicit else branch has the type unit while the if branch has type int. Intuitively, this makes sense: what would result's value be, if showMenu was false?
We also have ternary sugar, but we encourage you to prefer if-else when possible.
if-else and ternary are often replaced by pattern matching, which handles a wide range of conditional logic more expressively.
For Loops
For loops iterate from a starting value up to (and including) the ending value.
The loop body must evaluate to unit (()). If its last expression returns another type, discard the result with ->ignore, for example someFunction(i)->ignore.
You can make the for loop count in the opposite direction by using downto.
While Loops
While loops execute its body code block while its condition is true.
Tips & Tricks
There's no loop-breaking break keyword (nor early return from functions, for that matter) in ReScript. However, we can break out of a while loop easily through using a mutable binding.