Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Augmented assignment

Andy C++ supports augmented assignment for operations on existing variables.

This example increments a number with augmented assignment.

let my_number = 3;
my_number += 5;
print(my_number);  // 8

Indexed targets

The target of an augmented assignment can also be an indexed location:

let values = [1, 2, 3];
values[0] += 10;
print(values);  // [11,2,3]

This works for a character of a string and for a slice of a list too:

let text = "ab";
text[0] ++= "x";
print(text);   // axb

let items = [1, 2];
items[0..1] ++= [3];
print(items);  // [1,3,2]

Types

a op= b is checked like a = a op b: the operator has to take both values, and its result has to fit the type of a:

let values = [1];
values ++= ["two"]; // error: No function called '++' found that matches the arguments '[Int], [String]'

Annotate the target with Any to allow mixed contents:

let mixed: [Any] = [1];
mixed ++= ["two"];
print(mixed);  // [1,"two"]

Optimization

You might expect list ++= [1,2,3] to desugar to list = list ++ [1,2,3], but that would waste work. Andy C++ handles some augmented assignments directly. In this case, it appends [1,2,3] without creating an intermediate list.

Flexibility

Note: I stole this feature from Noulith.

Augmented assignment also works with built-in functions and user-defined functions. For example:

let x = 3;
let f = fn (a, b) { a + b }; // simple addition
x f= 5;   // similar to: x = f(x, 5);
print(x); // 8

One common use case is tracking the highest or lowest value in a loop:

fn g(x) => (x - 40.0) ^ 2;
let lowest, highest = Inf, -Inf;

for x in 1..100 {
  lowest min= g(x);
  highest max= g(x);
}

print(lowest, highest);  // 0.0 3481.0