Add some Standard ML examples.
Chris Pressey
4 years ago
0 | Standard ML Examples | |
1 | ==================== | |
2 | ||
3 | -> Functionality "Evaluate Standard ML expression" | |
4 | -> is implemented by shell command | |
5 | -> "cp %(test-body-file) /tmp/foo.sml && echo ';printVal it' >>/tmp/foo.sml && mosml -quietdec /tmp/foo.sml" | |
6 | ||
7 | -> Tests for functionality "Evaluate Standard ML expression" | |
8 | ||
9 | Some basic expressions. | |
10 | ||
11 | 1 | |
12 | ===> 1 | |
13 | ||
14 | ~100 * ~100 * ~100 | |
15 | ===> ~1000000 | |
16 | ||
17 | A conditional. | |
18 | ||
19 | if true then 5 else 6 | |
20 | ===> 5 | |
21 | ||
22 | The basic usage of `let` to create name bindings. | |
23 | ||
24 | let val a = 2 in a end | |
25 | ===> 2 | |
26 | ||
27 | let fun r(x) = 77 in r(1) end | |
28 | ===> 77 | |
29 | ||
30 | let fun r(x) = x in r(66) end | |
31 | ===> 66 | |
32 | ||
33 | You can also use `val` and `fn` to define function values in a `let`. | |
34 | ||
35 | let val r = fn(x) => x in r(66) end | |
36 | ===> 66 | |
37 | ||
38 | ML's `let` is like Scheme's `let*`: later bindings can refer to earlier ones. | |
39 | ||
40 | let | |
41 | fun r(x) = x * 2 | |
42 | fun p(x) = r(x) * 2 | |
43 | in | |
44 | p(10) | |
45 | end | |
46 | ===> 40 | |
47 | ||
48 | However in a `let`, earlier bindings cannot refer to later ones. | |
49 | ||
50 | Skipping because I don't know why `mosml` doesn't report this error under `falderal`. | |
51 | It does when you run it from the command line. | |
52 | ||
53 | > main() = | |
54 | > let | |
55 | > fun oddp(x) = if x = 0 then false else evenp(x - 1) | |
56 | > fun evenp(x) = if x = 0 then true else oddp(x - 1) | |
57 | > in | |
58 | > evenp(6) | |
59 | > end | |
60 | > ???> Unbound value identifier: evenp | |
61 | ||
62 | You need to use `rec` in order to let earlier bindings refer to later ones, | |
63 | and you need to use `and` between all the mutually recursive functions. | |
64 | ||
65 | let | |
66 | val rec oddp = fn(x) => if x = 0 then false else evenp(x - 1) | |
67 | and rec evenp = fn(x) => if x = 0 then true else oddp(x - 1) | |
68 | in | |
69 | evenp(6) | |
70 | end | |
71 | ===> true | |
72 | ||
73 | let | |
74 | val rec oddp = fn(x) => if x = 0 then false else evenp(x - 1) | |
75 | and rec evenp = fn(x) => if x = 0 then true else oddp(x - 1) | |
76 | in | |
77 | evenp(7) | |
78 | end | |
79 | ===> false |