Conditional structures

From Rosetta Code
Task
Conditional structures
You are encouraged to solve this task according to the task description, using any language you may know.
Control Structures

These are examples of control structures. You may also be interested in:

Here, we document the conditional structures offered by different programming languages. Common conditional structures are if-then-else and switch.

ActionScript

See JavaScript

Ada

if-then-else

<lang ada>type Restricted is range 1..10; My_Var : Restricted;

if My_Var = 5 then

 -- do something

elsif My_Var > 5 then

 -- do something

else

 -- do something

end if;</lang>

case

<lang ada>type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday); Today : Days;

case Today in

 when Saturday | Sunday =>
    null;
 when Monday =>
    Compute_Starting_Balance;
 when Friday =>
    Compute_Ending_Balance;
 when Others =>
    Accumulate_Sales;

end case;</lang>

select

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

Conditional Accept

<lang ada>select

  accept first_entry;
  -- do something
  or accept second_entry;
  -- do something
  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. <lang ada>select

 My_Task.Start;

or

 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.

ALGOL 68

See Conditional Structures/Ada

AmigaE

IF-THEN-ELSE <lang amigae>IF condition

 -> if condition is true...

ELSEIF condition2

 -> else if condition2 is true...

ELSE

 -> if all other conditions are not true...

ENDIF</lang>

or on one single line:

<lang amigae>IF condition THEN statement</lang>

Ternary IF THEN ELSE

The IF-THEN-ELSE can be used like ternary operator (?: in C) <lang amigae>DEF c c := IF condition THEN 78 ELSE 19</lang>

SELECT-CASE

<lang amigae>SELECT var

 CASE n1
   -> code
 CASE n2
   -> code
 DEFAULT
   -> no one of the previous case...

ENDSELECT</lang>

Another version allows for ranges:

<lang amigae>SELECT max_possible_value OF var

 CASE n1
   -> code
 CASE n2 TO n3, n4
   -> more
 CASE n5 TO n6, n7 TO n8
   -> more...
 DEFAULT
   -> none of previous ones

ENDSELECT</lang>

The biggest among n1, n2 and so on, must be not bigger than max_possible_value.

AppleScript

if-then-else

<lang applescript>if myVar is "ok" then return true

set i to 0 if i is 0 then

      return "zero"

else if i mod 2 is 0 then

      return "even"

else

      return "odd"

end if</lang>

AutoHotkey

if, else if, else
ternary if
while (looping if) <lang AutoHotkey>; if x = 1 If x

 MsgBox, x is %x%

Else If x > 1

 MsgBox, x is %x%

Else

 MsgBox, x is %x%
ternary if

x = 2 y = 1 var := x > y ? 2 : 3 MsgBox, % var

while

While (A_Index < 3) {

 MsgBox, %A_Index% is less than 3

}</lang>

AWK

Conditionals in awk are modelled after C: <lang awk>if(i<0) i=0; else i=42</lang> including the ternary conditional <lang awk>i=(i<0? 0: 42)</lang>

BASIC

if-then-else

Works with: QuickBasic version 4.5
Works with: FreeBASIC version 0.20.0

Single line IF does not require END IF

<lang qbasic>IF x = 0 THEN doSomething IF x < 0 THEN doSomething ELSE doOtherThing</lang>

Multi-line IF:

<lang qbasic>IF x > 0 AND x < 10 THEN

  'do stuff

ELSE IF x = 0 THEN

  'do other stuff

ELSE

  'do more stuff

END IF</lang>

Like in C, any non-zero value is interpreted as True:

<lang qbasic>IF aNumber THEN

  'the number is not 0

ELSE

  'the number is 0

END IF</lang>

select case

Works with: QuickBasic version 4.5
Works with: FreeBASIC version 0.20.0

The condition in each case branch can be one or more constants or variables, a range or an expression.

<lang qbasic>SELECT CASE expression CASE 1

  'do stuff

CASE 2, 3

  'do other stuff

CASE 3.1 TO 9.9

  'do this

CASE IS >= 10

  'do that

CASE ELSE

  'default case

END SELECT</lang>

Computed ON-GOTO

Older line-numbered BASICs had a mechanism for vectoring execution based on the contents of a numeric variable (a low-budget case statement).

ON V GOTO 120,150,150,170

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.

<lang befunge>v > "X",@ non-zero > & |

   > "0",@ zero</lang>

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

<lang befunge>& #v_ "0",@ zero

  >  "X",@ non-zero</lang>

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:

<lang bf>[.]</lang>

The . instruction will be skipped, while the following sequence

<lang bf>+[.]</lang>

will result in an infinite loop. Finally, in the following sequence

<lang bf>+[.-]</lang>

The . instruction will be executed once.

C

See Conditional Structures/C

C++

Run-Time Control Structures

See C

Compile-Time Control Structures

Preprocessor Techniques

See C

Template metaprogramming

Selecting a type depending on a compile time condition

<lang cpp>template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;

template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType> {

 typedef ThenType type;

};

template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType> {

 typedef ElseType type;

};

// example usage: select type based on size ifthenelse<INT_MAX == 32767, // 16 bit int?

          long int,         // in that case, we'll need a long int
          int>              // otherwise an int will do
 ::type myvar;              // define variable myvar with that type</lang>

Clean

if

There are no then or else keyword in Clean. The second argument of if 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

   | x == 42   = True
   | otherwise = False

case 6 * 7 of

   n | n < 0 -> "Not even close"
   42        -> "Correct"
   // no default, could result in a run-time error</lang>

Clojure

if-then-else

<lang lisp> (if (= 1 1) :yes :no) ; returns :yes

(if (= 1 2) :yes :no) ; returns :no

(if (= 1 2) :yes) ; returns nil </lang>

when

Similar to if, but body in an implicit do block allowing multiple statements. No facility for providing an else. <lang lisp> (when x

 (print "hello")
 (println " world")
 5) ; when x is logical true, prints "hello world" and returns 5; otherwise does nothing, returns nil

</lang>

case

<lang lisp> (case 2

 0 (println "0")
 1 (println "1")
 2 (println "2")) ; prints 2.</lang>

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. <lang lisp> (cond

 (= 1 2) :no) ; returns nil

(cond

 (= 1 2) :no
 (= 1 1) :yes) ; returns :yes

</lang> Since non-nil objects are logical true, by convention the keyword :else is used to yield a default result. <lang lisp> (cond

 (= 1 2) :no
 :else :yes) ; returns :yes

