Conditional Expressions
Basic Syntax
Wyrd provide three kind of syntax for structuring conditional expressions.
"One-Liner" If-Arrow Expression
If you want to directly output a value or a simple operation result, you can use the if <condition> => <expression>
format of the conditional expression:
Notice that the if <condition> ... else if ...
part, the keyword to chain the expression is simplified into elif
keyword.
"Single-Line-Block" If-Then Expression
The second conditional expression syntax style is the if <condition> then ...
style. You will need to change to new line after the then
keyword.
Notice that, then
block only evaluates single line expression as the result, and since the then
expression is block format, to close the expression, we need to use the end
keyword.
The compile result will be identical to the previous if-arrow
conditional example in previous section.
"Multi-Line Block" If-Do Expression
In Wyrd, if the content to be evaluated cannot easily be expressed in single-line, you can instead use the do
block expression which it will use the last expression in the do
block expression as return value.
By inspecting the Wyrd compilation result, we can see that Wyrd automatically compiles the do
block conditional expression using JavaScript IIFE (Immediately Invoked Function Expression).
Conditional Expression Returns Value
As described partially in the previous section, since most of the syntax in Wyrd are expressions, it will return values. In other words, we can do something like, for instance, assigning the evaluation result of conditional expression to a variable.
TODO: Advanced information about Wyrd - Most of the Wyrd program are expressions.
If-Condition Must Receive Boolean Type
In JavaScript, values, such as number 0, empty string ... etc, are tend to be false
if they are used as the condition in conditional statement:
However, Wyrd strictly limited developers to only provide any expressions which returns value of type Bool
. Hence, the following Wyrd program will throw error:
If you want to check if something is (or is not) 0, you should instead explicitly point out within the condition. Thus, the previous program example might need to adjust into:
Return Type of Each Branch Must Be Identical
Since Wyrd is strongly typed programming language, it will automatically check each conditional branch's returned result.
If Wyrd found out that the return type of either one or more branches differ, then it will raise error:
TODO: Error message might need to be more comprehensive, e.g. pointing out the branch where returned type differs.
Conditional Expressions Without Else Part Returns "Maybe" Types
If a conditional expression lacks the else
expression, since the condition might be False
, it will instead return Null
value in default. (See Variable Declarations)
Hence, the return type of the conditional expression without else
expression will return maybe
type data. (See Built-in Types)
Last updated
Was this helpful?