blob: 9c4f3760f6e87cc7cd349cda0fef1abad059d127 [file] [log] [blame] [view]
Marcel van Lohuizen6977a742019-01-30 21:30:01 +01001[TOC](Readme.md) [Prev](conditional.md) [Next](cycles.md)
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +01002
Marcel van Lohuizenaf0932f2019-01-11 13:03:56 +01003_Expressions_
4
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +01005# Null Coalescing
6
Jonathan Amsterdame4790382019-01-20 10:29:29 -05007<!-- 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 Lohuizen75cb0032019-01-11 12:10:48 +010016With null coalescing we really mean error, or bottom, coalescing.
17The defaults mechanism for disjunctions can also be
18used to provide fallback values in case an expression evaluates to bottom.
19
20In the example the fallback values are specified
21for `a` and `b` in case the list index is out of bounds.
22
Marcel van Lohuizen3e592b42019-01-11 20:31:29 +010023To do actual null coalescing one can unify a result with the desired type
24to force an error.
25In that case the default will be used if either the lookup fails or
26the result is not of the desired type.
27
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +010028<!-- CUE editor -->
29```
30list: [ "Cat", "Mouse", "Dog" ]
31
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +010032a: *list[0] | "None"
33b: *list[5] | "None"
Marcel van Lohuizen3e592b42019-01-11 20:31:29 +010034
35n: [null]
Marcel van Lohuizen6977a742019-01-30 21:30:01 +010036v: *n[0]&string | "default"
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +010037```
38
39<!-- result -->
40```
41list: [ "Cat", "Mouse", "Dog" ]
42
43a: "Cat"
44b: "None"
Marcel van Lohuizen3e592b42019-01-11 20:31:29 +010045n: [null]
46v: "default"
Jonathan Amsterdame4790382019-01-20 10:29:29 -050047```