Conditional structures: Difference between revisions

m
→‎case without a default: the error discussed isn’t syntactic
(→‎{{header|Java}}: Added switch expressions)
m (→‎case without a default: the error discussed isn’t syntactic)
 
(18 intermediate revisions by 16 users not shown)
Line 2:
{{Control Structures}}
[[Category:Simple]]
[[Category:Flow control]]
 
;Task:
Line 587 ⟶ 588:
);</syntaxhighlight>
====case expressions====
Using the same example above, we assume that the <syntaxhighlight lang="ada">''Operation</syntaxhighlight>'', <syntaxhighlight lang="ada">''Op</syntaxhighlight>'', and <syntaxhighlight lang="ada">''Result</syntaxhighlight>'' variables are declared. A case expression over the enumeration of operations might look like:
<syntaxhighlight lang="ada">Result := (case Op is
Add => A + B,
Line 596 ⟶ 597:
</syntaxhighlight>
Note: some websites (particularly [https://www.radford.edu/nokie/classes/320/abe/operators.html#:~:text=if%20and%20case-,Examples%3A,1%2C%20others%20%3D%3E%200)%3B this one]) contain a different variant of a case expression (<syntaxhighlight lang="ada">case Op of...</syntaxhighlight>). The Ada Reference Manual indicates this is incorrect, and we use the [http://www.ada-auth.org/standards/12rm/html/RM-4-5-7.html formal version] here.
 
===case with a default alternative===
<syntaxhighlight lang="ada">type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
Line 613 ⟶ 615:
===case without a default===
When there is no '''when others''' clause, the compiler will complain about any uncovered alternative. This defends against a common reason for bugs in other languages.
I.e., the following code is syntactically incorrect:
 
<syntaxhighlight lang="ada">case Today is
Line 625 ⟶ 627:
end case;</syntaxhighlight>
 
The syntactically correct version:
 
<syntaxhighlight lang="ada">case Today is
Line 1,740 ⟶ 1,742:
<syntaxhighlight lang="befunge">& #v_ "0",@ zero
> "X",@ non-zero</syntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
 
Lambda calculus has no conditional structures built in, but the standard representations of booleans can be seen to implement if-then-else: true = \then. \else. then, false = \then. \else. else, which correspond to BLC programs <code>00 00 110</code> and <code>00 00 10</code>.
 
=={{header|blz}}==
Line 2,283 ⟶ 2,289:
// if condition is true var will be set to 1, else false.
int var = condition ? 1 : 2;
</syntaxhighlight>
=={{header|Curto}}==
===si-sino===
<syntaxhighlight lang="curto">( condición ) si ( sentencias si verdadero ) entonces
( condición ) si ( sentencias si verdadero ) sino ( sentencias si falso ) entonces</syntaxhighlight>
ejemplo:
<syntaxhighlight lang="curto">
: menor-que-diez ( n -- )
10 < si
." Menor que 10"
sino
." Mayor o igual a 10"
entonces ;
</syntaxhighlight>
 
Line 2,473 ⟶ 2,492:
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">i = random 10
i = randint 10
if i mod 2 = 0
print i & " is divisible by 2"
elif i mod 3 = 0
print i & " is divisible by 3"
else
print i & " is not divisible by 2 or 3"
.
.</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Efene}}==
Line 2,570 ⟶ 2,591:
x::xs = x :: force xs
[] = []</syntaxhighlight>
 
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
int i = 19
^|if–then–else|^
if i > 18
writeLine("greater than 18")
else
writeLine("less or equal to 18")
end
^|else if|^
if i == 18 do writeLine("equal to 18")
else if i < 18 do writeLine("less than 18")
else do writeLine("greater than 18")
end
^|when expression: just like iif in Visual Basic|^
writeLine(when(i > 18, "greater than 18", "less or equal to 18"))
^|hash-based conditionals|^
Map dispatch = int%fun[
18 => <|writeLine("equal to 18"),
19 => <|writeLine("yeah, it's 19")]
if dispatch.has(i) do dispatch[i]() end
</syntaxhighlight>
{{out}}
<pre>
greater than 18
greater than 18
greater than 18
yeah, it's 19
</pre>
 
=={{header|Erlang}}==
Line 3,408 ⟶ 3,460:
=={{header|J}}==
See [[Conditional Structures/J]]
 
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn main() {
let a = 5
let b = 3
 
// If/else/else-if
if a > b {
println("a > b")
} else if a < b {
println("a < b")
} else {
println("a = b")
}
 
// Match
match a {
(..5) => {
println("a < 5")
}
5 => {
println("a == 5")
}
else => {
println("a > 5")
}
}
 
// Or equivalently
println(match a {
(..5) => "a < 5"
5 => "a == 5"
else => "a > 5"
})
 
// Hash based
let primality = [
1: false
2: false
3: true
4: false
5: true
6: false
]
let a_is_prime = primality[a]
println("a_is_prime = {}", a_is_prime)
}
</syntaxhighlight>
 
=={{header|Java}}==
Line 3,794 ⟶ 3,895:
 
=={{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,818 ⟶ 3,919:
 
===simple if===
Langur 0.7.1 added simpleSimple if expressions (previously erroneously called "if statements") usinguse a colon after the test condition. This is convenient for simple branching or assignments, without having to use curly braces, but does not allow for else if or else sections.
 
<syntaxhighlight lang="langur">if .x > .y: break</syntaxhighlight>
 
===switch/given expressions===
Switch 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), andbut giventhis defaultscan tobe testingchanged thatby allspecifying conditionsan areinfix trueoperator within square brackets, such as switch[and].
 
<syntaxhighlight lang="langur">switch .x, .y, .z {
Line 3,844 ⟶ 3,945:
}
 
givenswitch[and] .x, .y, .z {
case true: ...
# all are true
Line 3,853 ⟶ 3,954:
}</syntaxhighlight>
 
As of 0.7, complexComplex test expressions are evaluated once, then compared against conditions.
 
===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">givenswitch .x {
case true:
# implicit fallthrough
Line 3,866 ⟶ 3,967:
 
===explicit fallthrough from anywhere===
A fallthrough statement is allowed anywhere within a switch or given block, not just at the end. (It's typical in programming languages to only allow fallthrough at the end of the block.)
 
<syntaxhighlight lang="langur">given .x {
<syntaxhighlight lang="langur">switch .x {
case true:
if .y > 100 {
Line 3,877 ⟶ 3,979:
}</syntaxhighlight>
 
===shortened form switch/given===
A shortened form 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">givenswitch(.x, .y, .z;
true: ... ; # allany are equal to true
_, >= .z: ...; # .y >= .z
... ) # default</syntaxhighlight>
Line 5,157 ⟶ 5,259:
 
=={{header|Ol}}==
if-then, the simplest conditional `if` primitive.
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4) (print "if-then: equal"))
(if (= (* 2 2) 6) (print "if-then: non equal"))
(if (= (* 2 2) 6)
(print "if-then: should not be printed"))
; ==> if-then: equal
</syntaxhighlight>
 
if-then-else, the full conditional '`if'` primitive.
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4) (print "if-then-else: equal") (print "if-then-else: non equal"))
(if (= (* 2 2) 6) (print "if-then-else: non equal") (print "if-then-else: i don't know"))
(print "if-then-else: non equal"))
; ==> if-then-else: equal
 
; ==> if-then-else: i don't know
(if (= (* 2 2) 6)
(print "if-then-else: equal")
(print "if-then-else: non equal"))
; ==> if-then-else: non equal
</syntaxhighlight>
 
when and unless, the oppositesimplification forof '`if'.` without `begin`
<syntaxhighlight lang="scheme">
(unlesswhen (= (* 2 2) 4) (print "unless: non equal"))
(unless (= (* 2 2) 6) (print "unlesswhen: i..just don'tdo knowsomething.."))
(unless (= (* 2 2) 4) (print "unless: non equal") (print "unlesswhen: equal"))
; ==> when: ..just do something..
(unless (= (* 2 2) 6) (print "unless: i don't know") (print "unless: non equal"))
; ==> unlesswhen: i don't knowequal
 
; ==> unless: equal
(unless (= (* 2 2) 6)
; ==> unless: i don't know
(print "unless: ..just do something..")
(print "unless: not equal"))
; ==> unless: ..just do something..
; ==> unless: not equal
</syntaxhighlight>
 
if-then-else, extended conditional `if` primitive.
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4)
(print "if-then-else*: equal")
else
(print "if-then-else*: ..just do something..")
(print "if-then-else*: non equal"))
; ==> if-then-else*: equal
 
