Conditional expressions
"If" expressions
"If" syntax
The syntax for anif
expression is simple:
just put the true and false branches in indented blocks.
Using "if" as an expression
Crow's syntax technically does not have any statements; only expressions.
Any line of code not at the end of a block is a void
expression.
When an if
appears in a void
context,
the true and false branches must also be void
expressions.
A call to log
works because
it is a function returning void
.
Since if
is an expression,
it can have a non-void type like string
.
So the first example can be rewritten as:
"Elif"
You can add additional conditions to the chain using elif
.
"If" without "else"
If no else
branch is written, it will default to ()
.
This can create an empty value of most types; for example, it can be an empty string.
"Unless" expressions
unless
works the same as if
except the condition is negated.
This doesn't support an else
branch, since the double negation would be confusing.
Ternary expressions
There is an alternative syntax for short if
expressions.
"guard" expressions
A guard
expression is just like an if
,
except the branch where the condition is true
is written underneath it, and the
else
branch is (optionally)
written to the right after a :
.
Since a guard
is asymmetric,
it's best used for cases where the true
branch is the important one
and the false
branch returns an empty or error value.
A guard
is useful for returning early from a long function.
In Java, the first line would be written as if (!(a.high > b.low)) return false;
..
As with if
, the "else" branch is optional and defaults to ()
.
(()
for bool
is false
).
Scope
Each indented block of code has its own scope. Variables declared within the block can't be used outside of it.
"Do" expressions
do
is an unconditional expression.
It's useful for introducing a new scope.