Operators
Grammar: or-expr, and-expr, is-expr, cmp-expr, bit-expr, add-expr, mul-expr, pipe-expr, unary-expr, pow-expr
Each operator is defined on particular types, and using it on anything else is a compile error:
+adds two numbers, joins twoStrs, and joins two vectors into a new one whose length is the two added.-*/%**are arithmetic, onIntorFloat.==and!=compare two values of one type structurally — element by element down a vector, field by field through a declared type. Two function values cannot be compared, and two different types are an error rather than a silentfalse.<><=>=order anInt, aFloator aStr, and nothing else.&&and||takeBools and short-circuit. There is no truthiness: anInt, aStr, anAtomor a vector is not a condition.- Unary
-negates a number; unary!inverts aBool. &|^and unary~work on an integer's bits, and<<>>shift one — the slide on bits and bytes has them.
From loosest to tightest: ||, &&, then is and bounds, then the comparisons, the bitwise operators, + -, * / %, the pipe |>, unary -, ! and ~, and tightest **. So !found && ready is (!found) && ready, -2 ** 2 is -(2 ** 2), and ** groups from the right: 2 ** 3 ** 2 is 2 ** 9. Comparisons do not chain — 1 < x < 3 is a compile error — and ! may not be applied to an expression containing an is, since what a match binds could never be set; write the else instead.
A mut variable steps with += -= *= /=, each shorthand for x = x <op> …, and an Int with ++ and --. += joins a Str too. None of these ever converts a number behind your back: hive.math.max(0, health) with an Int health is a compile error rather than a surprise.
proc main(): void {
echo 7 + 3 * 2 // 13 — * binds tighter than +
echo 7 / 2 // 3 — Int division truncates
echo 7 % 2 // 1 — the remainder
echo 2 ** 3 ** 2 // 512 — ** groups from the right
echo -2 ** 2 // -4 — ** binds tighter than unary minus
echo 3 < 4 // ordering: Int, Float and Str
echo "bee" == "bee" // structural equality
echo [1, 2] != [2, 1]
}proc main(): void {
echo "hive" + " " + "tour" // Str: joined
echo [1, 2] + [3] // vectors: a new one, the lengths added
}proc main(): void {
ready := true
warm := false
echo ready && warm
echo ready || warm
echo !warm
// Tighter than every comparison, so both of these need their parentheses.
echo !(ready && warm)
echo !(1 == 2)
}proc main(): void {
mut n := 10
n += 5
n -= 3
n *= 2
n /= 4
n++
n--
echo n // 6
mut greeting := "hello"
greeting += ", bee"
echo greeting
}