</lang>

condp

Similar to cond, but useful when each test differs by only one variant. <lang lisp> (condp < 3

 4 :a  ; cond equivalent would be (< 3 4) :a
 3 :b
 2 :c
 1 :d) ; returns :c

</lang> Optionally takes a final arg to be used as the default result if none of the tests match. <lang lisp> (condp < 3

 4 :a
 3 :b
 :no-match) ; returns :no-match

</lang>

COBOL

if-then-else

<lang cobol>if condition-1

   imperative-statement-1

else

   imperative-statement-2

end-if

if condition-1

   if condition-a
       imperative-statement-1a
   else
       imperative-statement-1
   end-if

else

   if condition-a
       imperative-statement-2a
   else
       imperative-statement-2
   end-if

end-if</lang>

evaluate

<lang cobol>evaluate identifier-1 when 'good'

   good-imperative-statement

when 'bad'

   bad-imperative-statement

when 'ugly' when 'awful'

   ugly-or-awful-imperative-statement

when other

   default-imperative-statement

end-evaluate

evaluate true when condition-1

   condition-1-imperative-statement

when condition-2

   condition-2-imperative-statement

when condition-3

   condition-3-imperative-statement

when other

   default-condition-imperative-statement

end-evaluate

evaluate identifier-1 also identifier-2 when 10 also 20

  one-is-10-and-two-is-20-imperative-statement

when 11 also 30

  one-is-11-and-two-is-30-imperative-statement

when 20 also any

  one-is-20-and-two-is-anything-imperative-statement

when other

  default-imperative-statement

end-evaluate</lang>

ColdFusion

if-elseif-else

Compiler: ColdFusion any version <lang cfm><cfif x eq 3>

do something

<cfelseif x eq 4>

do something else

<cfelse>

do something else

</cfif></lang>

switch

Compiler: ColdFusion any version <lang cfm><cfswitch expression="#x#">

<cfcase value="1">
 do something
</cfcase>
<cfcase value="2">
 do something
</cfcase>
<cfdefaultcase>
 do something
</cfdefaultcase>

</cfswitch></lang>

Common Lisp

There are 2 main conditional operators in common lisp, (if ...) and (cond ...).

(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.

<lang lisp>(if (= val 42)

   "That is the answer to life, the universe and everything"
   "Try again") ; the else clause here is optional</lang>

when and unless

Common Lisp also includes (when condition form*) and (unless condition form*) which are equivalent, respectively, to (if condition (progn form*)) and (if (not condition) (progn form*)).

It is unidiomatic to use if without an else branch for side effects; when should be used instead.

(cond (pred1 form1) [... (predN formN)])

The (cond ...) construct acts as both an if..elseif...elseif...else operator and a switch, returning the result of the form associated with the first non-nil predicate.

<lang lisp>(cond ((= val 1) (print "no"))

     ((and (> val 3) (< val 6)) (print "yes"))
     ((> val 99)                (print "too far"))
     (T                         (print "no way, man!")))</lang>

C#

if-elseif-else

<lang csharp>if (condition) {

  // Some Task

}

if (condition) {

 // Some Task

} else if (condition2) {

 // Some Task

} else {

 // Some Task

}</lang>

Ternary

<lang csharp>// if condition is true var will be set to 1, else false. int var = condition ? 1 : 2;</lang>

switch

<lang csharp>switch (value) {

  case 1:
         // Some task
         break;  // Breaks are required in C#.
  case 2:
  case 3:
        // Some task
        break;
  default: // If no other case is matched.
        // Some task
        break;

}</lang>

If fall through algorithms are required use the goto keyword.

<lang csharp>switch (value) {

  case 1:
         // Some task
         goto case 2; // will cause the code indicated in case 2 to be executed.
  case 2:
         // Some task
         break;
  case 3:
        // Some task
        break;
  default: // If no other case is matched.
        // Some task
        break;

}</lang>

D

See C, sans the preprocessor.

Compile-time check: <lang d>const i = 5; static if (i == 7) { ... } else { ... }</lang>

Compile-time type check: <lang d> auto i = 5; // is(T: U) tests if T is implicitly castable to U. // typeof(var) is the type of the variable. // also: is(T==U) checks if T is U. static if (is(typeof(i) : int)) {

 ...

} else {

 ...

}</lang>

Delphi

See Pascal

E

if-then-else

<lang e>if (okay) {

   println("okay")

} else if (!okay) {

   println("not okay")

} else {

   println("not my day")

}</lang>

The pick/2 message of booleans provides a value-based conditional:

<lang e>println(okay.pick("okay", "not okay"))</lang>

It can therefore be used to construct a Smalltalk-style conditional:

<lang e>okay.pick(fn {

   println("okay")

}, fn {

   println("not okay")

})()</lang>

All of the above conditionals are expressions and have a usable return value.

switch

E's "switch" allows pattern matching.

<lang e>def expression := ["+", [1, 2]]

def value := switch (expression) {

   match [`+`, [a, b]] { a + b }
   match [`*`, [a, b]] { a * b }
   match [op, _] { throw(`unknown operator: $op`) }

}</lang>

Efene

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

if-elseif-else

<lang efene>

   # with parentheses
   # this will crash if condition1 is not true
   # always a condition must match
   if (condition1) {
       # do something if condition1 is true
   }
   if (condition1) {
       # do something if condition1 is true
   } else {
       # do something if condition1 is false
   }
   if (condition1) {
       # do something if condition1 is true
   } (condition2) {
       # do something if condition2 is true
   } else {
       # do something if condition1 is false
   }
   # without parentheses
   # this will crash if condition1 is not true
   # always a condition must match
   if condition1 {
       # do something if condition1 is true
   }
   if condition1 {
       # do something if condition1 is true
   } else {
       # do something if condition1 is false
   }
   if condition1 {
       # do something if condition1 is true
   } condition2 {
       # do something if condition2 is true
   } else {
       # do something if condition1 is false
   }

</lang>

switch

<lang efene> # with parenthesis

   switch (Value) {
       (1) {
           # do something if value is 1
       } (2) {
           # do something if value is 2
       } (3) {
           # do something if value is 3
       }
   } else {
       # do something if no other case matched
   }
   # without parenthesis
   switch Value {
       1 {
           # do something if value is 1
       } 2 {
           # do something if value is 2
       } 3 {
           # do something if value is 3
       }
   } else {
       # do something if no other case matched
   }</lang>

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.

?

