Wiki
Clone wikipool-spec / ControlStructures
Control Structures
if
T core.if!(T)( cond:bool, ifTrue:block(T)(), ifFalse:block(T)() = noop )
An if statement takes a condition and executes the first block if it is true otherwise the other ( if provided ). The value of the executed block is returned.
mutable cond = false; if (cond, sout.writeln("Not printed.")); cond = true; if (cond, sout.writeln("Printed.")); if (cond, sout.writeln("Printed."), sout.writeln("Not printed.")); mutable cond = false; if (cond, sout.writeln("Not printed."), sout.writeln("Printed."));
Syntactic Sugar
It doesn't look that bad but when you get into if else's things start to get
ugly. For if
s without an else clause you can use the trailing-block
function call syntax. With an else clause the if statement has a special syntax
using the else keyword.
mutable cond = true; if (cond) sout.writeln("Printed"); if (cond) sout.writeln("Printed"); // Now that's what you were looking else sout.writeln("Not printed."); // for.
else if
By chaining if statements together you can easily achieve else if
statements.
mutable cond = 7; if ( cond == 1 ) sout.writeln("1"); else if ( cond == 2 ) sout.writeln("2"); else if ( cond == 3 ) sout.writeln("3"); else if ( cond == 4 ) sout.writeln("4"); else if ( cond == 5 ) sout.writeln("5"); else sout.writeln("I give up, it's big.");
while
() while!(T)( block(bool)() cond, block(uint)() code )
The while statement performs the following steps.
- Evaluate cond. If true quit.
- Evaluate code.
- Go back to step 1.
mutable tries:uint = 0; while ( 2^^tries < 1_000_000 ) tries++; sout.write("You need ").write(tries, " bytes to store 1 000 000.");
dowhile
() dowhile!(T)( block(bool)() cond, block(uint)() code )
The same as while except it doesn't evaluate the condition on the first pass. (start at step 2)
for
() for!(T)( block()() init, block(bool)() cond, block()() inc, block(uint)() code )
The for loop performs the following steps.
- Evaluate init.
- Evaluate cond. If true quit.
- Evaluate code.
- Evaluate inc.
- Go back to step 2.
The for loop cannot be expressed perfectly as a function call as the variables
declared in the init
block are available in the other three. If it were
to be translated into a while loop it would look like.
for ( {init} , {cond}, {inc} ) {code} // is equivalent to: { {init}; while ({cond}) { {code}; {inc}; } }
Updated