Macaulay2 » Documentation
Packages » Macaulay2Doc > The Macaulay2 language > operators > ??
next | previous | forward | backward | up | index | toc

?? -- null coalescing operator

Synopsis

Description

If x is null or a non-interrupting error, then y is returned. When it is an error, the error message is suppressed like it is with try.

i1 : null ?? 2

o1 = 2
i2 : 1/0 ?? 3

o2 = 3

In all other cases, x is returned.

i3 : 5 ?? 6

o3 = 5

Note that y is lazily evaluated, that is, it is only evaluated if it is necessary.

The null coalescing operator can be combined with augmented assignment as a shortcut for if x === null then x = y and if not x#?i then x#i = y.

i4 : x = null
i5 : x ??= 2

o5 = 2
i6 : x ??= 3

o6 = 2
i7 : x = new MutableList

o7 = MutableList{}

o7 : MutableList
i8 : x#0 ??= 4

o8 = 4
i9 : peek x

o9 = MutableList{4}
i10 : x#0 ??= 5

o10 = 4
i11 : peek x

o11 = MutableList{4}

It is also possible to install a method for a particular type to determine whether an instance x of that type should be considered "null" or not. Such a method should return either x or null

i12 : X = new Type of BasicList;
i13 : ?? X := x -> if #x > 0 then x;
i14 : x = new X from {};
i15 : y = new X from {5};
i16 : x ?? y

o16 = X{5}

o16 : X
i17 : y ?? x

o17 = X{5}

o17 : X

It is also possible to use ?? as a prefix operator to call this method.

i18 : ?? 2

o18 = 2
i19 : ?? x
i20 : ??(1/0)

Caveat

Although this operator is "flexible" in the sense that it possible to install a method to determine the behavior on the left-hand side, it is not truly flexible like most other binary operators. In particular, since it is only lazily evaluated, it is not possible to install a method that uses the value of the right-hand side.

For the programmer

The object ?? is a keyword.

This operator may be used as a binary operator in an expression like x??y.

This operator may be used as a prefix unary operator in an expression like ??y. The user may install a method for handling such expressions with code such as

           ?? Y := (y) -> ...

where Y is the class of y.