? is for when you don't need branching, but only need to select between two different values. <lang factor> t 1 2 ? ! returns 1 </lang>

if

<lang factor>t [ 1 ] [ 2 ] if ! returns 1</lang>

cond

<lang factor>{ { [ t ] [ 1 ] } { [ f ] [ 2 ] } } cond ! returns 1</lang>

case

<lang factor>t { { t [ 1 ] } { f [ 2 ] } } case ! returns 1</lang>

when

<lang factor>t [ "1" print ] when ! prints 1</lang>

unless

<lang factor>f [ "1" print ] unless ! prints 1</lang>

FALSE

<lang false>condition[body]?</lang> Because there is no "else", you need to stash the condition if you want the same effect: <lang false>$[\true\]?~[false]?</lang> or <lang false>$[%true0~]?~[false]?</lang>

Forth

IF-ELSE

<lang forth>( condition ) IF ( true statements ) THEN ( condition ) IF ( true statements ) ELSE ( false statements ) THEN</lang> example: <lang forth>10 < IF ." Less than 10" ELSE ." Greater than or equal to 10" THEN</lang>

CASE-OF

<lang forth>( n -- ) CASE ( integer ) OF ( statements ) ENDOF ( integer ) OF ( statements ) ENDOF ( default instructions ) ENDCASE</lang> example: a simple CASE selection <lang forth>: test-case ( n -- )

  CASE
    0 OF ." Zero!" ENDOF
    1 OF ." One!"  ENDOF
    ." Some other number!"
  ENDCASE ;</lang>

Execution vector

To obtain the efficiency of a C switch statement for enumerations, one needs to construct one's own execution vector. <lang forth>: switch

 CREATE ( default-xt [count-xts] count -- ) DUP , 0 DO , LOOP ,
 DOES> ( u -- ) TUCK @ MIN 1+ CELLS + @ EXECUTE ;
 :NONAME ." Out of range!" ;
 :NONAME ." nine" ;
 :NONAME ." eight" ;
 :NONAME ." seven" ;
 :NONAME ." six" ;
 :NONAME ." five" ;
 :NONAME ." four" ;
 :NONAME ." three" ;
 :NONAME ." two" ;
 :NONAME ." one" ;
 :NONAME ." zero" ;

10 switch digit

8 digit   \ eight

34 digit \ Out of range!</lang>

Fortran

In ISO Fortran 90 and later, there are three conditional structures. There are also a number of other *unstructured* conditional statements, all of which are old and many of which are marked as "deprecated" in modern Fortran standards. These examples will, as requested, only cover conditional *structures*:

IF-THEN-ELSE

ANSI FORTRAN 77 or later has an IF-THEN-ELSE structure: <lang fortran>if ( a .gt. 20.0 ) then

  q = q + a**2

else if ( a .ge. 0.0 ) then

  q = q + 2*a**3

else

  q = q - a

end if</lang>

SELECT-CASE

ISO Fortran 90 or later has a SELECT-CASE structure: <lang fortran>select case (i)

  case (21:)      ! matches all integers greater than 20
     q = q + i**2
  case (0:20)     ! matches all integers between 0 and 20 (inclusive)
     q = q + 2*i**3
  case default    ! matches all other integers (negative in this particular case)
     q = q - I

end select</lang>

WHERE-ELSEWHERE

ISO Fortran 90 and later has a concurrent, array-expression-based WHERE-ELSEWHERE structure. The logical expressions in WHERE and ELSEWHERE clauses must be array-values. All statements inside the structure blocks must be array-valued. Furthermore, all array-valued expressions and statements must have the same "shape". That is, they must have the same number of dimensions, and each expression/statement must have the same sizes in corresponding dimensions as each other expression/statement. For each block, wherever the logical expression is true, the corresponding elements of the array expressions/statements are evaluated/executed. <lang fortran>! diffusion grid time step where (edge_type(1:n,1:m) == center)

  anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5

elsewhere (edge_type(1:n,1:m) == left)

  anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5

elsewhere (edge_type(1:n,1:m) == right)

  anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5

elsewhere (edge_type(1:n,1:m) == top)

  anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + 2*a(1:n,2:m+1)) / 5

elsewhere (edge_type(1:n,1:m) == bottom)

  anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + 2*a(1:n,0:m-1)) / 5

elsewhere (edge_type(1:n,1:m) == left_top)

  anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + 2*a(1:n,2:m+1)) / 5

elsewhere (edge_type(1:n,1:m) == right_top)

  anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + 2*a(1:n,2:m+1)) / 5

elsewhere (edge_type(1:n,1:m) == left_bottom)

  anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + 2*a(1:n,0:m-1)) / 5

elsewhere (edge_type(1:n,1:m) == right_bottom)

  anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + 2*a(1:n,0:m-1)) / 5

elsewhere  ! sink/source, does not change

  anew(1:n,1:m) = a(1:n,1:m)

end where</lang>

Haskell

if-then-else

<lang haskell>fac x = if x==0 then

          1
          else x * fac (x - 1)</lang>

Guards

<lang haskell>fac x | x==0 = 1

     | x>0 = x * fac (x-1)</lang>

Pattern matching

<lang haskell>fac 0 = 1 fac x = x * fac (x-1)</lang>

case statement

<lang haskell>fac x = case x of 0 -> 1

                 _ -> x * fac (x-1)</lang>

IDL

if-else

Basic if/then:

<lang idl>if a eq 5 then print, "a equals five" [else print, "a is something else"]</lang>

Any one statement (like these print statements) can always be expanded into a {begin ... end} pair with any amount of code in between. Thus the above will expand like this:

<lang idl>if a eq 5 then begin

 ... some code here ...

endif [else begin

 ... some other code here ...

endelse]</lang>

case

<lang idl>case <expression> of

 (choice-1): <command-1>
 [(choice-2): <command-2> [...]]
 [else: <command-else>]

endcase</lang>

(Or replace any of the commands with {begin..end} pairs)

switch

<lang idl>switch <expression> of

 (choice-1): <command-1>
 [(choice-2): <command-2> [...]]
 [else: <command-else>]

endswitch</lang>

The switch will execute all commands starting with the matching result, while the case will only execute the matching one.

on_error

<lang idl>on_error label</lang>

Will resume execution at label when an error is encountered. on_ioerror is similar but for IO errors.

J

See Conditional Structures/J

Java

if-then-else

<lang java>if(s.equals("Hello World")) {

   foo();

} else if(s.equals("Bye World"))

   bar();//{}'s optional for one-liners

