Marcel van Lohuizen | 6977a74 | 2019-01-30 21:30:01 +0100 | [diff] [blame] | 1 | [TOC](Readme.md) [Prev](conditional.md) [Next](cycles.md) |
Marcel van Lohuizen | 75cb003 | 2019-01-11 12:10:48 +0100 | [diff] [blame] | 2 | |
Marcel van Lohuizen | af0932f | 2019-01-11 13:03:56 +0100 | [diff] [blame] | 3 | _Expressions_ |
| 4 | |
Marcel van Lohuizen | 75cb003 | 2019-01-11 12:10:48 +0100 | [diff] [blame] | 5 | # Null Coalescing |
| 6 | |
Jonathan Amsterdam | e479038 | 2019-01-20 10:29:29 -0500 | [diff] [blame] | 7 | <!-- jba: the terms here are confusing. "Null coalescing" is actually not |
| 8 | that, but then there is something called "actual null coalescing." |
| 9 | |
| 10 | Just say that because _|_ | X evaluates to X, you can use disjunction |
| 11 | to represent fallback values. |
| 12 | |
| 13 | And then you can use that to effectively type-check with a default value. |
| 14 | --> |
| 15 | |
Marcel van Lohuizen | 75cb003 | 2019-01-11 12:10:48 +0100 | [diff] [blame] | 16 | With null coalescing we really mean error, or bottom, coalescing. |
| 17 | The defaults mechanism for disjunctions can also be |
| 18 | used to provide fallback values in case an expression evaluates to bottom. |
| 19 | |
| 20 | In the example the fallback values are specified |
| 21 | for `a` and `b` in case the list index is out of bounds. |
| 22 | |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 23 | To do actual null coalescing one can unify a result with the desired type |
| 24 | to force an error. |
| 25 | In that case the default will be used if either the lookup fails or |
| 26 | the result is not of the desired type. |
| 27 | |
Marcel van Lohuizen | 75cb003 | 2019-01-11 12:10:48 +0100 | [diff] [blame] | 28 | <!-- CUE editor --> |
| 29 | ``` |
| 30 | list: [ "Cat", "Mouse", "Dog" ] |
| 31 | |
Marcel van Lohuizen | c9b3cb2 | 2019-01-30 11:32:41 +0100 | [diff] [blame] | 32 | a: *list[0] | "None" |
| 33 | b: *list[5] | "None" |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 34 | |
| 35 | n: [null] |
Marcel van Lohuizen | 6977a74 | 2019-01-30 21:30:01 +0100 | [diff] [blame] | 36 | v: *n[0]&string | "default" |
Marcel van Lohuizen | 75cb003 | 2019-01-11 12:10:48 +0100 | [diff] [blame] | 37 | ``` |
| 38 | |
| 39 | <!-- result --> |
| 40 | ``` |
| 41 | list: [ "Cat", "Mouse", "Dog" ] |
| 42 | |
| 43 | a: "Cat" |
| 44 | b: "None" |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 45 | n: [null] |
| 46 | v: "default" |
Jonathan Amsterdam | e479038 | 2019-01-20 10:29:29 -0500 | [diff] [blame] | 47 | ``` |