-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc.mapal
More file actions
59 lines (53 loc) · 1.85 KB
/
Copy pathcalc.mapal
File metadata and controls
59 lines (53 loc) · 1.85 KB
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
// calc.mapal — a simple calculator in Mapal-Core
//
// HOW "CHOOSING" WORKS HERE:
// Mapal-Core has no stdin — the only effect is print/println (output). So you
// don't type a choice at runtime; you CHOOSE by editing the op-code and the two
// numbers in `main` below, then re-run:
// cargo run -p mapal-interp --example run -- examples/calc.mapal
//
// Operation codes (the "menu"):
// 0 = + 1 = - 2 = * 3 = / (anything else) = %
//
// calc(op, a, b) dispatches on `op` with a guard block. Guard arms are PURE,
// and the condition GATES them (plan-s39): only the selected arm's work runs,
// so `a / b` does not execute when you picked `+`. `calc(0, 20, 0)` is 20, not
// a trap. Arms are still compiled — both code paths exist in the binary — but
// an arm that is not taken is not computed.
//
// Expected output (op-by-op demo over a = 20, b = 6):
// 20 + 6 = 26
// 20 - 6 = 14
// 20 * 6 = 120
// 20 / 6 = 3
// 20 % 6 = 2
fn calc(op: i32, a: i32, b: i32) -> i32 {
// Switch on the op-code with a guard block: each `-N->` arm matches an integer
// literal, `-_->` is the default. This is the idiomatic Mapal-Core dispatch.
op -> {
-0-> a + b;
-1-> a - b;
-2-> a * b;
-3-> a / b;
-_-> a % b;
} -> ret;
}
fn main() {
// The "menu": one line per operation, all on a = 20, b = 6.
// Change the op code and the two numbers to make your own calculation.
(0, 20, 6) -> calc -> r_add;
"20 + 6 = " -> print;
r_add -> println;
(1, 20, 6) -> calc -> r_sub;
"20 - 6 = " -> print;
r_sub -> println;
(2, 20, 6) -> calc -> r_mul;
"20 * 6 = " -> print;
r_mul -> println;
(3, 20, 6) -> calc -> r_div;
"20 / 6 = " -> print;
r_div -> println;
(4, 20, 6) -> calc -> r_mod;
"20 % 6 = " -> print;
r_mod -> println;
}