-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathControlStructures.t2t
103 lines (72 loc) · 2.09 KB
/
ControlStructures.t2t
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Control Structures
%!includeconf: config.t2t
== if ==
``` T core.if!(T)( cond:bool, ifTrue:{(T)()}, ifFalse:{(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.
```
var cond = false;
if (cond, {sout.writeln("Not printed.")});
cond = true;
if (cond, {sout.writeln("Printed.")});
if (cond, {sout.writeln("Printed.")}, {sout.writeln("Not printed.")});
cond = false;
if (cond, {sout.writeln("Not printed.")}, {sout.writeln("Printed.")});
```
== elif ==
``` {(T)()} core.elif!(T)( cond:bool, ifTrue:{(T)()}, ifFalse:{(T)()} = noop )
This function returns a block that will call ``ifTrue`` if ``cond`` is true or
``ifFalse`` otherwise.
```
var i = 4;
if i == 1, { sout.writeln("1") },
elif i == 2, { sout.writeln("2") },
elif i == 2, { sout.writeln("3") },
elif i == 2, { sout.writeln("4") };
```
== while ==
``` () while!(T)( cond:{(bool)()}, code:{} )
The while statement performs the following steps.
# Evaluate cond. If true quit.
# Evaluate code.
# Go back to step 1.
```
var 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)( cond:{()(bool)}, code:{} )
The same as while except it doesn't evaluate the condition on the first pass.
(start at step 2)
== for ==
``` () for!(T)( init:{}, cond:{}, inc:{}, 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. Except ``{inc}`` will
be called on continue.
```
for ( /*init*/ , /*cond*/, /*inc*/, /*code*/ )
// is equivalent to:
{
/*init*/;
var first = true;
while /*cond*/,
{
if first,
{
/*inc*/;
first = false;
};
/*code*/;
};
}
```