else {

   deusEx();

}</lang> Java also supports short-circuit evaluation. So in a conditional like this: <lang java>if(obj != null && obj.foo()){

  aMethod();

}</lang> obj.foo() will not be executed if obj != null returns false. It is possible to have conditionals without short circuit evaluation using the & and | operators (from Bitwise operations). So in this conditional: <lang java>if(obj != null & obj.foo()){

  aMethod();

}</lang> You will get a null pointer exception if obj is null.

ternary

<lang java>s.equals("Hello World") ? foo() : bar();</lang>

switch

This structure will only work if the code being switched on evaluates to an integer or character. There is no switching on Objects or floating-point types in Java. <lang java>switch(c) { case 'a':

  foo();
  break;

case 'b':

  bar();

default:

  foobar();

}</lang> This particular example can show the "fallthrough" behavior of a switch statement. If c is the character b, then bar() and foobar() will both be called. If c is the character a, only foo() will be called because of the break statement at the end of that case.

Also, the switch statement can be easily translated into an if-else if-else statement. The example above is equivalent to: <lang java>if(c == 'a'){

  foo();

}else if(c == 'b'){

  bar();
  foobar();

}else{

  foobar();

}</lang> Cases without breaks at the end require duplication of code for all cases underneath them until a break is found (like the else if block shown here).

JavaScript

if-then-else

<lang javascript>if( s == "Hello World" ) {

   foo();

} else if( s == "Bye World" ) {

   bar();

} else {

   deusEx();

}</lang>

switch

<lang javascript>switch(object) {

   case 1:
       one();
       break;
   case 2:
   case 3:
   case 4:
       twoThreeOrFour();
       break;
   case 5:
       five();
       break;
   default:
       everythingElse();

}</lang>

conditional (ternary) operator (?:)

<lang javascript>var num = window.obj ? obj.getNumber() : null;</lang>

Lisaac

Works with: Lisaac version 0.13.1

if-then-else

<lang Lisaac>+ n : INTEGER;

n := 3;

(n = 2).if {

 IO.put_string "n is 2\n";

}.elseif {n = 3} then {

 IO.put_string "n is 3\n";

}.elseif {n = 4} then {

 IO.put_string "n is 4\n";

} else {

 IO.put_string "n is none of the above\n";

};</lang> <lang Lisaac>(n = 2).if_true { "n is 2\n".print; }; (n = 2).if_false { "n is not 2\n".print; };</lang>

when

<lang Lisaac>+ n : INTEGER;

n := 3; n .when 2 then {

 "n is 2\n".print;

} .when 3 then {

 "n is 3\n".print;

} .when 4 then {

 "n is 4\n".print;

};</lang> There is no "else" or "otherwise" method. If the values of the when-methods are overlapped, the related blocks will be evaluated ... they are not mutually exclusive.

