Conditional structures: Difference between revisions

m (→‎{{header|Forth}}: fix markup)
(→‎{{header|langur}}: added switch)
Line 3,468:
 
=={{header|langur}}==
If and switch/given expressions always produce a value, even if it's nothing (null).
 
In the shortened forms, you dispense with the keywords (except the first one).
Line 3,503:
<syntaxhighlight lang="langur">if .x > .y: break</syntaxhighlight>
 
===switch/given expressions===
GivenSwitch and given expressions are highly flexible, and it is not all covered here. See langurlang.org for details.
 
Switch was added to langur 0.11. The difference between switch and given is that switch defaults to testing that any condition is true (as familiar to many programmers) and given defaults to testing that all conditions are true.
Given expressions are scoped per section. Also, test expressions (such as the .x, .y, .z list below) may contain declarations which are scoped to the entire expression.
 
<syntaxhighlight lang="langur">givenswitch .x, .y, .z {
defaultcase true: ...
# .aany >are .btrue
case 7 <, 14false, 21_: ...
# .zx == 7 xor .a <= .bfalse
case _, _null, == 7; xor .a <= .btrue: ...
# 7 < .x and .y == 14null andor 21.z !== .ztrue
case orxor > 100_, _true, re/abc/true: ...
# .y == true xor .z == true
}
 
switch 0 {
case .x, .y: ...
# .x or .y equals 0
...
}
 
given .x, .y, .z {
case true: ...
# all are true
Line 3,518 ⟶ 3,535:
 
As of 0.7, complex test expressions are evaluated once, then compared against conditions.
 
The default logical operator between multiple conditions is "and" (even when there is a single test expression). You can specify another operator after the "case" keyword, using something like "case or".
 
<syntaxhighlight lang="langur">given .x, .y, != .z {
case 7 <, 14, 21: ...
# 7 < .x and .y == 14 and 21 != .z
 
case or > 100, _, re/abc/: ...
# .x > 100 or matching(re/abc/, .z)
 
case ; .a > .b: ...
# .a > .b
 
case _, _, == 7; xor .a <= .b: ...
# .z == 7 xor .a <= .b
 
default: ...
}</syntaxhighlight>
 
===implicit fallthrough===
If a block of a switch or given has any statements, there is no implicit fallthrough. A case with an empty block after it creates an implicit fallthrough.
<syntaxhighlight lang="langur">given .x {
case true:
Line 3,548 ⟶ 3,547:
 
===explicit fallthrough from anywhere===
A fallthrough statement is allowed anywhere within a switch or given block, not just at the end.
<syntaxhighlight lang="langur">given .x {
case true:
Line 3,559 ⟶ 3,558:
}</syntaxhighlight>
 
===shortened form switch/given===
A shortened form given expects a single action expression per test and is more limited in other ways, as well (no explicit fallthrough, no alternate test expressions, no alternate logical operators). A default section is optional (null by default).
<syntaxhighlight lang="langur">given(.x, .y, .z;
true: ... ; # all are equal to true
885

edits