git.iko.soy/rowtype-yoga/purescript-native
on 5159dfd help sign in
90 lines 1.9 kB history raw
1Blocks
2======
4Blocks are collections of statements wrapped in braces `{ ... }`. Blocks must return a value of the same type on every branch of execution.
6The following types of statement are supported:
8- Variable introduction
9- Variable assignment
10- For loops
11- While loops
12- If-Then-Else statements
14Here is an example of a power function defined using a block::
16 pow n p = {
17 var m = n;
18 for (i <- 0 until p) {
19 m = m * n;
20 }
21 return m;
22 }
24Blocks enable local mutation of their variables, but mutation is not allowed in general. The type system prevents mutable variables from escaping their scope.
26That is, while the example above is valid, the following does not compile::
28 incr n = {
29 n = n + 1;
30 return n;
31 }
33The variable `n` is not mutable, and so the assignment in the first line of the `do` block is not allowed.
35This function can be rewritten as follows::
37 incr n = {
38 var m = n;
39 m = m + 1;
40 return m;
41 }
43For Loops
44---------
46For loops iterate over a range of numbers::
48 total = {
49 var n = 0;
50 for (i <- 0 until 10) {
51 n = n + i;
52 }
53 return n;
54 }
56The bounds `0` and `10` are inclusive and exclusive respectively.
58While Loops
59------------
61While loops repeat a set of statements while a boolean expression evaluates to `true`::
63 log2 n = {
64 var count = 0;
65 var m = n;
66 while (m > 1) {
67 m = m / 2;
68 count = count + 1;
69 }
70 return count;
71 }
73If-Then-Else Statements
74-----------------------
76Else branches are optional, and may contain further `if` statements, just as in Javascript:
78 collatz n = {
79 var count = 0;
80 var m = n;
81 while (m > 1) {
82 if (m % 2 == 0) {
83 m = m / 2;
84 } else {
85 m = m * 3 + 1;
86 }
87 count = count + 1;
88 }
89 return count;
90 }