Arithmetic operators
a + b, a - b, a * b, a / b, and a % b add, subtract, multiply, divide, and take the remainder. -a negates a number. + also joins two strings.
Details
- Both operands have one type: a single numeric kind such as
intorfloat64, or a named primitive type over one. Ant never converts between kinds, so1 + 1.0and"n=" + 1are compile errors. The result has the operands' type. - Integer
/truncates toward zero, and%takes the sign of the dividend, for floats too. - Integer arithmetic panics when the result does not fit the kind, including unsigned subtraction below zero, and
/and%panic on a zero divisor. Float arithmetic follows IEEE 754 and never panics: dividing by zero gives an infinity orNaN. *,/, and%bind tighter than+and-; unary-binds tighter than both.
Basic examples
The five binary operators on integers:
7 + 2 // 9
7 - 2 // 5
7 * 2 // 14
7 / 2 // 3
7 % 2 // 1On floats, / keeps the fraction:
7.0 / 2.0 // 3.5
1.5 * 4.0 // 6.0+ joins two strings:
"ant" + "hill" // "anthill"Scope
Negative operands
Integer / truncates toward zero, and % keeps the sign of the dividend:
-7 / 2 // -3
-7 % 2 // -1
7 % -2 // 1% on floats follows the same rule:
5.5 % 2.0 // 1.5
-7.5 % 2.0 // -1.5Unary minus
- before an operand negates it, and binds tighter than *:
let n = 4
-n * 3 // -12
-(n - 6) // 2Precedence and grouping
*, /, and % bind tighter than + and -. Parentheses group first:
2 + 3 * 4 // 14
(2 + 3) * 4 // 20Other numeric kinds
The operators work on every numeric kind, as long as both operands have it. Convert a literal to the kind of the other operand:
let level = byte(200)
level + byte(50) // 250
uint8(255) / uint8(2) // 127
float32(1.5) * float32(2.0) // 3.0Float infinities and NaN
Float division by zero follows IEEE 754 and does not panic:
1.0 / 0.0 // Infinity
-1.0 / 0.0 // -Infinity
0.0 / 0.0 // NaN
1.0 % 0.0 // NaN
1e308 * 10.0 // InfinityNamed primitive types
Two values of one named primitive type combine as their base kind, and the result keeps the type:
type Cents = int
type Name = string
Cents(150) + Cents(25) // Cents(175)
Cents(150) * Cents(2) // Cents(300)
Name("Ann") + Name(" Lee") // Name("Ann Lee")Compound assignment
Each compound assignment reads the target, applies the operator, and stores the result:
var n = 10
n += 5
n *= 2
n -= 1
n /= 3
n %= 4
println(n)1Generic functions
Inside a function with [T: Number], the operators apply to T, because they apply to every member of Number:
func double[T: Number](x: T): T { x + x }
println(double(21))
println(double(1.25))
println(double(byte(100)))42
2.5
200Applications
Average of integers
Convert to float64 before dividing to keep the fraction:
let scores = [90, 85, 72]
let total = scores.sum() ?? 0
println(total / scores.length())
println(float64(total) / float64(scores.length()))82
82.33333333333333Hours and minutes
/ and % by the same divisor split a quantity into units:
func clock(minutes: int): string {
let h = minutes / 60
let m = minutes % 60
let mm = String.fromInt(m).padStart(2, "0")
"${h}:${mm}"
}
println(clock(135))
println(clock(61))2:15
1:01Index that wraps around
% takes the sign of the dividend, so step back from 0 by adding the length first:
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
func shift(i: int, by: int): int {
let n = days.length()
((i + by) % n + n) % n
}
println(days[shift(5, 3)])
println(days[shift(0, -1)])Tue
SunMoney in cents
A named type keeps cents from mixing with other integers, and integer arithmetic stays exact. Array.sum takes only the members of Number, so add the Cents values with +=:
type Cents = int
func total(prices: Array[Cents]): Cents {
var sum = Cents(0)
for p in prices {
sum += p
}
sum
}
println(total([Cents(199), Cents(250)]))Cents(449)Properties and relations
For integers with a nonzero divisor, / and % fit together:
for a in [7, -7, 13, -13] {
for b in [2, -2, 5, -5] {
assert(a / b * b + a % b == a)
}
}+ and * are commutative on integers, and -a is 0 - a:
let a = 12
let b = -5
assert(a + b == b + a)
assert(a * b == b * a)
assert(-a == 0 - a)Wrapping arithmetic is a function, not an operator:
Bits.wrapAdd(Math.maxInt, 1) == Math.minInt // truePossible issues
No mixing of int and float64
An integer and a float do not combine. Convert one of them:
let half = 1 + 0.5 // error: + needs both operands of one type, got int and float64float64(1) + 0.5 // 1.5+ does not convert to a string
Use interpolation to build a string from a number:
let count = 3
let label = "n=" + count // error: + needs both operands of one type, got string and intlet count = 3
"n=${count}" // "n=3"Only + works on strings
+ joins strings, but * and - do not apply to them:
let line = "-" * 3 // error: * needs both operands of one type, got string and intUse the library function for the job:
"-".repeat(3) // "---"Integer division drops the fraction
1 / 2 is 0, not 0.5. Divide floats when you need the fraction:
1 / 2 // 0
1.0 / 2.0 // 0.5Integer overflow panics
There is no silent wraparound. A result that does not fit the kind panics:
Math.maxInt + 1 // panic: integer overflow
-Math.minInt // panic: integer overflow
int8(100) * int8(2) // panic: integer overflowUnsigned subtraction below zero overflows too:
byte(0) - byte(1) // panic: integer overflowCompound assignment overflows the same way:
var n = Math.maxInt
n += 1 // panic: integer overflowUse Bits.wrapAdd, Bits.wrapSub, or Bits.wrapMul when you want wraparound.
Integer division by zero panics
10 / 0 // panic: division by zero
10 % 0 // panic: division by zeroGuard the divisor before dividing:
func perItem(total: int, count: int): int {
if count == 0 { return 0 }
total / count
}
println(perItem(10, 0))
println(perItem(10, 4))0
2Literals are always int or float64
A literal does not take the kind of the other operand, so convert it:
let level = byte(200)
let next = level + 1 // error: + needs both operands of one type, got byte and intWrite level + byte(1).
A named type does not mix with its base
Cents(5) + 3 is a compile error. Wrap the plain value:
type Cents = int
let price = Cents(5) + 3 // error: + needs both operands of one type, got Cents and intWrite Cents(5) + Cents(3).
Durations have no operators
A duration literal is a Time.Duration, not a number, so +, -, * and unary - do not apply to it. Use the Time functions to add, subtract, and negate:
let total = 5s + 1s // error: + applies to a single numeric kind, string, or a named primitive type over one, not to Time.DurationTime.addDuration(5s, 1s) // PT6S
Time.addDuration(5s, Time.negate(1s)) // PT4S
Time.negate(5s) // -PT5SFor a multiple, compute the field:
let n = 3
Time.duration(seconds: 2 * n) // PT6SNarrow nullable and union values first
A value that may be null, or a union such as Number, is not a single kind:
let stock: int | null = 3
let next = stock + 1 // error: + needs both operands of one type, got int | null and intUse ?? or a guard: (stock ?? 0) + 1.
func add(a: Number, b: Number): Number {
a + b // error: + applies to a single numeric kind, string, or a named primitive type over one, not to Number; narrow first
}Use a type parameter, func add[T: Number](a: T, b: T): T, as in the generic example above.
Float results are rounded
Floats are binary, so decimal fractions are not exact:
0.1 + 0.2 // 0.30000000000000004
0.1 + 0.2 == 0.3 // falseCount money in integer cents, or compare floats within a tolerance.
A negative remainder
% is not a modulo: a negative dividend gives a negative remainder, which is not a valid index. Add the divisor and take % again, as in the wrap-around example above:
-1 % 7 // -1
(-1 % 7 + 7) % 7 // 6See also
Comparison operators · Assignment · int · float64 and float32 · byte · Number literals · Bits.wrapAdd · Array.sum · String.repeat · String.padStart · Math.abs · float64(x) · Duration literals · Time.Duration
