Skip to main content
Version: 1.6.0

Options

The option type is a parametric, predefined variant type that is used to express whether there is a value of some type or none. This is especially useful when calling a partial function, that is, a function that is not defined for some inputs. In that case, the value of the option type would be None(), otherwise Some(v), where v is some meaningful value of any type. A typical example from arithmetics is the division:

function div (a: nat, b: nat): option<nat> {
if (b == 0n) return None() else return Some(a/b)
};

Note: See the predefined namespace Option

Euclidean Division

For cases when you need both the quotient and the remainder, LIGO provides the ediv operation. ediv(x,y) returns Some (quotient, remainder), unless y is zero, in which case it returns None. The function ediv is overloaded to accept all the combinations (4) of natural and integer numbers:

// All below equal Some (7,2)
const ediv1: option<[int, nat]> = ediv(37, 5);
const ediv2: option<[int, nat]> = ediv(37n, 5);
const ediv3: option<[nat, nat]> = ediv(37n, 5n);
const ediv4: option<[int, nat]> = ediv(37, 5n);

Checking positivity

You can check if a value is a natural number (nat) by using a predefined cast function which accepts an integer (int) and returns an optional natural number (nat): if the result is None, then the given integer was positive, otherwise the corresponding natural number n is given with Some(n).

const one_is_nat : option<nat> = is_nat(1);