Conditional structures: Difference between revisions

m
(→‎{{header|AWK}}: with braces)
m (Category:Simple, {{out}})
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'''.[[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}}==
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:
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
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.
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
BEQ ;Branch on EQual - branch when the zero flag is set.
Line 38 ⟶ 42:
DEX
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.
 
=={{header|ActionScript}}==
Line 71 ⟶ 76:
 
===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:
I.e., the following code is syntactically incorrect:
 
<lang ada>case Today is
Line 97 ⟶ 103:
 
===select===
Select provides conditional acceptance of entry calls. Select can also be used to conditionally call an entry
Select can also be used to conditionally call an entry
 
====Conditional Accept====
<lang ada>select
Line 106 ⟶ 114:
or terminate;
end select;</lang>
 
====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.
Without the time-out the calling task will suspend until the entry call is accepted.
<lang ada>select
My_Task.Start;
Line 113 ⟶ 123:
delay Timeout_Period;
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.
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}}==
Line 160 ⟶ 171:
println ("RETRY")
}
 
 
 
</lang>
 
Line 187 ⟶ 195:
 
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 second and third arguments should be blocks (aka anonymous functions or thunks).
 
<lang ambienttalk>
Line 495 ⟶ 504:
 
=={{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 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
Line 501 ⟶ 512:
> "0",@ zero</lang>
 
'''#''' is the skip command. It unconditionally skips one character, allowing a little flexibility in flow control.
It unconditionally skips one character, allowing a little flexibility in flow control.
 
<lang befunge>& #v_ "0",@ zero
Line 519 ⟶ 531:
=={{header|Bracmat}}==
=== "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
Line 528 ⟶ 546:
 
=== 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".
In the following example, the resulting expression is a single node containing "4".
 
<lang bracmat> 2+2
Line 542 ⟶ 561:
=={{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:
Thus in the following sequence:
 
<lang bf>[.]</lang>
Line 628 ⟶ 648:
=={{header|Clean}}==
===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.
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>
 
===case-of===
<lang clean>case 6 * 7 of
42 -> "Correct"
_ -> "Wrong" // default, matches anything</lang>
 
===function alternatives===
<lang clean>answer 42 = True
answer _ = False</lang>
 
===guards===
<lang clean>answer x
Line 656 ⟶ 680:
SomeFunc()
ENDIF</lang>
 
'''do case'''
<lang clipper>DO CASE
Line 675 ⟶ 700:
 
===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.
No facility for providing an else. <code>when</code> is defined as a macro.
<lang clojure>(when x
(print "hello")
Line 682 ⟶ 708:
 
===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.
Returns nil if none of the tests yield true.
<lang clojure>(cond
(= 1 2) :no) ; returns nil
Line 726 ⟶ 753:
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 elseif() and else() sections are optional.
 
=={{header|COBOL}}==
Line 822 ⟶ 850:
then "yup"
else "nope"</lang>
 
 
 
=={{header|ColdFusion}}==
Line 856 ⟶ 882:
===(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.
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)
Line 1,030 ⟶ 1,057:
io.writeln( 'a is neither 1 nor 3' )
}</lang>
 
===Switch Case===
<lang java>a = 3
Line 1,105 ⟶ 1,133:
=={{header|Efene}}==
 
theThe expressions can contain parenthesis or not, here both options are shown.
sinceSince 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>
Line 1,195 ⟶ 1,222:
=={{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===
Line 1,209 ⟶ 1,241:
===if===
 
if expressions match against guards only, without pattern matching. Guards must evaluate to true or false so true is the catch-all clause.
Guards must evaluate to true or false so true is the catch-all clause.
 
<lang erlang>{N,M} = X,
Line 1,227 ⟶ 1,260:
 
=={{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.
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 ⟶ 1,954:
show vowel? "e
show vowel? "x</lang>
{{out}}
Output is:
<lang logo>true
false</lang>
Line 3,607 ⟶ 3,643:
(- 1 2)))
(newline)</lang>
{{out}}
Output:
<langpre>no
#<unspecified></langpre>
 
===Derived===
====cond====
Line 3,623 ⟶ 3,660:
(else "equal")))
(newline)</lang>
{{out}}
Output:
<langpre>less
equal</langpre>
 
====case====
<lang>(case <key> <clause1> <clause2> ...)</lang>
Line 3,640 ⟶ 3,678:
(else "consonant")))
(newline)</lang>
{{out}}
Output:
<langpre>composite
consonant</langpre>
 
=={{header|Seed7}}==
===if-then-else===
There can be single or multiple statements. An if-statement can have multiple elsif parts.
An if-statement can have multiple elsif parts.
<lang seed7>if condition then
statement
Line 4,008 ⟶ 4,047:
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:
For instance:
 
<lang txr>@(all)
Line 4,019 ⟶ 4,059:
@(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 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
Anonymous user