Conditional structures: Difference between revisions

Content added Content deleted
(→‎{{header|AWK}}: with braces)
m (Category:Simple, {{out}})
Line 1: Line 1:
{{Task|Control Structures}}{{Control Structures}}This page lists the conditional structures offered by different programming languages. Common conditional structures are '''if-then-else''' and '''switch'''.
{{Task|Control Structures}}{{Control Structures}} [[Category:Simple]],
This page lists the conditional structures offered by different programming languages.
Common conditional structures are '''if-then-else''' and '''switch'''.


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
6502 Assembly has 8 conditional branch instructions; each instruction will test the appropriate flag and condition and jump between -128 and 127 bytes. To understand these conditional instructions, it is helpful to remember that the comparison instructions (CMP, CPX, CPY) set the flags as if a subtraction had occurred:
6502 Assembly has 8 conditional branch instructions; each instruction will test the appropriate flag and condition and jump between -128 and 127 bytes.
To understand these conditional instructions, it is helpful to remember that the comparison instructions (CMP, CPX, CPY) set the flags as if a subtraction had occurred:
<lang 6502asm> LDA #10
<lang 6502asm> LDA #10
CMP #11</lang>
CMP #11</lang>
Following these instructions, the accumulator will still hold 10 but the flags are set as if you had instructed the processor to perform 10 - 11. The result is -1, so the sign flag will be set, the zero flag will be cleared, the overflow flag will be cleared, and the carry flag will be set.
Following these instructions, the accumulator will still hold 10 but the flags are set as if you had instructed the processor to perform 10 - 11.
The result is -1, so the sign flag will be set, the zero flag will be cleared, the overflow flag will be cleared, and the carry flag will be set.
<lang 6502asm> BNE ;Branch on Not Equal - branch when the zero flag is set
<lang 6502asm> BNE ;Branch on Not Equal - branch when the zero flag is set
BEQ ;Branch on EQual - branch when the zero flag is set.
BEQ ;Branch on EQual - branch when the zero flag is set.
Line 38: Line 42:
DEX
DEX
BNE Loop</lang>
BNE Loop</lang>
This code will loop until X is zero.
This code will loop until X is zero. Most assemblers will figure out the correct offset for you if you use a label in place of the offset after a branch instruction, as in the above example.
Most assemblers will figure out the correct offset for you if you use a label in place of the offset after a branch instruction, as in the above example.


=={{header|ActionScript}}==
=={{header|ActionScript}}==
Line 71: Line 76:


===case without a default===
===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:
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:


<lang ada>case Today is
<lang ada>case Today is
Line 97: Line 103:


===select===
===select===
Select provides conditional acceptance of entry calls. Select can also be used to conditionally call an entry
Select provides conditional acceptance of entry calls.
Select can also be used to conditionally call an entry

====Conditional Accept====
====Conditional Accept====
<lang ada>select
<lang ada>select
Line 106: Line 114:
or terminate;
or terminate;
end select;</lang>
end select;</lang>

====Conditional entry call====
====Conditional entry call====
A selective entry call provides a way to time-out an entry call. Without the time-out the calling task will suspend until the entry call is accepted.
A selective entry call provides a way to time-out an entry call.
Without the time-out the calling task will suspend until the entry call is accepted.
<lang ada>select
<lang ada>select
My_Task.Start;
My_Task.Start;
Line 113: Line 123:
delay Timeout_Period;
delay Timeout_Period;
end select;</lang>
end select;</lang>
The entry Start on the task My_Task will be called. If My_Task accepts the entry call before the timer expires the timer is canceled. If the timeout expires before the entry call is accepted the entry call is canceled.
The entry Start on the task My_Task will be called.
If My_Task accepts the entry call before the timer expires the timer is canceled. If the timeout expires before the entry call is accepted the entry call is canceled.


=={{header|Aikido}}==
=={{header|Aikido}}==
Line 160: Line 171:
println ("RETRY")
println ("RETRY")
}
}



</lang>
</lang>


Line 187: Line 195:


In AmbientTalk, if:then:else: is a keyworded message (as in Smalltalk).
In AmbientTalk, if:then:else: is a keyworded message (as in Smalltalk).
The first argument should be a boolean expression. The second and third arguments should be blocks (aka anonymous functions or thunks).
The first argument should be a boolean expression.
The second and third arguments should be blocks (aka anonymous functions or thunks).


<lang ambienttalk>
<lang ambienttalk>
Line 495: Line 504:


=={{header|Befunge}}==
=={{header|Befunge}}==
Befunge only has one conditional structure, which comes in two flavors: ''vertical IF'' ( | ) and ''horizontal IF'' ( _ ). Befunge only has two boolean commands, ''greater-than'' ( ` ) and ''not'' ( ! ). These snippets input a number and use the conditional operators to print a "0" if it is zero and an "X" otherwise.
Befunge only has one conditional structure, which comes in two flavors: ''vertical IF'' ( | ) and ''horizontal IF'' ( _ ).
Befunge only has two boolean commands, ''greater-than'' ( ` ) and ''not'' ( ! ).
These snippets input a number and use the conditional operators to print a "0" if it is zero and an "X" otherwise.


<lang befunge>v > "X",@ non-zero
<lang befunge>v > "X",@ non-zero
Line 501: Line 512:
> "0",@ zero</lang>
> "0",@ zero</lang>


'''#''' is the skip command. It unconditionally skips one character, allowing a little flexibility in flow control.
'''#''' is the skip command.
It unconditionally skips one character, allowing a little flexibility in flow control.


<lang befunge>& #v_ "0",@ zero
<lang befunge>& #v_ "0",@ zero
Line 519: Line 531:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
=== "if .. then .. else .." type of branching ===
=== "if .. then .. else .." type of branching ===
Bracmat uses & and | for branching.
Bracmat uses & and | for branching. These binary operators are like && and || in C-like languages. Bracmat does not have the notion of Boolean variables, but marks all evaluated expressions as either succeeded or failed. If the left hand side of the & operator has succeeded, Bracmat goes on evaluating the right hand side. Only if both of left and right hand sides succeed, the expression tree headed by the & operator as a whole succeeds. Likewise, only if both of left and right hand sides of an expression tree headed by | fail, the expression tree as a whole fails. Evaluated expressions are just that: expressions. The following expression writes "That's what I thought." to your screen and evaluates to the expression "Right".
These binary operators are like && and || in C-like languages.
Bracmat does not have the notion of Boolean variables, but marks all evaluated expressions as either succeeded or failed.
If the left hand side of the & operator has succeeded, Bracmat goes on evaluating the right hand side.
Only if both of left and right hand sides succeed, the expression tree headed by the & operator as a whole succeeds. Likewise, only if both of left and right hand sides of an expression tree headed by | fail, the expression tree as a whole fails.
Evaluated expressions are just that: expressions.
The following expression writes "That's what I thought." to your screen and evaluates to the expression "Right".


<lang bracmat> 2+2:5
<lang bracmat> 2+2:5
Line 528: Line 546:


=== switch-like branching ===
=== switch-like branching ===
Use a patterns with alternations. Note that the match-expression (the tree headed by the : operator) evaluates to the left hand side of the : operator. In the following example, the resulting expression is a single node containing "4".
Use a patterns with alternations. Note that the match-expression (the tree headed by the : operator) evaluates to the left hand side of the : operator.
In the following example, the resulting expression is a single node containing "4".


<lang bracmat> 2+2
<lang bracmat> 2+2
Line 542: Line 561:
=={{header|Brainf***}}==
=={{header|Brainf***}}==


Brainf*** has two conditional jump instructions, [ and ]. the [ instruction jumps forward to the corresponding ] instruction if the value at the current memory cell is zero, while the ] instruction jumps back if the current memory cell is nonzero. Thus in the following sequence:
Brainf*** has two conditional jump instructions, [ and ]. the [ instruction jumps forward to the corresponding ] instruction if the value at the current memory cell is zero, while the ] instruction jumps back if the current memory cell is nonzero.
Thus in the following sequence:


<lang bf>[.]</lang>
<lang bf>[.]</lang>
Line 628: Line 648:
=={{header|Clean}}==
=={{header|Clean}}==
===if===
===if===
There are no ''then'' or ''else'' keyword in Clean. The second argument of <tt>if</tt> is the then-part, the third argument is the else-part.
There are no ''then'' or ''else'' keyword in Clean.
The second argument of <tt>if</tt> is the then-part, the third argument is the else-part.
<lang clean>bool2int b = if b 1 0</lang>
<lang clean>bool2int b = if b 1 0</lang>

===case-of===
===case-of===
<lang clean>case 6 * 7 of
<lang clean>case 6 * 7 of
42 -> "Correct"
42 -> "Correct"
_ -> "Wrong" // default, matches anything</lang>
_ -> "Wrong" // default, matches anything</lang>

===function alternatives===
===function alternatives===
<lang clean>answer 42 = True
<lang clean>answer 42 = True
answer _ = False</lang>
answer _ = False</lang>

===guards===
===guards===
<lang clean>answer x
<lang clean>answer x
Line 656: Line 680:
SomeFunc()
SomeFunc()
ENDIF</lang>
ENDIF</lang>

'''do case'''
'''do case'''
<lang clipper>DO CASE
<lang clipper>DO CASE
Line 675: Line 700:


===when===
===when===
Similar to if, but body in an implicit do block allowing multiple statements. No facility for providing an else. <code>when</code> is defined as a macro.
Similar to if, but body in an implicit do block allowing multiple statements.
No facility for providing an else. <code>when</code> is defined as a macro.
<lang clojure>(when x
<lang clojure>(when x
(print "hello")
(print "hello")
Line 682: Line 708:


===cond===
===cond===
The cond macro takes a series of test/result pairs, evaluating each test until one resolves to logical true, then evaluates its result. Returns nil if none of the tests yield true.
The cond macro takes a series of test/result pairs, evaluating each test until one resolves to logical true, then evaluates its result.
Returns nil if none of the tests yield true.
<lang clojure>(cond
<lang clojure>(cond
(= 1 2) :no) ; returns nil
(= 1 2) :no) ; returns nil
Line 726: Line 753:
endif()</lang>
endif()</lang>


The if() and elseif() commands evaluate boolean expressions like ''num GREATER 100''; refer to [http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:if cmake --help-command if]. The elseif() and else() sections are optional.
The if() and elseif() commands evaluate boolean expressions like ''num GREATER 100''; refer to [http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:if cmake --help-command if].
The elseif() and else() sections are optional.


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 822: Line 850:
then "yup"
then "yup"
else "nope"</lang>
else "nope"</lang>




=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
Line 856: Line 882:
===(if cond then [else])===
===(if cond then [else])===


The (if ...) construct takes a predicate as its first argument and evaluates it. Should the result be non-nil, it goes on to evaluate and returnm the results of the 'then' part, otherwise, when present, it evaluates and returns the result of the 'else' part. Should there be no 'else' part, it returns nil.
The (if ...) construct takes a predicate as its first argument and evaluates it.
Should the result be non-nil, it goes on to evaluate and returnm the results of the 'then' part, otherwise, when present, it evaluates and returns the result of the 'else' part. Should there be no 'else' part, it returns nil.


<lang lisp>(if (= val 42)
<lang lisp>(if (= val 42)
Line 1,030: Line 1,057:
io.writeln( 'a is neither 1 nor 3' )
io.writeln( 'a is neither 1 nor 3' )
}</lang>
}</lang>

===Switch Case===
===Switch Case===
<lang java>a = 3
<lang java>a = 3
Line 1,105: Line 1,133:
=={{header|Efene}}==
=={{header|Efene}}==


the expressions can contain parenthesis or not, here both options are shown
The expressions can contain parenthesis or not, here both options are shown.
Since if and case do pattern matching, if an if or case expression don't match some of the patterns, the program will crash

since if and case do pattern matching if an if or case expression don't match some of the patterns the program will crash


<lang efene>
<lang efene>
Line 1,195: Line 1,222:
=={{header|Erlang}}==
=={{header|Erlang}}==


Erlang's conditionals are based on pattern matching and guards.
Erlang's conditionals are based on pattern matching and guards. There are several mechanisms for this: case-of, if, function clauses. Pattern matching allows destructuring a term and matches a clause based on the structure. In the case example the term is X and the pattern is {N,M} or _. _ will match anything, while {N,M} will only match tuples of two terms. Though N and M could be any other type (in this case an error will occur if they're non-numeric). Guards allow more specification on the terms from the matched pattern. In the case example comparing N and M are guards.
There are several mechanisms for this: case-of, if, function clauses.
Pattern matching allows destructuring a term and matches a clause based on the structure.
In the case example the term is X and the pattern is {N,M} or _. _ will match anything, while {N,M} will only match tuples of two terms.
Though N and M could be any other type (in this case an error will occur if they're non-numeric).
Guards allow more specification on the terms from the matched pattern. In the case example comparing N and M are guards.


===case===
===case===
Line 1,209: Line 1,241:
===if===
===if===


if expressions match against guards only, without pattern matching. Guards must evaluate to true or false so true is the catch-all clause.
if expressions match against guards only, without pattern matching.
Guards must evaluate to true or false so true is the catch-all clause.


<lang erlang>{N,M} = X,
<lang erlang>{N,M} = X,
Line 1,227: Line 1,260:


=={{header|Factor}}==
=={{header|Factor}}==
There are many conditional structures in Factor. Here I'll demonstrate the most common ones. A few of these have other variations that abstract common stack shuffle patterns. I will not be demonstrating them.
There are many conditional structures in Factor.
Here I'll demonstrate the most common ones.
A few of these have other variations that abstract common stack shuffle patterns.
I will not be demonstrating them.


===?===
===?===
Line 1,918: Line 1,954:
show vowel? "e
show vowel? "e
show vowel? "x</lang>
show vowel? "x</lang>
{{out}}
Output is:
<lang logo>true
<lang logo>true
false</lang>
false</lang>
Line 3,607: Line 3,643:
(- 1 2)))
(- 1 2)))
(newline)</lang>
(newline)</lang>
{{out}}
Output:
<lang>no
<pre>no
#<unspecified></lang>
#<unspecified></pre>

