Nasal Conditionals: Difference between revisions

Jump to navigation Jump to search
If I have undestood correctly then the example given did not illustrate the feature it was intended to, that is that the 'if' clause is an expression that reurns a value.
m (Remove line numebrs)
(If I have undestood correctly then the example given did not illustrate the feature it was intended to, that is that the 'if' clause is an expression that reurns a value.)
Line 76: Line 76:


Nasal has no "statements", which means that any expression can appear in any context. This means that you can use an if/else clause to do what the ?: (ternary operator) does in C.  
Nasal has no "statements", which means that any expression can appear in any context. This means that you can use an if/else clause to do what the ?: (ternary operator) does in C.  
The last semicolon in a code block is optional, to make this prettier:
The last semicolon in a code block is optional, to make this prettier. First, a completely conventional implementation of the '''abs''' function:


<syntaxhighlight lang="nasal">
<syntaxhighlight lang="nasal">
Line 86: Line 86:
}
}
</syntaxhighlight>
</syntaxhighlight>
This form would work as it is in "C" and, with minor adjustments for syntax, in many other languages. However, te following form would not work in "C":
<syntaxhighlight lang="nasal">
var abs = func(n) {
    return if (n<0)
    { -n }
    else
    { n }
}
</syntaxhighlight>
In this form the '''if''' clause is clearly an expression that yields a value. That value is the result of the last expression executed within the '''if''' clause.


And for those who don't like typing, the ternary operator works like you expect:
And for those who don't like typing, the ternary operator works like you expect:
Line 92: Line 105:
var abs = func(n) { n < 0 ? -n : n }
var abs = func(n) { n < 0 ? -n : n }
</syntaxhighlight>
</syntaxhighlight>
This also illustrates that a function will return a value even when there is no '''return''' clause. The value returned is the value of the last expression evaluated within the function.


In addition, Nasal supports braceless blocks, like they're known from C/C++ and other languages. Basically, the block ends with a semicolon, instead of being encapsulated inside a <tt>{</tt>/<tt>}</tt> pair. This means basically that the first statement (expression) after a conditional is evaluated if the condition is true, otherwise it will be ignored:
In addition, Nasal supports braceless blocks, like they're known from C/C++ and other languages. Basically, the block ends with a semicolon, instead of being encapsulated inside a <tt>{</tt>/<tt>}</tt> pair. This means basically that the first statement (expression) after a conditional is evaluated if the condition is true, otherwise it will be ignored:
15

edits

Navigation menu