Skip to main content

If

rascal-0.34.0

Synopsis

Conditional statement.

Syntax

if (Exp)
Statement

if (Exp) {
Statements
}

if (Exp)
Statement₁
else
Statement₂

if (Exp) {
Statements₁
}
else {
Statements₂
}

Types

Expif ( Exp ) Statement;
boolvoid
ExpStatement₁Statement₂if ( Exp ) Statement₁ else Statement₂;
boolT₁T₂lub(T₁, T₂)

Description

The test Exp is evaluated and its outcome determines the statement to be executed: Statement₁ if Exp yields true and Statement₂ otherwise. The value of an if-then statement is equal to Statement when its test is true. Otherwise it is void. The value of an if-then-else statement is the value of the statement that was executed.

Examples

rascal>if (3 > 2) {
>>>>>>> 30;
>>>>>>>} else {
>>>>>>> 40;
>>>>>>>}
int: 30
rascal>x = if (3 > 2) {
>>>>>>> 30;
>>>>>>>} else {
>>>>>>> 40;
>>>>>>>}
int: 30
rascal>if (3 > 2)
>>>>>>> 30;
int: 30

An if-then statement yields void when its test is false (demonstrated by the ok that is printed by the Rascal system):

rascal>if( 2 > 3 ) 
>>>>>>> 30;
ok

Here we use Fail to backtrack over the possible matches of the if:

rascal>import IO;
ok
rascal>Label: if ([*_, 1, *_] := [1,2,1]) {
>>>>>>> println("yep");
>>>>>>> fail Label;
>>>>>>>}
yep
yep
ok

Benefits

  • backtracking is a powerful and easy way to search for solutions
  • nested if-then-else's are often not necessary with the , notation

Pitfalls

  • backtracking does not undo side-effects like println