Version: 0.8.0

Booleans and Conditionals

Booleans#

The type of a boolean value is bool. Here is how to define a boolean value:

const a : bool = True // Also: true
const b : bool = False // Also: false

Common operations:

and
Logical and
const logical_and: bool = True and True;
or
Logical or
const logical_or: bool = False or True;
not
Logical not
const logical_not: bool = not False;
=
Equals
const eq: bool = 2 = 3;
=/=
Not equals
const not_eq: bool = 2 =/= 3;
>
Greater than
const gt: bool = 4 > 3;
<
Less than
const lt: bool = 4 < 3;
>=
Greater than or equal to
const gte: bool = 4 >= 3;
<=
Less than or equal to
const lte: bool = 4 <= 3;

Comparing Values#

In LIGO, only values of the same type can be compared. Moreover, not all values of the same type can be compared, only those with comparable types, which is a concept lifted from Michelson. Comparable types include, for instance, int, nat, string, tez, timestamp, address, etc. As an example of non-comparable types: maps, sets or lists are not comparable: if you wish to compare them, you will have to write your own comparison function.

Comparing Strings#

const a : string = "Alice"
const b : string = "Alice"
const c : bool = (a = b) // True

Comparing numbers#

const a : int = 5
const b : int = 4
const c : bool = (a = b)
const d : bool = (a > b)
const e : bool = (a < b)
const f : bool = (a <= b)
const g : bool = (a >= b)
const h : bool = (a =/= b)

Comparing tez#

๐Ÿ’ก Comparing tez values is especially useful when dealing with an amount sent in a transaction.

const a : tez = 5mutez
const b : tez = 10mutez
const c : bool = (a = b) // False

Conditionals#

Conditional logic enables forking the control flow depending on the state.

type magnitude is Small | Large // See variant types.
function compare (const n : nat) : magnitude is
if n < 10n then Small else Large

You can run the compare function defined above using the LIGO compiler like this:

ligo run-function
gitlab-pages/docs/language-basics/src/boolean-if-else/cond.ligo compare '21n'
# Outputs: Large(Unit)

When the branches of the conditional are not a single expression, as above, we need a block:

if x < y then
block {
const z : nat = x;
x := y; y := z
}
else skip;

As an exception to the rule, the blocks in a conditional branch do not need to be introduced by the keyword block, so we could have written instead:

if x < y then {
const z : nat = x;
x := y; y := z
}
else skip;