Assignment Expressions
An assignment expressions consists of the character = immediately followed by
a pattern. It binds the names in the pattern to the corresponding parts of its
input value so you can reuse them later in the program. A pattern can be a
name, an array literal where the elements are patterns, or an object literal
where the values are patterns.
| Program | Type | Value | Error |
|---|---|---|---|
1 +1 =a 3 *2 +a | Num | 8 | |
1 +1 ==2 =p 1 +1 ==1 =q p ==q not | Bool | true | |
[1, 2, 3] =[a, b, c] a | Num | 1 | |
[1, 2, 3] =[a;r] r | Arr<Num, Num> | [2, 3] | |
{a: 1, b: 2, c: 3} ={a: d, b: e, c: f} d | Num | 1 | |
{a: 1, b: 2, c: 3} ={a: d, b: e, c: f} e | Num | 2 | |
{a: 1, b: 2, c: 3} ={a: d, b: e, c: f} f | Num | 3 | |
for Num def cube Num as =n *n *n ok 3 cube | Num | 27 |
An “impossible match” error occurs if the pattern cannot match any values of the input type, e.g., if an array pattern has a different length from the input, or matching objects with array patterns, or vice versa, or if an object pattern contains keys that the input doesn’t.
| Program | Type | Value | Error |
|---|---|---|---|
[1, 2, 3] =[a, b] | Type error | ||
{a: 1, b: 2, c: 3} =[a, b] | Type error | ||
{a: 1, b: 2, c: 3} ={g: h} | Type error |
A “nonexhaustive match” error occurs if the pattern can match some but not all values of the input type, e.g., if a variable-length array type is matched as fixed-length, or if an object type is matched against a key it might or might not contain.
| Program | Type | Value | Error |
|---|---|---|---|
for Arr<Num...> def f Num as =[a, b] a ok | Type error | ||
for Obj<a: Num, Num> def f Num as ={a: a, b: b} a +b ok | Type error | ||
for Obj<a: Num, Num> def f Num as ={b: b} b ok | Type error |