| 1 | (* match: the names of an arm stand for the fields of the variant |
| 2 | itself when it is a variable, and for a copy when it isn't. *) |
| 3 | module VariantMatch; |
| 4 | import Out; |
| 5 | |
| 6 | type |
| 7 | Shape = variant num(n: I64); pair(a, b: I64); none; end; |
| 8 | Op = (plus, minus, times, divide); |
| 9 | |
| 10 | var g: Shape; |
| 11 | |
| 12 | proc copyOfG(): Shape; |
| 13 | begin |
| 14 | return g; |
| 15 | end; |
| 16 | |
| 17 | proc show(s: Shape); |
| 18 | begin |
| 19 | match s of |
| 20 | | num(n): Out.str("num "); Out.int(n); |
| 21 | | pair(a, b): Out.str("pair "); Out.int(a); Out.char(' '); Out.int(b); |
| 22 | | none: Out.str("none"); |
| 23 | end; |
| 24 | Out.ln; |
| 25 | end; |
| 26 | |
| 27 | proc kind(op: Op); |
| 28 | begin |
| 29 | match op of |
| 30 | | plus, minus: Out.str("additive"); |
| 31 | | times: Out.str("times"); |
| 32 | | else: Out.str("other"); |
| 33 | end; |
| 34 | Out.ln; |
| 35 | end; |
| 36 | |
| 37 | proc size(n: I64); |
| 38 | begin |
| 39 | match n of |
| 40 | | 0: Out.str("zero"); |
| 41 | | 1 .. 9: Out.str("small"); |
| 42 | | -5 .. -1, 10: Out.str("negative or ten"); |
| 43 | | else: Out.str("big"); |
| 44 | end; |
| 45 | Out.ln; |
| 46 | end; |
| 47 | |
| 48 | proc main*; |
| 49 | begin |
| 50 | g := pair(3, 4); |
| 51 | match g of |
| 52 | | pair(a, b): a := a * 10; INC(b); (* through the names: g changes *) |
| 53 | | else: |
| 54 | end; |
| 55 | show(g); |
| 56 | match copyOfG() of |
| 57 | | pair(a, b): a := 0; b := 0; (* a copy: g does not change *) |
| 58 | | else: |
| 59 | end; |
| 60 | show(g); |
| 61 | match g of |
| 62 | | num: Out.str("no\n"); (* fields left unnamed *) |
| 63 | | pair: Out.str("unnamed\n"); |
| 64 | | none: Out.str("no\n"); |
| 65 | end; |
| 66 | g := none; |
| 67 | show(g); |
| 68 | g := num(5); |
| 69 | show(g); |
| 70 | kind(plus); kind(minus); kind(times); kind(divide); |
| 71 | size(0); size(5); size(-3); size(10); size(11); |
| 72 | end; |
| 73 | |
| 74 | end VariantMatch. |