(if (= (* 2 2) 4)
then
(print "if-then-else*: ..just do something..")
(print "if-then-else*: equal")
else
(print "if-then-else*: ..just do something..")
(print "if-then-else*: non equal"))
; ==> if-then-else*: ..just do something..
; ==> if-then-else*: equal
 
(if (= (* 2 2) 4) ; same as `when`
then
(print "if-then-else*: ..just do something..")
(print "if-then-else*: equal"))
; ==> if-then-else*: ..just do something..
; ==> if-then-else*: equal
</syntaxhighlight>
 
Line 5,186 ⟶ 5,326:
<syntaxhighlight lang="scheme">
(case (* 2 2)
(3 ; exact number
(print "case: 3"))
(4 ; exact number
(print "case: 4"))
((5 6 7) ; list of numbers
(print "case: 5 or 6 or 7"))
(else
(print "case: i don't know")))
; ==> case: 4
</syntaxhighlight>
 
; extended case with usable else
additionally, case can select vectors with variables filling
(case (* 2 2)
<syntaxhighlight lang="scheme">
(3 ; exact number
(case (vector 'selector 1 2 3)
(print "case: 3"))
(else => (lambda (num)
(print "case: real value is " num))))
; ==> case: real value is 4
 
(case (* 2 2)
(3 ; exact number
(print "case: 3"))
(else is num
(print "case: real value is " num)))
; ==> case: real value is 4
 
; extended case with vectors
(case ['selector 1 2 3]
(['case1 x y]
(print "case: case1 " x ", " y))
Line 5,206 ⟶ 5,359:
(else
(print "case: i don't know")))
; ==> tuple-case: selector 1, 2, 3
</syntaxhighlight>
 
Line 6,420 ⟶ 6,573:
 
(<code>]'[</code>, pronounced "meta-literal" grants the property of <code>'</code> (pronounced "literal", <code>'</code> places the item following it on the stack and unconditionally branches over it) to the enclosing nest.)
 
See [[Flow-control structures#Quackery]] for a deeper dive into Quackery control flow.
 
=={{header|R}}==
Line 6,757 ⟶ 6,912:
}}
</syntaxhighlight>
 
=={{header|RPL}}==
'''IF..THEN'''
'''IF''' <instruction(s)> '''THEN''' <instruction(s)> '''END'''
'''IF..THEN..ELSE'''
'''IF''' <instruction(s)> '''THEN''' <instruction(s)> '''ELSE''' <instruction(s)> '''END'''
Instructions between <code>IF</code> and <code>THEN</code> are not mandatory, but recommended for lisibility. The interpreter considers <code>IF</code> as a null word and performs branching when meeting the word <code>THEN</code>: if stack level 1 is not equal to zero, the instructions between <code>THEN</code> and <code>END</code> will be executed.
 
<code>IFT</code> and <code>IFTE</code> are stack-based conditonal structures. <code>IFT</code> evaluates the content of stack level 1 only if the content of stack level 2 is not zero, otherwise it is dropped. <code>IFTE</code> evaluates the content of stack level 1 if the content of stack level 2 is zero, otherwise if evaluates the content of stack level 2.
 
'''CASE..END'''
'''CASE'''
<instruction(s)> '''THEN''' <instruction(s)> '''END'''
<instruction(s)> '''THEN''' <instruction(s)> '''END'''
<span style="color:grey">@ as many branches as needed</span>
<instruction(s)> <span style="color:grey">@ default branch (optional)</span>
'''END'''
 
=={{header|Ruby}}==
Line 7,230 ⟶ 7,402:
(else 'zero))</syntaxhighlight>
 
=={{header|SmallBASIC}}==
 
===if===
 
<syntaxhighlight lang="basic">
IF foo == 1
PRINT "one"
ELSEIF foo == 2
PRINT "two"
ELSE
PRINT "something else"
ENDIF
</syntaxhighlight>
 
===Inline if===
<syntaxhighlight lang="basic">ans = iff(x <= 5, 0, 10)</syntaxhighlight>
 
===select===
<syntaxhighlight lang="basic">
select case x
case 12
print "x is 12"
case 13,14,15
print "x is 13,14,or 15"
case iff(x <= 4, x, x + 1)
print "x <= 4"
case else
print "x is not <=4,12,13,14,15"
end select
</syntaxhighlight>
 
=={{header|Smalltalk}}==
Line 7,851 ⟶ 8,050:
There are optional <code>elif</code> (else if) and <code>else</code> clauses.
 
<syntaxhighlight lang="sh">if test 4 -ge 6; then
then echo '4 is greater than or equal to 6'
elif test 4 -lt 6; then
then echo '4 is less than 6'
else echo '4 compares not to 6'
else
echo '4 compares not to 6'
fi</syntaxhighlight>
 
Line 7,917 ⟶ 8,115:
else
x * fac (Nat.drop x 1)</syntaxhighlight>
 
=={{header|Ursalang}}==
===if…then…else===
Ursalang has a single conditional construct, the familiar `if…then…else`.<syntaxhighlight lang="ursalang">
if energyLevel > 9000 { "That's impossible!!!" } else { "Ok, I guess" }
</syntaxhighlight>As in most C-like languages, conditionals can be chained:<syntaxhighlight>
if color == "red" { "aaaaaah!" }
else if color == "blue" { "oooooh!" }
else { "eeeeeeee!" }
</syntaxhighlight>
 
=={{header|V}}==
Line 8,443 ⟶ 8,651:
=={{header|Wren}}==
The ''if/else'' statement and the ''ternary operator (?:)'' are Wren's basic conditional structures though it can be argued that the ''&&'' and ''||'' operators, which do short-circuit evaluation, should be included under this heading as well.
<syntaxhighlight lang="ecmascriptwren">for (b in [true, false]) {
if (b) {
System.print(true)
5

edits