<lang logo>if :x < 0 [make "x 0 - :x]

ifelse emptyp :list [print [empty]] [print :list]</lang> UCBLogo and its descendants have also case: <lang logo>to vowel? :letter output case :letter [ [[a e i o u] "true] [else "false] ] end show vowel? "e show vowel? "x</lang> Output is: <lang logo>true false</lang> Logo also provides TEST which is local to a procedure: <lang logo>to mytest :arg1 :arg2 test :arg1 = :arg2 iftrue [print [Arguments are equal]] iffalse [print [Arguments are not equal]] end</lang>

LSE64

The simple conditionals take single words rather than blocks of statements, as in most other languages. <lang lse64>t : " true" ,t f : " false" ,t true if t false ifnot f true ifelse t f</lang>

Cascading conditionals are constructed using duplicate definitions and "then", yielding a syntax reminiscent of functional language Pattern Matching. <lang lse64>onetwo : drop " Neither one nor two" ,t # default declared first onetwo : dup 2 = then " Two" ,t onetwo : dup 1 = then " One" ,t</lang>

Short-circuit operators "&&" and "||" are used for complex conditionals. <lang lse64>dup 0 = || ,t # avoid printing a null string</lang>

lua

<lang lua> --if-then-elseif-then-else if(a) then b() elseif(c) then d() else e() end

for var = start, end, step do something() end

for var, var2, etc in iteratorfunction do something() end

while somethingistrue() do something() end

repeat something() until somethingistrue()

cases = { key1 = dothis, key2 = dothat, key3 = dotheother }

cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively</lang>

Make

An if condition using pure make (no gmake extensions) <lang make># make -f do.mk C=mycond if C=0

if:

  -@expr $(C) >/dev/null && make -f do.mk true; exit 0
  -@expr $(C) >/dev/null || make -f do.mk false; exit 0

true:

  @echo "was true."

false:

  @echo "was false."</lang>

Using it <lang make>make -f do.mk if C=0 > was false.

make -f do.mk if C=1 > was true.</lang>

With out using recursion but letting make continue with non-failed targets even when some of the targets failed (-k) <lang make>C=0

if: true false

true:

  @expr $(C) >/dev/null && exit 0 || exit 1
  @echo "was true."

false:

  @expr $(C) >/dev/null && exit 1 || exit 0
  @echo "was false."</lang>

Invoking it. Note the use of -k which allows make to evaluate subsequent targets even when a previous non-related target failed. <lang make>|make -f do.mk -s -k C=1 was true.

      • Error code 1

|make -f do.mk -s -k C=0

      • Error code 1

was false.</lang>

Using gmake

<lang make>A= B=

ifeq "$(A)" "1"

      B=true

else

      B=false

endif

do:

      @echo $(A) ..  $(B)</lang>

Using it <lang make>|gmake -f if.mk A=1 1 .. true |gmake -f if.mk A=0 0 .. false</lang>

MAXScript

if

<lang maxscript>if x == 1 then (

    print "one"

) else if x == 2 then (

   print "two"

) else (

   print "Neither one or two"

)</lang>

case

Form one <lang maxscript>case x of (

   1:       (print "one")
   2:       (print "two")
   default: (print "Neither one or two")

)</lang> Form two <lang maxscript>case of (

   (x == 1): (print "one")
   (x == 2): (print "two")
   default:  (print "Neither one or two")

)</lang>

Metafont

<lang metafont>if conditionA:

 % do something

elseif conditionB:

 % do something

% more elseif, if needed... else:

 % do this

fi;</lang>

The particularity of if construct in Metafont is that it can be part of an expression, and the "do something" does not need to fit into the syntactic structure. E.g. we can write something like

<lang metafont>b := if a > 5: 3 + else: 2 - fi c;</lang>

Alone, the code 3 + does not mean anything; but once the condition is evaluated, the whole expression must become "correct"; e.g. if a > 5, the expression will be b := 3 + c;.

There are no other kind of conditional structures, but the great flexibility of Metafont allows for sure to create "new syntaxes" similar to switches or whatever needed.

Modula-3

if-then-else

<lang modula3>IF Foo = TRUE THEN

 Bar();

ELSE

 Baz();

END;</lang>

<lang modula3>IF Foo = "foo" THEN

 Bar();

ELSIF Foo = "bar" THEN

 Baz();

ELSIF Foo = "foobar" THEN

 Quux();

ELSE

 Zeepf();

END;</lang>

Case

<lang modula3>CASE Foo OF | 1 => IO.Put("One\n"); | 2 => IO.Put("Two\n"); | 3 => IO.Put("Three\n"); ELSE

 IO.Put("Something\n");

END;</lang>

Type-case

TYPECASE is used on reference types to perform different operations, depending on what it is a reference to. <lang modula3>TYPECASE ref OF | NULL => IO.Put("Null\n"); | CHAR => IO.Put("Char\n"); | INTEGER => IO.Put("Integer\n"); ELSE

 IO.Put("Something\n");

END;</lang>

newLISP

if

Interpreter: newLISP v.9.0 <lang lisp>(set 'x 1) (if (= x 1) (println "is 1"))</lang> A third expression can be used as an else. <lang lisp>(set 'x 0) (if (= x 1) (println "is 1") (println "not 1"))</lang>

Object Pascal

See Pascal

Objective-C

See also C

One difference: the preprocessor has been extended with an #import directive which does the same thing as #include with "include guards".

OCaml

if-then-else

<lang ocaml>let condition = true

if condition then

 1 (* evaluate something *)

else

 2 (* evaluate something *)</lang>

If-then-else has higher precedence than ; (the semicolon), so if you want to have multiple statements with side effects inside an "if", you have to enclose it with begin...end or with parentheses:

<lang ocaml>if condition then begin

 (); (* evaluate things for side effects *)
 5

end else begin

 (); (* evaluate things for side effects *)
 42

end</lang>

match-with

<lang ocaml>match expression with | 0 -> () (* evaluate something *) | 1 -> () (* evaluate something *) | n when n mod 2 = 0 -> () (* evaluate something *) | _ -> () (* evaluate something *)</lang>

The first | is optional, and usually omitted.

Match is especially useful for Pattern Matching on various types of data structures.

Nested match's need to be surrounded by begin-end or parentheses, or else it won't know where it ends.

Octave

if-then-elseif-else <lang octave>if (condition)

 % body

endif

if (condition)

 % body

else

 % otherwise body

endif

if (condition1)

 % body

elseif (condition2)

 % body 2

else

 % otherwise body

endif</lang>

switch <lang octave>switch( expression )

 case label1
    % code for label1
 case label2
    % code for label2
 otherwise
    % none of the previous

endswitch</lang>

Labels can be numeric or string, or cells to group several possibilities:

<lang octave>switch ( x )

 case 1
   disp("it is 1");
 case { 5,6,7 }
   disp("it is 5, or 6 or 7");
 otherwise
   disp("unknown!");

endswitch</lang>

Oz

if-then-else

<lang oz>proc {PrintParity X}

  if {IsEven X} then
     {Show even}
  elseif {IsOdd X} then
     {Show odd}
  else
     {Show 'should not happen'}
  end

end</lang>

if-then-else as a ternary operator

<lang oz>fun {Max X Y}

  if X > Y then X else Y end

end</lang>

case statement

<lang oz>fun {Fac X}

  case X of 0 then 1
  [] _ then X * {Fac X-1}
  end

end</lang>

Pascal

if-then-else

<lang pascal>IF condition1 THEN

 procedure1

ELSE

 procedure3;

IF condition1 THEN

 BEGIN
   procedure1;
   procedure2;
 END

ELSE

 procedure3;

IF condition 1 THEN

 BEGIN
   procedure1;
   procedure2;
 END

ELSE

 BEGIN
   procedure3;
   procedure4;
 END;</lang>

case

Works with: Turbo Pascal version 7.0

In Pascal there's no fall-through, that is, if execution reaches the end of any case, execution continues after the end of the case statement, not in the code for the next case. Pascal implements the ELSE operator for all cases that do not match any of the given cases. Case selectors must be an ordinal type. This might seem to be a restriction, but with a little thought, just about anything can be resolved to an ordinal type with a bit of imagination. Additionally, each item in the case may consist of more then one item.

<lang pascal>case i of

 1,4,9: { executed if i is 1, 4 or 9 }
   DoSomething;
 11, 13 .. 17: { executed if i is 11, 13, 14, 15, 16 or 17 }
   DoSomethingElse;
 42: { executed only if i is 42 }
   DoSomeOtherThing;
 else
   DoYetAnotherThing;

end;</lang>

Given the variable "X" as a char the following is valid:

<lang pascal>Case X of

  'A'           : statement ;
  'B'           : statement ;     
  in ['C'..'W'] : statement ;      

else

  Statement ;

end;</lang>

Perl

Works with: Perl version 5

if/else

if ($expression) {
    do_something;
};

# postfix conditional
do_something if $expression;

if ($expression) {
    do_something;
} else {
    do_fallback;
};

if ($expression1) {
    do_something;
} elsif ($expression2) {
    do_something_different;
} else {
    do_fallback;
};

unless

unless behaves like if, only logically negated. You can use it wherever you can use if. An unless block can have elsif and else blocks, but there is no elsunless.

ternary operator

This is the same as the if/else example, only less readable. But it returns the value of its executed branch.

$expression ? do_something : do_fallback;

logical operators

$condition and do_something is equivalent to $condition ? do_something : $condition.

$condition or do_something is equivalent to $condition ? $condition : do_something.

&& and || have the same semantics as and and or, respectively, but their precedence is much higher, making them better for conditional expressions than control flow.

switch

Works with: Perl version 5.10

<lang perl>use feature "switch"; given ($input) {

   when (0)          { print 'input == 0'; }
   when ('coffee')   { print 'input equal coffee'; }
   when ([1..9])     { print 'input between 1 and 9'; }
   when (/rats/)     { print 'input matches rats'; }
   default           { do_fallback; }

}</lang>

Perl 6

if, else, elsif, unless, and given work much as they do in Perl 5, with the following differences:

  • All the parentheses are now optional.
  • unless no longer permits elsif or else blocks.
  • If the block of an if, elsif, or unless has a nonzero arity, the value of the conditional expression is used as an argument to the block: <lang perl6>if won() -> $prize { say "You won $prize."; }</lang> If an else block has a nonzero arity, it recieves the value of the condition tested by the last if or elsif.

when blocks are now allowed "in any block that sets $_, including a for loop (assuming one of its loop variables is bound to $_) or the body of a method (if you have declared the invocant as $_)." See Synopsis 4.

The ternary operator now looks like this:

<lang perl6>$expression ?? do_something !! do_fallback</lang>

and, or, &&, and || work as in Perl 5.

PHP

if

Interpreter: PHP 3.x & 4.x & 5.x

<lang php><?php

$foo = 3;

if ($foo == 2)

 //do something

if ($foo == 3)

 //do something

else

 //do something else

if ($foo != 0) {

 //do something

}

else {

 //do another thing

}

?></lang>

switch

Interpreter: PHP 3.x & 4.x & 5.x

<lang php><?php

switch ($i) {

 case "apple":
     echo "i is apple";
     break;
 case "bar":
     echo "i is bar";
     break;
 case "cake":
     echo "i is cake";
     break;

}

?></lang>

See Also

PicoLisp

Two-way conditions

<lang PicoLisp>(if (condition) # If the condition evaluates to non-NIL

  (then-do-this)                # Then execute the following expression
  (else-do-that)                # Else execute all other expressions
  (and-more) )

(ifn (condition) # If the condition evaluates to NIL

  (then-do-this)                # Then execute the following expression
  (else-do-that)                # Else execute all other expressions
  (and-more) )</lang>

One-way conditions <lang PicoLisp>(when (condition) # If the condition evaluates to non-NIL

  (then-do-this)                # Then execute tall following expressions
  (and-more) )

(unless (condition) # If the condition evaluates to NIL

  (then-do-this)                # Then execute all following expressions
  (and-more) )</lang>

Four-way condition

<lang PicoLisp>(if2 (condition1) (condition2) # If both conditions evaluate to non-NIL

  (expression-both)             # Then execute this expression
  (expression-first)            # Otherwise this for the first
  (expression-second)           # or this the second condition.
  (expression-none)             # If both are NIL, all following expressions
  (and-more) )</lang>

Multiple conditions

<lang PicoLisp>(cond

  ((condition1)                 # If this condition evaluates to non-NIL
     (expression 1)             # Execute these expression(s)
     (more 1) )
  ((condition2)                 # Otherwise, if this evaluates to non-NIL
     (expression 2)             # Execute these expression(s)
     (more 2) )
  (T                            # If none evaluated to non-NIL
     (expression 1)             # Execute these expression(s)
     (more 1) )
  

(nond

  ((condition1)                 # If this condition evaluates to NIL
     (expression 1)             # Execute these expression(s)
     (more 1) )
  ((condition2)                 # Otherwise, if this evaluates to NIL
     (expression 2)             # Execute these expression(s)
     (more 2) )
  (NIL                          # If none evaluated to NIL
     (expression 1)             # Execute these expression(s)
     (more 1) )</lang>

Selection

<lang PicoLisp>(case (expression) # Evaluate the expression

  (value1                       # If it is equal to, or member of, 'value1'
     (do-this1)                 # Execute these expression(s)
     (do-that1) )
  (value2                       # Else if it is equal to, or member of, 'value2
     (do-this2)                 # Execute these expression(s)
     (do-that2) )
  (T                            # Else execute final expression(s)
     (do-something-else) ) )</lang>

Pop11

The simplest conditional is:

<lang pop11>if condition then

   ;;; Action

endif;</lang>

Two way conditional looks like:

<lang pop11>if condition then

   ;;; Action1

else

   ;;; Alternative action

endif;</lang>

One can do multiway choice using elseif clause

<lang pop11>if condition1 then

  ;;; Action1

elseif condition2 then

  ;;; Action1

elseif condition2 then

  ;;; Action2

elseif condition3 then

  ;;; Action3

else

  ;;; Alternative action

endif;</lang>

Instead of if keyword one can use unless keyword.

<lang pop11>unless condition then /* Action */ endunless;</lang>

has the same meaning as

<lang pop11>if not(condition) then /* Action */ endif;</lang>

One can also use elseunless keword.

<lang pop11>if condition1 then

  ;;; Action1

elseunless condition2 then

  ;;; Action2

endif;

  ;;; Action2

endif;</lang>

has the same meaning as

<lang pop11>if condition1 then

  ;;; Action1

elseif not(condition2) then

  ;;; Action2

endif;</lang>

Note that conditional must end in matching keyword, if must be finished by endif, unless must be finished by endunless (in the middle one can mix elseif with elseunless.

Pop11 conditional is an expression:

<lang pop11>if x > 0 then 1 elseif x < 0 then -1 else 0 endif -> sign_x ;</lang>

assigns sign of x to sign_x.

Instead of multiway if one can use switchon construct (which is equivalent to a special case of if, but may be shorter).

<lang pop11>switchon(x)

   case .isstring  then printf('A1');
   notcase .isinteger then printf('A2');
   case = 2 orcase = 3 then printf('A3');
   case > 4 andcase < 15 then printf('A4');
   else printf('A5');

endswitchon;</lang>

There is also multiway goto statement and conditional control transfers, we explain them together with other control transfers and loops (in case of loop exit/continue statements).

Pop11 also has preprocessor allowing conditional compilation:

<lang pop11>#_IF condition1 /* Variant 1 */

  1. _ELSEIF condition2

/* Variant 2 */

  1. _ELSE

/* Variant 3 */

  1. _ENDIF</lang>

condition1 and condition2 are arbitrary Pop11 expressions (they have access to all previously compiled code).

Also note that Pop11 syntax is user extensible, so users may create their own conditional constructs.

PostScript

The "if" operator uses two items form the stack, a procedure and a boolean. It will execute the procedure if the boolean is true. It will not leave anything on the stack (but the procedure might):

<lang postscript>9 10 lt {(9 is less than 10) show} if</lang>

The "ifelse" operator expects two procedures and executes the one or the other depending on the value of the boolean. I.e. this:

<lang postscript>/a 5 lt {(yeah)} {(nope)} ifelse show</lang>

will render either the string "yeah" or "nope" depending on whether a is less than 5 or not.

PowerShell

If, ElseIf, Else

<lang powershell># standard if if (condition) {

   # ...

}

  1. if-then-else

if (condition) {

   # ...

} else {

   # ...

}

  1. if-then-elseif-else

if (condition) {

   # ...

} elseif (condition2) {

   # ...

} else {

   # ...

}</lang>

Switch

<lang powershell># standard switch switch ($var) {

   1 { "Value was 1" }
   2 { "Value was 2" }
   default { "Value was something else" }

}

  1. switch with wildcard matching

switch -Wildcard ($var) {

   "a*" { "Started with a" }
   "*x" { "Ended with x" }

}

  1. switch with regular expression matching

switch -Regex ($var) {

   "[aeiou]" { "Contained a consonant" }
   "(.)\1" { "Contained a character twice in a row" }

}

  1. switch allows for scriptblocks too

switch ($var) {

   { $_ % 2 -eq 0 } { "Number was even" }
   { $_ -gt 100 }   { "Number was greater than 100" }

}

  1. switch allows for handling a file

switch -Regex -File somefile.txt {

   "\d+" { "Line started with a number" }
   "\s+" { "Line started with whitespace" }

}</lang>

PureBasic

Works with: PureBasic version 4.41

If, Elseif, Else

<lang PureBasic>If a=0

 Debug "a=0"

ElseIf a>0

 Debug "a>0" 

Else

 Debug "a<0"

EndIf</lang>

Select

<lang PureBasic>Variable = 2

Select Variable

 Case 0
   Debug "Variable = 0"
   
 Case 10
   Debug "Variable = 10"
   
 Case 20 
   Debug "Variable = 20"
   
 Default
   Debug "Variable = something else..."

EndSelect</lang>

Python

if-then-else

if x == 0:
    foo()
elif x == 1:
    bar()
elif x == 2:
    baz()
else:
    boz()

ternary expressions

Interpreter: Python 2.5

 true_value if condition else false_value

Example: <lang python>secret='foo'

print 'got it' if secret=='foo' else 'try again'

'got it'</lang>

Note: this syntax is valid as an expression, the clauses cannot constain statements. The foregoing example is equivalent to:

<lang python>secret = 'foo'

result = 'got it' if secret=='foo' else 'try again'
print result

'got it'</lang>

Function dispatch dictionary

In some cases it's useful to associate functions with keys in a dictionary; and simply use this in lieu of long sequences of "if...elif...elif..." statements.

dispatcher = dict()
dispatcher[0]=foo  # Not foo(): we bind the dictionary entry to the function's object, 
                   # NOT to the results returned by an invocation of the function
dispatcher[1]=bar
dispatcher[2]=baz  # foo,bar, baz, and boz are defined functions.
# Then later
results = dispatcher.get(x, boz)()  # binding results to a name is optional
# or with no "default" case:
if x in dispatcher:
    results=dispatcher[x]()

This can be particularly handy when using currying techniques, or when lambda expressions or meta-function generators (factories) can be used in place of normal named functions.

In general a dispatch table or class/object abstraction (using dynamic method over-rides) is considered preferable to chains of if ... elif ... elif ... in Python programming.

R

if-else

<lang R>#Single line example

#x is assumed to be scalar
if(x < 3) message("x is less than 3") else if(x < 5) message("x is greater than or equal to 3 but less than 5") else message("x is greater than or equal to 5")
  1. Block example
if(x < 3)
{
   x <- 3
   warning("x has been increased to 3")
} else
{
   y <- x^2
}
  1. It is important that the else keyword appears on the same line as the closing '}' of the if block.</lang>

ifelse

<lang r>#ifelse is a vectorised version of the if/else flow controllers, similar to the C-style ternary operator.

x <- sample(1:10, 10)
ifelse(x > 5, x^2, 0)</lang>

switch

<lang r>#Character input

calories <- function(food) switch(food, apple=47, pizza=1500, stop("food not known"))
calories("apple")  #47
calories("banana") #throws an error
  1. Numeric input
alphabet <- function(number) switch(number, "a", "ab", "abc")
alphabet(3) # "abc"
alphabet(4) # NULL
  1. Note that no 'otherwise' option is allowed when the input is numeric.</lang>

Rhope

Works with: Rhope version alpha 1

if-then-else

<lang rhope>If[cond] |:

   Do Something[]
||:
   Do Something Else[]
|</lang>

Ruby

See Conditional Structures/Ruby

Scheme

Procedures can be categorised as primitive or derived. Derived procedures can be defined in terms of primitive procedures.

Primitive

if

<lang>(if <test> <consequent> <alternate>)</lang> <lang>(if <test> <consequent>)</lang> Example: <lang scheme>(display

 (if (> 1 2)
     "yes"
     "no"))

(newline) (display

 (if (> 1 2)
     (- 1 2)))

(newline)</lang> Output: <lang>no

  1. <unspecified></lang>

Derived

cond

<lang>(cond <clause1> <clause2> ...)</lang> Example: <lang scheme>(display

 (cond ((> 1 2) "greater")
       ((< 1 2) "less")))

(newline) (display

 (cond ((> 1 1) "greater")
       ((< 1 1) "less")
       (else "equal")))

(newline)</lang> Output: <lang>less equal</lang>

case

<lang>(case <key> <clause1> <clause2> ...)</lang> Example: <lang scheme>(display

 (case (* 2 3)
   ((2 3 5 7) "prime")
   ((1 4 6 8 9) "composite")))

(newline) (display

 (case (car (list c d))
   ((a e i o u) "vowel")
   ((w y) "semivowel")
   (else "consonant")))

(newline)</lang> Output: <lang>composite consonant</lang>

Slate

ifTrue/ifFalse

<lang slate>"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)"

balance > 0
    ifTrue: [inform: 'still sitting pretty!'.]
    ifFalse: [inform: 'No money till payday!'.].</lang>


caseOf:otherwise:

<lang slate>c@(Net URLPathEncoder traits) convert [ | byte1 byte2 byte3 digit1 digit2|

 [c in isAtEnd] whileFalse:
   [byte1: c in next.
    byte1 caseOf: {
      $+ -> [c out nextPut: $\s].
      $% -> [byte2: c in next. 
             byte3: c in next.
             digit1: (byte2 toDigit: 16).
             digit2: (byte3 toDigit: 16).
             digit1 isNil \/ [digit2 isNil] ifTrue: [error: 'Error reading hex sequence after %'].
             c out nextPut: (digit1 * 16 + digit2 as: c out elementType)].
    } otherwise: [c out nextPut: byte1].
    ].

].</lang>

whileTrue:/whileFalse:

<lang slate>[p isAtEnd] whileFalse: [p next evaluate]].</lang>


Smalltalk

The pattern for handling a multi-option switch is to create classes for the various options, and let Polymorphism take care of the decisions.

ifTrue/ifFalse

<lang smalltalk>"Conditionals in Smalltalk are really messages sent to Boolean objects"

balance > 0
    ifTrue: [Transcript cr; show: 'still sitting pretty!'.]
    ifFalse: [Transcript cr; show: 'No money till payday!'.].</lang>

You can also use them as the ternary operator

<lang smalltalk>abs := x > 0 ifTrue: [ x ] ifFalse: [ x negated ]</lang>


SNUSP

<lang snusp>$==?\==zero=====!/==#

   \==non zero==/</lang>

? is the only conditional operator. It skips one character if the current cell is zero.

! is an unconditional skip. !/ is the idiom for joining two lines of execution. ?! inverts the test.

\ and / redirect the flow of control. All the other characters besides $ and # are commentary.

SQL

Works with: MS SQL version 2005

Conditional Expression

<lang sql>case when a then b else c end

declare @n int set @n=124 print case when @n=123 then 'equal' else 'not equal' end

--If/ElseIf expression set @n=5 print case when @n=3 then 'Three' when @n=4 then 'Four' else 'Other' end</lang>

If/Else

<lang sql>declare @n int set @n=123 if @n=123

 BEGIN --begin/end needed if more than one statement inside
   print 'one two three'
 END

ELSE

 if @n=124 print 'one two four'
 else print 'other'</lang>

Tcl

if-then-else

<lang tcl>if {$foo == 3} {

   puts "foo is three"

} elseif {$foo == 4} {

   puts "foo is four"

} else {

   puts "foo is neither three nor four"

}</lang> or (using the ternary operator of expressions) <lang tcl>set result [expr { $foo == 3 ? "three" : "not three" }]</lang>

switch

<lang tcl>switch -- $foo {

   3 {puts "foo is three"}
   4 {puts "foo is four"}
   default {puts "foo is something else"}

}</lang> Note that the switch command can also use glob matching (like case in the Bourne Shell) or regular-expression matching.

Toka

ifTrue

( condition ) ( quote ) ifTrue

<lang toka>100 100 = [ ." True\n" ] ifTrue 100 200 = [ ." True\n" ] ifTrue</lang>

ifFalse

( condition ) ( quote ) ifFalse

<lang toka>100 100 = [ ." True\n" ] ifFalse 100 200 = [ ." True\n" ] ifFalse</lang>

ifTrueFalse

( condition ) ( true quote ) ( false quote ) ifTrueFalse

<lang toka>100 100 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse 100 200 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse</lang>


V

ifThenElse

<lang v>[true]

 ['is true' puts]
 ['is false' puts]

ifte

=is true</lang>

ifThen

<lang v>[true]

 ['is true' puts]

if =is true</lang>

When

<lang v>3 [

 [1 =] [1 *]
 [2 =] [10 *]
 [3 =] [100 *]
 [4 =] [1000 *]

] when

=300</lang>

Choice

<lang v>true

 1 2

choice

=1

false

 1 2

choice

=2</lang>

Visual Basic .NET

if-then-else

Basic <lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"

If a = b Then

 result = "passed"

Else

 result = "failed"

End If</lang>

Condensed <lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"

If a = b Then result = "passed" Else result = "failed"

If a = b Then

 result = "passed"

Else : result = "failed" End If

If a = b Then : result = "passed" Else

 result = "failed"

End If</lang>

if-then-elseif

<lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"

If a = b Then

 result = "passed"

ElseIf a <> b Then

 result = "failed"

Else

 result = "impossible"

End If</lang>

select-case-else

<lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"

Select Case a

 Case b
   result = "match"
 Case a : result = "duh"
 Case Else
   result = "impossible"

End Select</lang>

inline-conditional

<lang vbnet>Imports Microsoft.VisualBasic

...

Dim result As String = CType(IIf("pants" = "glasses", "passed", "failed"), String) 'VB 1-8

Dim result As String = If("pants" = "glasses", "passed", "failed") 'VB 9</lang>

generic-inline-conditional

Works with: Microsoft (R) Visual Basic Compiler version 8.0

<lang vbnet>Imports Microsoft.VisualBasic

...

Function IIf2(Of T)(ByVal condition As Boolean, ByVal truepart As T, ByVal falsepart As T) As T

 If condition Then Return truepart Else Return falsepart

End Function

...

Dim result As String = IIf2("pants" = "glasses", "passed", "failed") ' type is inferred</lang>


generic-inline-conditional

Language Version: 9.0+

<lang vbnet>Dim result As String = If("pants" = "glasses", "passed", "failed") ' type is inferred</lang>

VBScript

if-then-else

<lang vbscript>if (condition) then

  result = "met"

else

  Result = "not met"

end if</lang>

Vorpal

if-then-else

<lang vorpal>if(condition){

  result = 'met'

} else{

  result = 'not met'

}</lang>

Wrapl

simple conditional

Conditionals in Wrapl are expressions. Either success or failure can be omitted from the expression. <lang wrapl>condition => success // failure condition => success condition // failure</lang>

goal directed evaluation

Wrapl's goal directed evaluation can be used to control conditional execution. The select-right operator & produces the values of the right operand for each value produced by the left operand. Thus if the left operand fails to produce any values, the right operand is never evaluated. <lang wrapl>condition & success</lang> The sequence operator | produces the values of the left operand followed by the values of the right operand. Thus if the left operand produces enough values (for example in a context where only one value is required), the right operand is never evaluated. <lang wrapl>condition | failure</lang>

XSLT

The <xsl:if> element allows simple conditional processing. <lang xml><xsl:if test="condition"> </xsl:if></lang> The <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements allow more general conditional processing. <lang xml><xsl:choose>

 <xsl:when test="condition1">
 </xsl:when>
 <xsl:when test="condition2">
 </xsl:when>
 <-- etc. -->
 <xsl:otherwise>
 </xsl:otherwise>

</xsl:choose></lang> The XPath expressions allowed for the "test" attribute are those which return a boolean value: <lang xml>@attrib = 'false' position() != last() not( false() ) boolean( $param )</lang>

contains( node, "stuff" ) and (position() > first())