Operators
Unary operators
-a negates a number.
~a is bitwise negation.
Since this latter is an uncommon operation, it's defined in keen/bits.
(Imports will be explained in Modules.)
- doesn't work on nat since that is an unsigned type.
~ doesn't work on int since bitwise operations on signed numbers are confusing.
Defining operators
Operators are just ordinary functions, so you can define them for any type.
Binary operators
Here are all binary operators and operator-like syntaxes, in order from lowest to highest precedence.
Operators with the same precedence, such as < and >, share a row in the table.
Lower precedence means being less tightly binding.
+ has lower precedence than *,
so 1 +2 *3 is 7
because 2 * 3 binds more tightly than
1 + 2.
| Syntax | Use |
|---|---|
is | Asserts that two expressions have the same value. |
foo= | A function name may end in = , which makes it parse as infix. |
else | Provides a default value for an option. See Options. |
or | True if either side is true. |
and | True if both sides are true. |
'foo | Infix function calls. |
foo | Normal function calls. |
.. | Creates a range, e.g. 0 .. 10 .
The low end is inclusive and the high end is exclusive. |
~, ~~ | Adds one (~) or many (~~) elements to a collection. |
==, !=, <, >,
<=, >=, <=> | Standard comparison operators.
All return bool except <=> returns comparison. |
| | Union (of sets, flags, or bits in a nat). |
& | Union (of sets, flags, or bits in a nat). |
<<, >> | Bitshift left and right. These are only defined for nats. |
+, - | Addition and subtraction. |
*, /, % | Multiplication, division, and modulo. |
** | Exponentiation: 2 ** 3 is 8. |
As shown above, infix function calls like 'contains have lower precedence than any operator.
The above parses like: log ((10 .. (10 + 10)) 'contains 15)
The parentheses around the argument to log are needed
because the call to 'contains has lower precedence.
Assignment functions
Function names are allowed to end in an = sign.
If they do, they are always parsed as infix and with an especially low precedence.
Binary assignment
Any binary function, including operators,
can be combined with the assignment operator := to update a local.
This works with set-x functions too, such as record field setters.
Logical "operators"
Unlike the actual operators, these are not functions and can't be overloaded.
!x negates booleans.
and and or work as you would expect.
These don't evaluate their right hand side if not necessary.
"is"
is parses with the lowest precedence.
It asserts that the left side is equal to the right side and returns void.