===Derived===
===Derived===
====cond====
====cond====
Line 3,623: Line 3,660:
(else "equal")))
(else "equal")))
(newline)</lang>
(newline)</lang>
{{out}}
Output:
<lang>less
<pre>less
equal</lang>
equal</pre>

====case====
====case====
<lang>(case <key> <clause1> <clause2> ...)</lang>
<lang>(case <key> <clause1> <clause2> ...)</lang>
Line 3,640: Line 3,678:
(else "consonant")))
(else "consonant")))
(newline)</lang>
(newline)</lang>
{{out}}
Output:
<lang>composite
<pre>composite
consonant</lang>
consonant</pre>


=={{header|Seed7}}==
=={{header|Seed7}}==
===if-then-else===
===if-then-else===
There can be single or multiple statements. An if-statement can have multiple elsif parts.
There can be single or multiple statements.
An if-statement can have multiple elsif parts.
<lang seed7>if condition then
<lang seed7>if condition then
statement
statement
Line 4,008: Line 4,047:
y="xyzzy"</pre>
y="xyzzy"</pre>


The <code>cases</code>, <code>all</code> and <code>none</code> directives most resemble control structures because they have short-circuiting behavior. For instance:
The <code>cases</code>, <code>all</code> and <code>none</code> directives most resemble control structures because they have short-circuiting behavior.
For instance:


<lang txr>@(all)
<lang txr>@(all)
Line 4,019: Line 4,059:
@(end)</lang>
@(end)</lang>


If any subclause fails to match, then <code>all</code> stops processing subsequent clauses. There are subtleties though, because an earlier clause can produce variable bindings which are visible to later clauses. If previously bound variable is bound again, it must be to an identical piece of text:
If any subclause fails to match, then <code>all</code> stops processing subsequent clauses. There are subtleties though, because an earlier clause can produce variable bindings which are visible to later clauses.
If previously bound variable is bound again, it must be to an identical piece of text:


<lang txr>@# match a line which contains some piece of text x
<lang txr>@# match a line which contains some piece of text x