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

Welcome

Welcome to the documentation for Andy C++!

This language is the result of a hobby project that I’ve poured a lot of time and effort into, purely for the fun of exploring new ideas in programming. I was inspired to create this language by Brian Chen, who developed Noulith to participate in (and ultimately win) Advent of Code. I’d like to thank Brian for the inspiration his work provided.

Disclaimers

  • To enhance clarity and minimize errors in this documentation, I used AI assistance, hoping it would make the language’s concepts easier to understand. Thank you for checking out Andy C++, I hope you enjoy exploring it as much as I enjoyed creating it!
  • This is the first time I attempted to make a programming language, and it’s one of my first Rust projects. You’re welcome to look at the source or even send in contributions but don’t expect it to be easy. I’m just an average guy bashing my head against problems until I stumble into a solution that seems to work. There will be a lot of really bad stuff under the hood.
  • I made this language for fun, and it’s meant to be used for fun. Don’t rely on the output of the interpreter to make important decissions. It took me 4 months before I noticed that subtracting floats was actually performing addition.
  • The performance of the interpreter is pretty bad, but as long as you come up with smart solutions and offload some of the calculations to functions written in rust you should be fine.

Playground

Write Andy C++ and run it right here: the interpreter is compiled to WebAssembly and runs in your browser. Press Ctrl+Enter to run, or open the playground on a page of its own.

The editor knows the language the way an editor with the language server does:

  • Errors are underlined as you type.
  • Completion offers the functions that fit: after xs. with xs a list, the ones that take a list. Ctrl+Space asks for it.
  • Hovering over a name shows its type, or a function’s signature and documentation.
  • F12, or Ctrl+click, jumps to where a name is declared.
  • Tick Vim for vim’s keys; :w runs the program.

The examples in this manual can be run too: hover over one and press the ▶ button, or the button next to it to open the example in the playground.

Installation

Prerequisites

Make sure you have Rust and Cargo installed on your system. If not, you can install them by following the instructions at https://rustup.rs/.

Installing

To install Andy C++ using Cargo, run the following command:

cargo install --git https://github.com/timfennis/andy-cpp

This will compile Andy C++ and install it into your Cargo bin directory (usually located at $HOME/.cargo/bin).

Hello, World!

Now that the Andy C++ interpreter is installed we can write our first program.

First create a file called hello.ndc and add this code:

print("Hello, world!");

In Andy C++ we don’t need a main function. Semicolons are mandatory, just like they are in Rust. If you already know Rust, Andy C++ will feel very familiar.

$ ndc hello.ndc
Hello, world!

You can also pass a program on the command line with --eval (or -e), without creating a file. Errors in it are reported against <eval>:

$ ndc run --eval 'print("Hello, world!");'
Hello, world!

Variables and Scopes

In Andy C++, you declare new variables with let, like you do in Rust. Use = to reassign an existing variable.

let x = 1;
print(x); // 1

Shadowing

Andy C++ follows Rust-style shadowing. If you declare a variable with an existing name, the new binding hides the old one in that scope.

let x = 1;
let x = 2;
print(x); // 2

You can create a new scope with curly braces. A binding inside that scope can shadow an outer binding. When the scope ends, the outer binding stays available.

let x = 1;
{
  let x = 2;
  print(x); // 2
}
print(x); // 1

Scopes

In Andy C++, every block is an expression. End the block with an expression, not a semicolon, and that expression becomes the block’s value.

let x = {
  let a = 1;
  let b = 2;
  a + b
};

print(x); // 3

Reassignment

The = operator assigns a new value to an existing variable. A variable keeps the type of the value it starts with, so a new value has to have that type too:

let n = 1;   // n is an Int
n = 2;       // fine
n = 3.14;    // error: mismatched types: found Float but expected Int

So to keep a running total of Floats, start it at 0.0 rather than 0. The same goes for augmented assignment, like n += 0.5.

An empty list or map gets its type from the first thing you put in it:

let counts = %{};
counts["a"] = 1;      // counts is a %{String: Int} from here on
counts["b"] = "two";  // error: mismatched types: found String but expected Int

A variable that only gets its real value later can hold an Option:

let pos = None;
pos = Some((1, 2));
print(pos);    // Some((1,2))

To store values of different types in one variable, annotate it with Any:

let x: Any = 1;
x = "text";    // fine
print(x);      // text

Type annotations

You can give a variable a type by adding : Type after its name. The value has to fit it:

let count: Int = 0;
let name: String = "world";
let xs: [Int] = [1, 2, 3];
print(count, name, xs);  // 0 world [1,2,3]
let x: Int = "hello";   // ERROR: mismatched types: found String but expected Int

An annotation is the way to say what an empty list or map will hold:

let xs: [Int] = [];
let m: %{String: Int} = %{};
print(xs, m);          // [] %{}

The same syntax works on function parameters and return types (see Function). See Types for the names you can use.

Destructuring

Destructuring works more like Python than Rust. Commas matter more than the delimiters, so [] and () both work.

The statements below are all equivalent:

let a, b = 3, 4;
let [a, b] = 3, 4;
let (a, b) = [3, 4];
let [a, b] = (3, 4);
print(a, b);  // 3 4

You can also destructure nested patterns:

let [a, (b, c)] = (1, [2, 3]);
print(a, b, c);  // 1 2 3

Ranges and deques destructure too, as long as they have exactly as many elements as there are names:

let low, high = 0..2;
print(low, high);  // 0 1

Types

Every value in Andy C++ has a type, but you rarely have to write one down. Before the program runs, Andy C++ works out the type of everything in it and reports code that can’t work. Annotations on variables, parameters and return values are optional.

Mistakes found before the program runs

A mistake is found even in code that never runs, and the error points through the calls to the line that can’t work. This program prints nothing:

fn inc(x) => x + 1;
fn shout(s) => inc(s) ++ "!";
print("hello");
if false {
    shout("a");  // error: No function called '+' found that matches the arguments 'String, Int'
}

An anonymous function knows the types of its parameters:

struct Player { name: String, score: Int }
let players = [Player("ann", 3), Player("bob", 5)];
players.map(fn(p) => p.score ++ " points");
// error: No function called '++' found that matches the arguments 'Int, String'

An empty list gets its type from what you put in it:

let xs = [];
xs.push(1);
xs.push("two");  // error: No function called 'push' found that matches the arguments '[Int], String'

If nothing is put in it, annotate it: let xs: [Int] = [];.

The types

Every value is an Any. The other types are:

  • Any
    • Option<T>
    • Bool
    • Int — checked signed 64-bit integers
    • Float — IEEE 754 f64 values
    • Number — arbitrary-size, rational, floating-point, and complex values
    • Sequences, which a for loop iterates over:
    • fn(A, B) -> C: a function taking an A and a B and returning a C
    • Structs: user-defined record types, one per struct declaration

These are also the names you write in annotations. Generic types take their parameters in angle brackets:

let xs: [Int] = [1, 2, 3];
let table: %{String: Int} = %{"a": 1, "b": 2};
let maybe: Option<String> = Some("hi");
let pair: (Int, String) = (1, "hi");
let grid: [[Int]] = [[1, 2], [3, 4]];

print(maybe, pair, grid);  // Some("hi") (1,"hi") [[1,2],[3,4]]

Struct names are type names like any other:

struct Point { x: Int, y: Int }

fn manhattan(p: Point) => p.x + p.y
let points: [Point] = [Point(1, 2), Point(3, 4)];
print(points.map(manhattan));  // [3,7]

Values of different types

The elements of a list, the keys and values of a map, the branches of an if, and the values a function returns all share one type. Numbers mix: [1, 2.5] is a list of Floats. Values that share no type are an error:

let mixed = [1, "a"];  // error: values of different types: Int and String

To mix them, say that they are Anys:

let b: Any = if true { 1 } else { "a" };
let xs: [Any] = [1, "a"];
let m: %{String: Any} = %{"a": 1, "b": "two"};
print(b, xs, m["b"]);  // 1 [1,"a"] two

Write the Any where the list or map is made: a list made as a [String] can’t be used as a [Any] later.

Getting a value out of an Any

Anything can go into an Any, but to get a value back out you need a cast. cast::<Int>(value) checks that the value is an Int, and cast?::<Int>(value) gives an Option<Int>:

let a: Any = 5;
let n: Int = a;  // error: mismatched types: found Any but expected Int
let a: Any = 5;
let n: Int = cast::<Int>(a);
print(n + 1);           // 6
print(cast?::<String>(a));    // None

The same goes for operators and functions: a + 1 needs cast::<Int>(a) + 1. Functions that take any value, like print, string and ==, take an Any as it is.

Indexing is the exception: a[i] works on an Any and gives an Any, so you can read nested data and cast what you find:

let data: %{String: Any} = %{"scores": [3, 5]};
print(cast::<Int>(data["scores"][1]) + 1);  // 6

Option

let value = Some(3);

if value.is_some() {
   // Some!!
   print(value.unwrap());  // 3
}

if value.is_none() {
    value.unwrap(); // ERROR!!
}

None is a literal, like true and false, so it can’t be used as a variable or parameter name.

Some functions have variations with a ? appended to their name that return options instead of throwing errors:

let my_list = [1,2,3];
print(my_list.first?);    // Some(1)

let empty = [];
print(empty.first?());    // None
empty.first();            // ERROR: collection is empty

The list accessors get? and index? give None when the index is past the end (see List):

let my_list = [10, 20, 30];
print(my_list.get?(0));     // Some(10)
print(my_list.index?(5));   // None

unwrap_or extracts the contained value, falling back to a default when the option is None:

print([10, 20, 30].get?(1).unwrap_or(0));  // 20
print([10, 20, 30].get?(9).unwrap_or(0));  // 0

Note: unfortunately the language doesn’t support pattern matching on options

Boolean

Booleans in Andy C++ represent a binary state, capable of holding either the value true or false. Unlike some other languages, where booleans are often used as numbers, Andy C++ treats them as a distinct type. When attempting to perform arithmetic operations with booleans, such as true + true, Andy C++ will throw an error because these operations are not defined for this type.

Operators defined for booleans:

OperatorFunction
&non-lazy and
|non-lazy or
~non-lazy xor
!not
orlazy logical or
andlazy logical and
notlogical not like ! but lower precedence

See Logical operators for short-circuiting and precedence rules.

Numbers

Andy C++ exposes three sibling numeric types:

  • Int stores a signed 64-bit integer. Arithmetic that overflows is an error.
  • Float stores an IEEE 754 f64.
  • Number supports arbitrary-size integers, exact rational values, floats, and complex values.

Int, Float, and Number are separate types: an Int doesn’t fit a Number annotation. Use an n literal or the Number constructor when you need a Number:

let count: Int = 42;
let measurement: Float = 42.0;
let exact: Number = 42n;

print(Number(42) == 42n);      // true
print(Number(42.0) == 42.0n);  // true

Literals

The n suffix creates a Number from a decimal integer or float. Binary, octal, and hexadecimal integers also accept it:

let large = 123456789123456789123456789n;
let decimal = 1.25n;
let binary = 0b101010n;
let octal = 0o52n;
let hexadecimal = 0x2an;

print(large);                       // 123456789123456789123456789
print(decimal);                     // 1.25
print(binary, octal, hexadecimal);  // 42 42 42

An _ between digits is ignored, so you can use it to group them:

print(1_000_000, 3.141_592, 0xFF_FF);  // 1000000 3.141592 65535

A literal with an exponent, written with e or E, is a Float:

print(2.5e3, 1e-3, 1E6);  // 2500.0 0.001 1000000.0

An integer literal without n must fit in i64. The lexer reports an error and suggests the suffixed form when it does not fit.

A whole number like 7 is an Int, but where a Float is expected, such as after a Float annotation or in a list of Floats, it is a Float:

print(7 / 2);            // 3
let f: Float = 7;
print(f / 2, [1, 2.5]);  // 3.5 [1.0,2.5]

A variable keeps the type it starts with, so one that starts at 0 stays an Int. To keep a running total of Floats, start it at 0.0:

let total = 0.0;
total += 2.5;          // fine: total is a Float
let count = 0;
count += 2.5;          // error: mismatched types: found Float but expected Int

Arbitrary-radix literals such as 16r2a remain Int literals and do not accept n. The i and j suffixes create complex Number values:

let z: Number = 2 + 3i;
print(z);            // 2+3i
print(z == 2 + 3j);  // true

Arithmetic modes

The arithmetic operators +, -, *, /, \, %, %%, and ^ define all nine pairs of Int, Float, and Number. The operands select the result type:

OperandsResult
Int, IntInt
Int, Float or Float, IntFloat
Float, FloatFloat
Any pair containing NumberNumber

Int uses checked i64 arithmetic. / truncates toward zero, while \ rounds toward negative infinity. % pairs with truncating division and %% returns a Euclidean remainder:

print(-7 / 2);   // -3
print(-7 \ 2);   // -4
print(-7 % 2);   // -1
print(-7 %% 2);  // 1

Float follows IEEE 754 behavior. Number keeps integer and rational operations exact when it can:

print(7 / 2);      // 3
print(7n / 2n);    // 7/2
print(2n ^ 100n);  // 1267650600228229401496703205376

Integer powers and shifts must fit their checked Int result. Use Number for negative exponents, arbitrary-size powers, and complex continuation. Roots, logarithms, inverse trigonometric functions, and fractional powers return a complex Number when the real result does not exist:

print(5n ^ -1n);   // 1/5
print(sqrt(-1n));  // 0+1i

Division by zero

Int division and remainder by zero report an error. Float returns IEEE infinity or NaN. Number also falls back to a wrapped Float result when an exact zero divisor has no rational representation:

print(1n / 0n);  // Inf
print(1n \ 0n);  // Inf

let nan = 0n / 0n;
print(nan);         // NaN
print(nan == nan);  // true

Equality, hashing, and ordering

Numeric equality compares exact values across all three modes. Equal values produce the same map or set hash. Andy C++ converts each finite Float to its exact binary rational value for this comparison, so decimal approximation does not make values equal:

print(1 == 1.0);                     // true
print(1.0 == 1n);                    // true
print(1n == 1 + 0i);                 // true
print(0.1 == 1n / 10n);              // false
let numbers: %{Any} = %{1, 1.0, 1n, 1 + 0i};
print(numbers.len());                // 1

Positive and negative zero compare equal. All NaN values compare equal and hash alike. Real scalars sort in this order:

-Inf < finite values < Inf < NaN

Complex values keep lexicographic ordering. The comparison checks the real part, then the imaginary part:

print((2 + 0i) > (1 + 100i));  // true
print((1 + 2i) < (1 + 3i));    // true

Integer-only operators

Only Int supports bitwise operations and shifts:

OperatorFunction
|Bitwise OR
&Bitwise AND
~Binary XOR or unary NOT
>>Checked right shift
<<Checked left shift

Use Int values for list indices, range bounds, and APIs that take counts. Convert with int(value) when the value fits in i64.

String

In Andy C++ a String is a mutable list of characters. Characters don’t have their own type in the language so if you iterate over a string you get strings of length 1. Just like in Rust strings are guaranteed (and required) to be valid UTF-8. This means that you can’t store arbitrary binary data in a String.

Indexing into a String counts characters (UTF-8 codepoints, like Rust’s char) rather than bytes.

let string = "I ❤ Andy C++";
print(string[2]);  // ❤
print(string[4]);  // A

The advantage is that it’s a bit easier to guess that A is at index 4 in the example above. The downside is that depending on which heart you’re using there might be an invisible Variation Selector after the heart which messes everything up. This specific behavior will probably change in the future.

Escape sequences

Inside a string, a backslash starts an escape: \n is a newline, \t a tab, \r a carriage return, \0 a null character, \\ a backslash and \" a double quote. \u{...} is the Unicode character with the hexadecimal code point between the braces:

print("caf\u{e9} \u{1F600}");  // café 😀

Raw strings

You may also define raw strings using this syntax borrowed from rust.

let string = r#"raw string with "" lots of "" quotes"#;
print(string);  // raw string with "" lots of "" quotes

and even

let string = r###"raw string with r#"stop doing this"#"###;
print(string);  // raw string with r#"stop doing this"#

Repeating

repeat(string, n) gives the string n times over:

print("ab".repeat(3));  // ababab

Removing prefixes and suffixes

strip_prefix(string, prefix) and strip_suffix(string, suffix) remove one matching prefix or suffix. strip_circumfix(string, prefix, suffix) removes both. Each function returns a new string, leaving the original string unchanged, and it’s an error when the pattern doesn’t match.

print("foobar".strip_prefix("foo"));         // bar
print("foobar".strip_suffix("bar"));         // foo
print("[hello]".strip_circumfix("[", "]"));  // hello
print("foofoo".strip_prefix("foo"));         // foo
print("[]".strip_circumfix("[", "]") == "");  // true

A mismatch is an error:

"hello".strip_prefix("x");  // error: "hello" doesn't start with "x"

The ? variants return an Option instead of failing:

print("foobar".strip_prefix?("foo"));         // Some("bar")
print("hello".strip_prefix?("x"));            // None
print("aaa".strip_circumfix?("aa", "aa"));    // None

Splitting once

split_once(string, pattern) splits a string at the first occurrence of pattern into the parts before and after it. It’s an error when pattern doesn’t occur, and split_once? returns None instead:

let (key, value) = "port=80".split_once("=");
print(key);                       // port
print("a=b=c".split_once("="));   // ("a","b=c")
print("abc".split_once?("="));    // None

Operators

OperatorFunction
++concatenate two strings
<>coerces both operands into strings before concatenating them
incheck if left operand is a substring of right operand
==Equality
!=Inequality
>Greater (lexicographically)
<Less (lexicographically)
>=Greater equals (lexicographically)
<=Less equals (lexicographically)
<=>-1, 0, or 1 (lexicographically)
>=<-1, 0, or 1 (reverse lexicographically)

Note: The in operator checking if the left operand is a substring of the right operand is different from the behavior of in on lists.

Examples

print("foo" <> 3);        // foo3
print(10 <> 5.0);         // 105.0
print("oo" in "foobar");  // true
let a = "foo" ++ 3; // Error: No function called '++' found that matches the arguments 'String, Int'

List

Lists are mutable in Andy C++.

let my_list = [1,2,3];

// Values inside a list can be changed
my_list[2] = 4;
print(my_list);           // [1,2,4]

// You can add elements to the end of a list
my_list.push(99);
print(my_list);           // [1,2,4,99]

// Remove and return the last element of the list
let element = my_list.pop();
print(element, my_list);  // 99 [1,2,4]

The values of a list share one type. To put values of different types in one list, like [1, "a"], annotate it: let xs: [Any] = [1, "a"]; (see Values of different types).

Indexing

Lists, strings, and tuples also support negative indexes. Negative indexes count from the end.

let my_list = [1,2,3,4,5,6,7,8,9];
print(my_list[-1]);  // 9

Element accessors

Besides the [] operator, lists provide four element accessor functions. They differ on two axes: whether negative indexes are allowed, and what happens when the index is out of bounds.

functionindexout of bounds
getnon-negative only (negative is an error)error
get?non-negative only (negative is an error)None
indexsigned; negatives wrap from the enderror
index?signed; negatives wrap from the endNone
let my_list = [10, 20, 30];

print(my_list.get(0));      // 10
print(my_list.get?(9));     // None
print(my_list.index(-1));   // 30
print(my_list.index?(-9));  // None

index works like the [] operator, and index? gives None instead of an error.

First and last

first and last give the first and last element of a list (or any sequence), and with a function, the first and last element the function gives true for. Their ? forms give None where they would fail:

let numbers = [1, 4, 5, 8, 9];
print(numbers.first, numbers.last);                // 1 9
print(numbers.first(fn(x) => x % 2 == 0));         // 4
print(numbers.last(fn(x) => x % 2 == 0));          // 8
print(numbers.first?(fn(x) => x > 10), [].last?);  // None None

Runs

chunk_by splits a list (or any sequence) into runs of equal neighbours, and with a function, into runs of neighbours the function gives true for:

print([1, 1, 2, 1, 1].chunk_by());                         // [[1,1],[2],[1,1]]
print([1, 2, 3, 5, 6].chunk_by(fn(a, b) => b == a + 1));  // [[1,2,3],[5,6]]

To group equal elements wherever they are, rather than only neighbours, use group_by on maps.

Slicing

Use ranges to slice lists. Ranges can be inclusive or exclusive. Negative indices count from the end of the list.

let my_list = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];

// Exclusive range: 3 to 6 (does not include index 6)
print(my_list[3..6]);    // [30,40,50]

// Inclusive range: 3 to 6 (includes index 6)
print(my_list[3..=6]);   // [30,40,50,60]

// Negative indices: Counting from the end of the list
print(my_list[-3..-1]);  // [80,90]

A range whose start lands after its end (for example my_list[6..3]) is out of bounds and raises an error rather than returning a reversed or empty slice. This holds for lists, strings, tuples and deques alike.

Operators

OperatorFunction
++Concatenation
<>Coerce operands into strings and concatenate
inChecks if an element is present in the list
not inChecks if an element is not present in the list
==Equality
!=Inequality
>Greater (lexicographically)
<Less (lexicographically)
>=Greater equals (lexicographically)
<=Less equals (lexicographically)

Tuple

Tuples are similar to lists, but you cannot change their elements after you create them.

let my_tuple = (1,2,3);

// You can access elements using indexing
print(my_tuple[0]);  // 1

// You may also iterate over tuples
for item in my_tuple {
  print(item);
}
let my_tuple = (1,2,3);

// Tuples are immutable, so assignment fails
my_tuple[0] = 99; // ERROR

The elements of a tuple can have different types. An index written as a number, like t[1] or t[-1], gives that element with its own type. An index in a variable, like t[i], could pick any of them, so it gives an Any that you have to cast: cast::<Int>(t[i]).

let point = ("origin", 0, 0);
let name: String = point[0];
let y: Int = point[-1];
print(name, y);  // origin 0

Create a 1-element tuple by adding a trailing comma:

print((1,).len());  // 1

Operators

Like lists, tuples support ++, in, not in, ==, !=, <> and the comparisons <, <=, > and >=. ++ puts two tuples together into a new one:

let point = (1, "a");
print(point ++ (true,));  // (1,"a",true)

Other operators work on each element, as described below.

Vectorization

Operators broadcast element-wise over tuples. Both arguments must be tuples of the same length, or one side may be a scalar that broadcasts:

print((1, 2) + (3, 4));           // (4,6)
print(-(1, 2, 3));                // (-1,-2,-3)
print((1, 2) + 5);                // (6,7)

This only works for operators, not for function calls: f((1, 2, 3)) passes the whole tuple to f. Comparisons like < and <=> don’t work element by element either: they compare two tuples as a whole and give one result:

print((1, 2) < (1, 3), (2, 0) <=> (1, 9));  // true 1

Tuples of different lengths are an error:

(1, 2, 3) + (4, 5)  // ERROR: no overload accepts those argument types

Unit

In Andy C++ the unit type is written as () and indicates that there is no value. Statements evaluate to the unit type for instance when a semicolon is used after the last value.

let x = 1;
let y = 2;

let result = if x == y {
  5 + 5;
} else {
  10 + 10;
};

// Result is unit because the last expression in the blocks has a semicolon
print(result == ());  // true

Unit is also a 0-length tuple:

print((1,2,3)[0..0] == ());  // true

The language does not have null or nil.

Map and Set

Andy C++ does not have separate map and set types. A set is a map whose values all use the unit type ().

Set

Because { is already used to create a block expression, Andy C++ uses %{ to create a set or map.

let my_set = %{5, 3, 2, 1};
print(3 in my_set);  // true

Map

let my_map = %{
    "apples": 60,
    "oranges": 22,
    "bananas": 0,
};
print(my_map["apples"]);  // 60

Reading a key the map doesn’t have is an error. get? gives an Option instead, and remove? takes the entry out and gives its value:

let stock = %{"apples": 60};
print(stock.get?("pears"));                // None
print(stock.get?("pears").unwrap_or(0));   // 0
print(stock.remove?("apples"), stock);     // Some(60) %{}

clear empties a map or a set.

Default values

let defaultdict = %{:0};

// Missing keys in defaultdict default to 0
print(defaultdict[10]);  // 0

// You can also mutate a missing key this way
defaultdict[33] += 7; // adds 7 to 0 and associates it to key 33
print(defaultdict[33]);  // 7

Map and set types

The type of a map is written like the map itself, with the types of its keys and values: %{String: Int}. A set leaves out the values: %{Int}.

let stock: %{String: Int} = %{};
let seen: %{Int} = %{};
stock["apples"] = 60;
seen.insert(3);
print(stock, seen);  // %{"apples": 60} %{3}

The keys of a map share one type, and so do its values. To store values of different types, like %{"a": 1, "b": "two"}, annotate the map: let m: %{String: Any} = … (see Values of different types).

Note: Lists are copied by reference. If you use [] as a dictionary default value, every missing key gets the same list instance. Use a default function instead.

Default functions

You can also specify the default value as a function. Andy C++ evaluates that function each time it needs a new value. Use this form when each missing key needs its own list.

let dd = %{:fn() => []};
dd["foo"].push(3);
dd["bar"].push(4);

print(dd["foo"]);  // [3]
print(dd["bar"]);  // [4]

You can still use a function itself as the default value:

let dd = %{:fn() => fn(x) => x * x};
print(dd["test"](5)); // 25

Iteration

Iterate over a map with a for loop. Each element is a (key, value) tuple:

let m = %{"a": 1, "b": 2};
for (k, v) in m {
    print(k, v);
}

A set iterates as its elements, and so do the functions that take any kind of sequence:

let primes = %{2, 3, 5};
for p in primes {
    print(p);
}
print(primes.sum());  // 10

Iteration order is unspecified. Maps are hash-based, so keys may appear in any order.

Keys are snapshotted at the start of the loop. A key added to the map during the loop isn’t visited, and a key removed before the loop gets to it is skipped. Values read during iteration do reflect changes to existing keys. Functions that take a function, like map and filter, go over a map the same way.

Grouping

group_by(seq, key) makes a map from each key the function gives to the elements with that key, in the order they came:

let words = ["apple", "bean", "avocado"].group_by(fn(word) => word[0]);
print(words["a"]);  // ["apple","avocado"]
print(words["b"]);  // ["bean"]

Operators

OperatorFunctionSupport augmented assignment [1]Augmentable with not
|Uniontruefalse
&Intersectiontruefalse
-Difference: the keys of lhs that aren’t in rhstruefalse
~Symmetric differencetruefalse
inTest if lhs is part of the Set or a key in the Maptruetrue
==Equalityfalsetrue
!=Inequalityfalsetrue

Note: The union, intersection, difference and symmetric difference operations retain the default value from the left operand

Note: The equality operations ignore the default value

is_subset, is_superset and is_disjoint compare the keys of two maps or sets:

let small = %{1, 2};
print(small.is_subset(%{1, 2, 3}));  // true
print(small.is_disjoint(%{3}));      // true

Range

A range is the Ints from one number to another. a..b stops before b, and a..=b includes it:

print([x for x in 1..4]);   // [1,2,3]
print([x for x in 1..=4]);  // [1,2,3,4]

A range without an end, a.., goes on counting until you stop the loop:

for n in (10..) {
    if n * n > 200 {
        print(n);  // 15
        break;
    }
}

map, filter and the like give a lazy sequence for a range without an end.

A range is a value

Looping over a range doesn’t use it up, so you can keep one in a variable and use it as often as you like:

let digits = 0..10;
print([d for d in digits].sum());  // 45
print([d for d in digits].sum());  // 45

Asking whether a number is in a range, or how many numbers it holds, doesn’t loop over it:

let valid = 1..=12;
print(7 in valid, 13 in valid);  // true false
print(len(valid));               // 12

Two ranges are equal when they hold the same numbers, and a range can be a map key:

print((1..=3) == (1..4));  // true

let names = %{1..=3: "low", 4..=6: "high"};
print(names[1..4]);  // low

Ranges also select a part of a list or string; see slices.

Lazy

Functions like map and filter make a new list straight away:

let squares = [1, 2, 3, 4].map(fn(x) => x * x);
print(squares);  // [1,4,9,16]

A lazy sequence makes its elements only when something reads them. Write .lazy to get one, and the same functions add a step to it instead of making a list:

let squares = [1, 2, 3, 4].lazy.map(fn(x) => x * x);
print(squares);       // lazy([1,2,3,4]).map(<fn ?>)
print(squares.list);  // [1,4,9,16]

Printing a lazy sequence shows what it will do, not its elements, as making them may call your functions.

Stopping early

A lazy sequence is useful when you don’t need every element. Here first stops at the first square over 5, so map runs only three times:

let checked = [];
let square = [1, 2, 3, 4, 5]
    .lazy
    .map(fn(x) { checked.push(x); x * x })
    .first(fn(x) => x > 5);
print(square, checked);  // 9 [1,2,3]

Picking elements

enumerate, take, skip and combinations only pick elements, without calling a function of yours, so they give a lazy sequence for any sequence, without .lazy. A for loop over one makes no list:

for (i, name) in ["Ann", "Bob"].enumerate() {
    print(i, name);
}
// 0 Ann
// 1 Bob
print([1, 2, 3].combinations(2).list);  // [[1,2],[1,3],[2,3]]

Ranges without an end

A range without an end, 1.., never ends, so map and filter give a lazy sequence for one without .lazy. Take as many elements as you need:

let multiples_of_7 = (1..).map(fn(x) => x * 7).take(4);
print(multiples_of_7.list);  // [7,14,21,28]

Reading it again runs it again

A lazy sequence doesn’t keep its elements. Every for loop, and every function that reads it, makes them again:

let loud = [1, 2].lazy.map(fn(x) { print("making", x); x });
print(loud.sum());
print(loud.sum());
// making 1
// making 2
// 3
// making 1
// making 2
// 3

If you need the elements more than once, make them into a list with list, and use the list.

Where it goes

A for loop, a comprehension and these functions read a lazy sequence: list, set, sorted, sum, product, min, max, join, count, first, first?, last, last?, any, all, none, first_or, fold, reduce and in. These add a step to one: map, filter, flat_map, enumerate, take, skip, take_while, skip_while and combinations. repeat(x) is a lazy sequence that gives x without end, and repeat(x, n) a list of n of them, or for a string the string n times over.

Other functions that take a list don’t take a lazy sequence. Make it into a list first:

let pairs = list([1, 2, 3].lazy.map(fn(x) => x * 10)).pairwise();
print(pairs);  // [(10,20),(20,30)]

Deque

A double-ended queue backed by Rust’s VecDeque.

This is very useful for implementing algorithms like BFS.


let queue = Deque();
queue.push_back((0, 0));

while not queue.is_empty() {
    let cur = queue.pop_front();
    print(cur);  // (0,0)

    // etc.
}

MinHeap & MaxHeap

A data structure backed by Rust’s BinaryHeap that keeps elements in sorted order. This is very useful when implementing algorithms like Dijkstra and A*.

Iterating

A heap is a sequence of its elements in the order it gives them: smallest first for a MinHeap, largest first for a MaxHeap. A for loop, sum, map, sorted and the other functions that take a sequence all see that order, and len counts the elements:

let heap = MaxHeap();
for x in [2, 3, 1] {
    heap.push(x);
}
print(heap.list(), heap.len(), heap.pop());  // [3,2,1] 3 3

Function

Functions are first-class values in Andy C++. You can store them in variables, pass them as arguments, and call them like any other value.

Named functions

Declare named functions with fn.

fn my_function(input) {
  if input == something {
    return foo;
  }

  // do some more stuff

  // implicitly return the last expression in the block
  bar
}

Function declarations are not hoisted. Define a function before you call it.

foo(); // ERROR: Identifier foo has not previously been declared

fn foo() {
  print("Hello, World!");
}

A function declared with fn can’t be replaced. If you want a variable that holds a function, declare it with let:

let scale = fn(x) { x * 2 };
scale = fn(x) { x * 10 };      // fine
print(scale(3));               // 30

Functions close over their environment.

let x: [Int] = [];

fn my_function(n) {
  // add argument n to x
  x.push(n);

  // return the sum of x
  x.sum()
}

print(my_function(10));  // 10
print(my_function(5));   // 15
print(x);                // [10,5]

A function captures the variable itself, not a copy of its value. It sees later assignments, and its own assignments are seen outside:

let count = 0;
let increment = fn() { count += 1; };
increment();
increment();
print(count);  // 2

Each loop iteration has its own variables, so a function made in a loop keeps the values of the iteration that made it:

let getters = [];
let i = 0;
while i < 3 {
    let j = i;
    getters.push(fn() { j });
    i += 1;
}
print([g() for g in getters]);  // [0,1,2]

Anonymous functions

Anonymous functions let you write inline function values.

// An anonymous function that adds its operands together
let my_function = fn(a, b) { a + b };

print(my_function(5, 3));  // 8

fn foo() {
    "whatever"
}

let my_variable = foo; // Store the foo-function in a variable
print(my_variable());      // whatever

map applies an anonymous function to each element in the list:

let my_list = [x for x in 1..10];
let out = my_list.map(fn(x) => x * 10);
print(out);  // [10,20,30,40,50,60,70,80,90]

Arrow syntax

Use the fat arrow => for functions that return a single expression.

// Works for anonymous functions
let my_function = fn(a, b) => a + b;
print(my_function(1, 2));  // 3

// Also works for named functions
fn foo() => "whatever";
print(foo());              // whatever

// Note that commas have a very low precedence in this example x is a tuple (function, 3)
let x = fn(y) => y, 3;
print(x[1]);               // 3

// If you want to return a tuple from a function written in this way you must use parentheses
let x = fn(y) => (y, 3);
print(x(1));               // (1,3)

Type annotations

Parameters and return values can have type annotations, just like let bindings. They are optional, so you can annotate as much or as little as you like:

fn greet(name: String) -> String => "hello " <> name;

fn add(x: Int, y: Int) -> Int {
    x + y
}

fn count(xs) -> Int => len(xs);

print(greet("world"));  // hello world
print(add(1, 2));       // 3
print(count([1, 2]));   // 2

If the body returns a value that doesn’t fit the return type, you get an error before the program runs:

fn bad() -> Int { "hello" }   // error: mismatched types

A function that returns values of different types, like a String in one place and an Int in another, has to say that it returns Any:

fn size(n: Int) -> Any {
  if n > 9 { return "big"; }
  n
}
print(size(3), size(10));  // 3 big

Function types

The type of a function is written fn(A, B) -> C: it takes an A and a B and returns a C. Without -> … the function returns ():

let twice: fn(Int) -> Int = fn(x: Int) => x * 2;
let log: fn(String) = fn(s: String) { print(s); };

fn apply(f: fn(Int) -> Int, x: Int) -> Int { f(x) }
fn make_adder(n: Int) -> fn(Int) -> Int { fn(x: Int) => x + n }

print(apply(twice, 4));           // 8
print(apply(make_adder(10), 1));  // 11

You rarely need to annotate the parameters of an anonymous function. They get their types from where the function is used:

let shout: fn(String) -> String = fn(s) => s ++ "!";   // s is a String
print(shout("hi"));  // hi!

let tens = [3, 1, 2].map(fn(x) => x * 10);             // x is an Int
print(tens);         // [30,10,20]

When nothing says what a parameter is, annotate it, as in fn(x: Int) => x + 1.

Generic functions

A function declared with fn takes any argument that its body can work with. You don’t have to say so:

fn inc(x) => x + 1;
print(inc(1), inc(2.5));               // 2 3.5

fn apply(f, x) => f(x);
print(apply(abs, -1));                 // 1
print(apply(fn(s) => s ++ "!", "hi"));  // hi!

Calling it with an argument the body can’t use is an error before the program runs, and the error points at the line in the body that can’t take it:

fn inc(x) => x + 1;
inc("a");  // error: No function called '+' found that matches the arguments 'String, Int'

To take a value of any type at all, annotate the parameter with Any. Inside the function you can print it or compare it, but to use it as something else you have to cast it:

fn show(x: Any) => "got " <> x;
print(show(1), show("a"));  // got 1 got a

Type parameters and type arguments

To say that two values have the same type, whatever it is, name the type in angle brackets after the function’s name. T stands for any type, and the same type everywhere T is written:

fn first<T>(xs: [T], fallback: T) -> T {
    if xs.len() > 0 { xs[0] } else { fallback }
}
print(first([3, 4], 0));    // 3
print(first([], "none"));   // none

A call works out what T is from its arguments. To say it yourself, write the type after the name and ::. These are type arguments, and they go in the order the function declares its type parameters:

fn pair<A, B>(a: A, b: B) -> (A, B) { (a, b) }
print(pair::<Int, String>(1, "x"));   // (1,"x")

fn id<T>(x: T) -> T { x }
print(id::<Float>(1));                // 1.0

Built-in functions take type arguments too. ndc docs shows their type parameters in order, as in map<T, U>:

print([1, 2].map::<Int, String>(fn(x) => x.string()));   // ["1","2"]

The type arguments come before the call’s parentheses, so id::<Int> without a call is the function itself:

fn id<T>(x: T) -> T { x }
let f = id::<String>;
print(f("hi"));   // hi

Recursion

A function can call itself. Calls can go a million deep. A program that goes deeper stops with an error, as that usually means a function calls itself without end:

fn forever(n) => forever(n + 1);
forever(0)
// error[vm]: calls go more than 1000000 deep, which usually means a function calls itself without end

Function overloading

A name can refer to several functions, called overloads, as long as they differ in their number of parameters or their parameter types:

fn add(n) { n + 1 }
fn add(x, y) { x + y }

print(add(9));     // 10
print(add(8, 4));  // 12

A call uses the overload whose parameters fit its arguments. When several fit, the most specific one wins:

fn describe(x: Int) { "int" }
fn describe(x: String) { "string" }
fn describe(x) { "something else" }

print(describe(1));    // int
print(describe("a"));  // string
print(describe([1]));  // something else

Two overloads with the same parameter types are an error. Parameter names don’t count:

fn foo(a) { a + 1 }
fn foo(b) { b + 2 }   // error: Illegal redefinition of function 'foo' with parameters (Any)

An overloaded function as a value

You can pass a function by its name, as in xs.map(abs). When the name has several overloads, Andy C++ picks the one that fits where it’s used. Where nothing says which one you mean, add a function type:

print([-1.5, 2.5].map(abs));     // [1.5,2.5]

let by_pattern: fn(String, String) -> [String] = split;
print(by_pattern("a:b", ":"));   // ["a","b"]

Variables with the name of a function

A variable hides the functions with the same name. A method call, like "test".len(), only looks at functions, so it still finds them:

let len = 300;
print(len);              // 300
print("test".len());     // 4
let len = 300;
len("test");     // ERROR: The variable 'len' is Int, which can't be called

Method call syntax

In Andy C++, you can call a function as a method on its first argument. You get method-style syntax without defining member functions.

fn add(x, y) {
  return x + y;
}

// Normal function call
print(add(3, 5));  // 8

// Method-like syntax
print(3.add(5));   // 8

Both forms do the same thing, except that a method call only looks among functions: a variable named add is skipped.

Implicit call

You can also omit () when you call a 0-ary function.

let input = "some text\nsome more text";
let lines = input.lines;
print(lines);  // ["some text","some more text"]

Struct

Structs are user-defined record types: a named collection of typed fields.

struct Point {
    x: Int,
    y: Int,
}

let p = Point(1, 2);
print(p.x);  // 1

p.y = 20;
print(p);    // Point {x: 1, y: 20}

Declaring a struct

A declaration names the struct and lists its fields. Every field requires a type annotation, and a trailing comma after the last field is allowed. A struct may have zero fields.

struct Person {
    name: String,
    age: Int,
    locations: [String],
}

struct Marker { }

print(Person("Ada", 36, ["London"]));  // Person {name: "Ada", age: 36, locations: ["London"]}
print(Marker());                       // Marker {}

Struct names are scoped like variables: a struct declared inside a function or block can only be used there. Declaring two structs with the same name in the same scope is an error:

struct Point { x: Int }
struct Point { y: Int } // ERROR: Illegal redefinition of struct 'Point'

Constructing instances

Declaring a struct binds a constructor function with the same name. It takes the field values positionally, in declaration order.

struct Point { x: Int, y: Int }

let p = Point(1, 2);
print(p);  // Point {x: 1, y: 2}

Passing the wrong number of arguments, or arguments of the wrong type, is an error before the program runs:

struct Point { x: Int, y: Int }
Point("x", 2); // ERROR: No function called 'Point' found that matches the arguments 'String, Int'

Field access

p.x reads the field x from p. Declaring a struct also declares a function for each field, and p.x is the method call x(p), so these are all the same:

struct Point { x: Int, y: Int }
let p = Point(1, 2);

print(p.x);    // 1
print(x(p));   // 1
print(p.x());  // 1

Because these are ordinary functions, you can pass them to other functions:

struct Point { x: Int, y: Int }
let points = [Point(1, 10), Point(2, 20)];

print(points.map(x));                // [1,2]
print(points.map(fn (p) => p.x));    // [1,2]

// The constructor is a function value too.
struct Wrap { v: Int }
print([1, 2, 3].map(Wrap));          // [Wrap {v: 1},Wrap {v: 2},Wrap {v: 3}]

Two structs can have a field with the same name:

struct Foo { size: Int }
struct Bar { size: Int }

print(Foo(1).size);   // 1
print(Bar(10).size);  // 10

To call a function stored in a field, put parentheses around the field: (s.f)() reads the field and calls what it holds, while s.f() is the method call f(s).

struct Callback { f: fn(Int) -> Int }
let cb = Callback(fn (a) => a * 2);

print((cb.f)(21));  // 42
struct Callback { f: fn(Int) -> Int }
let cb = Callback(fn (a) => a * 2);

cb.f(21);    // ERROR: this is method-call syntax for `f(cb, 21)`

Field assignment

p.x = value writes to a field. The value must fit the field’s declared type:

struct Point { x: Int }
let p = Point(1);

p.x = "ten";   // ERROR: mismatched types: found String but expected Int

Augmented assignment works on fields too:

struct Counter { hits: Int }
let c = Counter(1);

c.hits += 4;
print(c.hits);  // 5

Reference semantics

Struct instances are passed by reference, like lists and maps (see Memory Management). Assigning an instance to another variable aliases it rather than copying it:

struct Point { x: Int, y: Int }

let a = Point(1, 2);
let b = a;
b.x = 99;

print(a.x);  // 99

Use clone for an independent instance (nested containers are still shared, like cloning a list of lists) or deepcopy to duplicate nested mutable state as well:

struct Point { x: Int, y: Int }
let a = Point(99, 2);

let c = clone(a);
c.x = 1;
print(a.x);  // 99
print(c.x);  // 1

Equality and hashing

Instances of the same struct are equal when their fields are equal. Instances of different structs are never equal, even when their fields match.

struct Foo { v: Int }
struct Bar { v: Int }

print(Foo(1) == Foo(1));  // true
print(Foo(1) == Foo(2));  // false
print(Foo(1) == Bar(1));  // false

Instances are hashable, so they work as map keys and set members:

struct Point { x: Int, y: Int }

let visited = %{Point(0, 0): true};
print(visited[Point(0, 0)]);  // true

Structs and JSON

json_encode rejects structs, because the struct type would be lost: a JSON object decodes back to a map, not a struct. Use json_encode_lossy to encode an instance as a JSON object with the field names as keys.

struct Point { x: Int, y: Int }

print(json_encode_lossy(Point(1, 2)));  // {"x":1,"y":2}
json_encode(Point(1, 2));                // ERROR: cannot convert a struct to JSON

Current limitations

  • Constructors are positional only; there is no named-field or default-value syntax.
  • Structs do not take generic parameters: Point<Int> is an error.
  • A struct can’t refer to itself in its own fields, so struct Node { next: Option<Node> } is an error.

Control flow

Control flow in Andy C++ uses expressions and keywords instead of punctuation-heavy syntax. This section covers branching, loops, and the lazy logical operators that often appear in conditions.

If/else

If-statements are very similar to how they are in Go and Rust. You don’t need parentheses around the conditions but braces around the body are required. The condition has to be a Bool: write if count > 0, not if count.

let x = 3;
let y = 4;

if x == 3 {
  print("x is three");
} else if y == 4 {
  print("y is four");
} else {
  print("neither x is three or y is four");
}

Expressions

Just like in Rust they are expressions and can be used to return a value when you omit the semicolon at the end of the last statement in the block.

let n = 5;
let x = if n > 0 {
  1
} else if n == 0 {
  0
} else {
  -1
};
print(x);  // 1

Both branches have to give a value of the same type. Branches of different types, like if c { 1 } else { "a" }, are an error unless you store the result as an Any: let x: Any = if c { 1 } else { "a" }; (see Values of different types).

An if without an else has no value when the condition is false, so its value is always ():

let c = true;
let x = if c { 1 };
print(x == ());  // true

While loop

Like in every other language a while loop will run as long as a condition is true. A while loop is an expression that always evaluates to the unit value ().

let n = 1;

while n <= 100 {
  if n % 15 == 0 {
    print("fizzbuzz");
  } else if n % 3 == 0 {
    print("fizz");
  } else if n % 5 == 0 {
    print("buzz");
  } else {
    print(n);
  }

  n += 1;
}

For loop

Start with a basic for loop:

for n in 1..=100 {
  if n % 15 == 0 {
    print("fizzbuzz");
  } else if n % 3 == 0 {
    print("fizz");
  } else if n % 5 == 0 {
    print("buzz");
  } else {
    print(n);
  }
}

You can loop over several sequences in one loop:

let drinks = ["Coffee", "Tea", "Juice"];
let desserts = ["Cake", "Pie", "Ice Cream"];

// Print all combinations of drinks and desserts
for drink in drinks, dessert in desserts {
  print(drink <> " and " <> dessert);
}

You can also add one or more guards. This example finds all pairs from 1..10 with an even sum.

for x in 1..10, y in 1..10, if (x + y) % 2 == 0 {
  print(x, y, "is even");
}

For comprehensions

You can use the same syntax in a list comprehension.

// Produce a series of perfect squares
let perfect_squares = [x * x for x in 1..=10];

print(perfect_squares);  // [1,4,9,16,25,36,49,64,81,100]

The earlier example can also produce pairs:

let pairs_with_even_sum = [x, y for x in 1..10, y in 1..10, if (x + y) % 2 == 0];
print(pairs_with_even_sum[0..4]);  // [(1,1),(1,3),(1,5),(1,7)]

Changing what you loop over

A loop over a list reads it as it is when it gets to each element, so elements you add during the loop are visited too:

let xs = [1, 2, 3];
for x in xs {
    if x < 3 { xs.push(x * 10); }
}
print(xs);  // [1,2,3,10,20]

Functions that take a function, like map and filter, go over a list the same way. A loop that adds an element every time it gets to one never ends.

Logical operators

Andy C++ uses the keywords and, or, and not for logical operators. If you are coming from Rust, write and and or instead of && and ||.

let has_input, failed, timed_out, disconnected = true, false, false, true;

let ready = has_input and not failed;
let retry = timed_out or disconnected;
print(ready, retry);  // true true

Short-circuiting

and and or are lazy. Andy C++ evaluates the right-hand side only when it needs that value to decide the result.

let x = 0;

true and { x = x + 1; false };
false and { x = x + 1; false };
true or { x = x + 1; false };
false or { x = x + 1; false };

print(x);  // 2

false and ... stops at false, and true or ... stops at true.

Both sides have to be Bools. A number, a list or an Option isn’t true or false by itself, so using one there is an error, just like in the condition of an if or a while:

let count = 3;
if count { print("some"); }
// error[analysis]: mismatched types: found Int but expected Bool

Precedence

and binds tighter than or.

print(true or true and false);  // true
print(false and true or true);  // true

That means Andy C++ reads those expressions as:

print(true or (true and false));  // true
print((false and true) or true);  // true

Bitwise operators

Boolean values also support the non-lazy operators &, |, and ~.

Use and and or when you want short-circuiting. Use & and | when you need both sides to run.

Memory Management

Andy C++ uses reference counting to manage memory. Every value that lives on the heap (strings, lists, maps, closures, etc.) is wrapped in a reference-counted pointer. When the last reference to a value is dropped, it is freed immediately — there is no garbage collector and no pause times.

Reference Cycles

Reference counting cannot detect cycles: two or more values that refer to each other. When a cycle exists, the reference count of each value in the cycle never reaches zero, so the memory is never freed.

There are two common ways to create cycles:

Mutable containers that reference each other

{
    let m: %{String: Any} = %{};
    let n: %{String: Any} = %{};
    m["n"] = n;
    n["m"] = m;
    print(m["n"]["m"] == m);  // true
}
// m and n are out of scope, but each map still holds
// a reference to the other — neither can be freed.

Self-referential closures

A closure that captures a variable which holds a reference back to itself creates a cycle:

{
    let f: fn(Int) -> Int = fn(x) => 0;
    f = fn(x) { if x > 0 { x + f(x - 1) } else { 0 } };
    print(f(3));  // 6
}
// f now holds the closure, and the closure holds
// f, because it captured f to call it.

Practical Impact

For short-lived scripts this is a non-issue — all memory is reclaimed when the process exits. Cycles only become a problem in long-running programs that repeatedly create and discard cyclic structures. If you find yourself in that situation, break the cycle manually by assigning () to one side before the values go out of scope:

m["n"] = ();  // break the cycle

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

Casts

A cast is how you get a value back out of an Any. Anything can go into an Any, but an Any can’t be used where another type is expected (see Getting a value out of an Any):

let value: Any = 5;
value + 1
// error[analysis]: No function called '+' found that matches the arguments 'Any, Int'

cast::<T>(value) says that the value is a T. It checks that while the program runs:

let value: Any = 5;
print(cast::<Int>(value) + 1);  // 6

cast is a function: the type it casts to goes between ::< and >, and the value in the parentheses. Like other functions, it can be called as a method, value.cast::<Int>().

A cast that turns out to be wrong stops the program with an error:

let value: Any = "five";
cast::<Int>(value)
// error[vm]: cannot cast String to Int

A cast only checks the value, it doesn’t convert it, so cast::<Float>(n) is an error when n is an Int. To turn one type into another, use functions like float(n), int(x) and string(x).

Casting a list or a map

A cast checks every element of a list, map or other container:

let values: Any = [1, 2];
let ints = cast::<[Int]>(values);
print(ints.sum());  // 3

A list of Anys needs a cast too before you use a function that wants a list of something more specific, like sum:

let values: [Any] = [1, 2, 3];
print(cast::<[Int]>(values).sum());  // 6

A cast of a list gives you a list of your own. When a variable still holds the list, the cast copies it, so changing one doesn’t change the other:

let values: [Any] = [1, 2];
let ints = cast::<[Int]>(values);
values.push("three");
print(ints);    // [1,2]
print(values);  // [1,2,"three"]

Testing a value’s type with cast?

cast?::<T>(value) is the cast that doesn’t fail: it gives Some(value) when the value is a T, and None when it isn’t.

let value: Any = 5;
print(cast?::<Int>(value));     // Some(5)
print(cast?::<String>(value));  // None

That makes it the way to ask what a value is:

fn describe(value: Any) {
    if cast?::<Int>(value).is_some() {
        "a number"
    } else if cast?::<String>(value).is_some() {
        "some text"
    } else {
        "something else"
    }
}
print(describe(1));    // a number
print(describe("a"));  // some text
print(describe([1]));  // something else

Casting each element with map

cast::<T> without the parentheses is a function that casts what it’s given, so it can be passed to map:

let values: [Any] = [1, 2, 3];
print(values.map(cast::<Int>).sum());  // 6

Method call syntax

In Andy C++, you can call a function as a method on its first argument. You get method-style syntax without defining member functions.

fn add(x, y) {
  return x + y;
}

// Normal function call
print(add(3, 5));  // 8

// Method-like syntax
print(3.add(5));   // 8

Both forms do the same thing, except that a method call only looks among functions: a variable named add is skipped.

Implicit call

You can also omit () when you call a 0-ary function.

let input = "some text\nsome more text";
let lines = input.lines;
print(lines);  // ["some text","some more text"]

Examples

let l = [50, 40, 20, 40, 10];

// A plain function-call version
let x = reduce(map(sorted(l), fn(x) => x + 5), fn(a, b) => a * b);

// The same code with method call syntax
let y = l.sorted
         .map(fn(x) => x + 5)
         .reduce(fn(a, b) => a * b);

print(x, y);  // 41765625 41765625

Slices

Use ranges to slice lists. Ranges can be inclusive or exclusive. Negative indices count from the end of the list.

let my_list = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];

// Exclusive range: 3 to 6 (does not include index 6)
print(my_list[3..6]);    // [30,40,50]

// Inclusive range: 3 to 6 (includes index 6)
print(my_list[3..=6]);   // [30,40,50,60]

// Negative indices: Counting from the end of the list
print(my_list[-3..-1]);  // [80,90]

A range whose start lands after its end (for example my_list[6..3]) is out of bounds and raises an error rather than returning a reversed or empty slice. This holds for lists, strings, tuples and deques alike.

Memoization

Andy C++ supports memoization through the pure keyword. Mark a function as pure when it has no side effects and returns the same output for the same inputs. Andy C++ can then cache and reuse previous results.

Syntax

Mark both named and anonymous functions as pure:

pure fn add(x, y) {
    x + y
}

let multiply = pure fn (x, y) { x * y };

print(add(2, 3));       // 5
print(multiply(4, 5));  // 20

Note: The interpreter does not check whether a function is actually pure. You must avoid side effects yourself.

When a result is reused

A pure function remembers its results. When you call it again with the same arguments, it gives back the remembered result instead of running again:

let calls = 0;
pure fn square(n) {
    calls += 1;
    n * n
}
print(square(4), square(4), calls);  // 16 16 1

Arguments are the same when they’re equal with ==, so two separate lists with the same items count as the same argument:

let calls = 0;
pure fn total(xs: [Int]) {
    calls += 1;
    xs.sum()
}
print(total([1, 2, 3]), total([1, 2, 3]), calls);  // 6 6 1

What a pure function can take

The arguments of a pure function have to be plain data: numbers, strings, booleans, None, and lists, tuples, maps, deques, options and structs of those. Functions, lazy sequences, heaps and Anys aren’t allowed:

pure fn apply(f: fn(Int) -> Int, x: Int) => f(x);
// error[analysis]: `apply` is a `pure fn`, which only takes data, but its parameter `f` has type `fn(Int) -> Int`

The remembered result isn’t a copy

Every call that reuses a result gets the very same value. If that value is a list and you change it, later calls see the change:

pure fn empty() -> [Int] => [];
empty().push(1);
print(empty());  // [1]

If you want to change a result, copy it first with clone:

pure fn empty() -> [Int] => [];
let mine = empty().clone();
mine.push(1);
print(empty());  // []

Performance: keep the arguments small

Every call looks at everything in its arguments, so passing a big list or map to a pure function costs time on every call. See Performance for how to avoid that.

Example: Fibonacci Sequence

pure fn fib (n) {
  return if n == 0 {
    0
  } else if n <= 2 {
    1
  } else {
    fib(n-2) + fib(n-1)
  }
}

print(fib(92));  // 7540113804746346429

Reading input

A program can read its input from a file with read_file, or from standard input with read_stdin. Both return the whole input as one string, which you can then split with lines, words or paragraphs.

From a file

read_file takes a path and returns what the file holds:

let text = read_file("numbers.txt");
let total = 0;
for line in text.lines {
    total += int(line);
}
print(total);

A relative path is relative to the directory you run ndc from, not the directory the script is in.

From standard input

read_stdin reads everything on standard input. Save this as sum.ndc:

let total = 0;
for line in read_stdin().lines {
    total += int(line);
}
print(total);

Then give it a file to read with <, or pipe another program’s output into it:

$ printf '1\n2\n3\n' > numbers.txt
$ ndc sum.ndc < numbers.txt
6
$ seq 10 | ndc sum.ndc
55

This keeps the file name out of the program, so the same script runs on any input.

If you leave out < numbers.txt, the program reads what you type instead, until you press Ctrl-D (Ctrl-Z and Enter on Windows).

read_stdin reads all of the input at once, so call it once and keep the result:

let input = read_stdin();
let sections = input.trim().paragraphs;

Tracing

Andy C++ has built-in tracing support for inspecting how the bytecode VM executes your program. Tracing is available when the binary is compiled with the trace feature flag and is controlled via command-line flags on the run subcommand.

cargo run --features trace -- run --trace-print program.ndc

Multiple trace flags can be combined in a single invocation.

Trace modes

--trace-print

Prints every VM instruction to stderr as it is dispatched, with the registers it reads and writes and the corresponding source excerpt. For a loop that adds up square(i):

[VM] 0007 ForRangeNext r2, r0, +7         for i in 1..=3 {↵    total += square(i);↵}
[VM] 0008 GetGlobal r5, g639              total
[VM] 0009 GetGlobal r6, g640              square
[VM] 0010 Copy r7, r0                     i
[VM] 0011 Call r6, 1                      square
[VM] 0000 MulInt r1, r0, r0               *
[VM] 0001 Return r1
[VM] 0012 AddInt r4, r5, r6               total += square(i)
[VM] 0013 SetGlobal g639, r4              total
[VM] 0014 Jump -8                         for i in 1..=3 {↵    total += square(i);↵}

r0 is a register of the running function, g639 a global and +7 how far a jump goes. This is useful for understanding the exact sequence of bytecode operations your program produces; ndc disassemble lists the same instructions without running them.

--trace-histogram

Prints a summary table of how many times each instruction type was dispatched:

--------------------------------------------------
Instruction histogram (42 total)
--------------------------------------------------
  GetGlobal                     7  ( 16.7%)
  SetGlobal                     5  ( 11.9%)
  ForRangeNext                  4  (  9.5%)
  LoadK                         4  (  9.5%)
  ...

--trace-time

Measures cumulative wall-clock time spent per instruction type and prints a summary:

------------------------------------------------------------
Instruction timing (total: 198us)
------------------------------------------------------------
  Call                      125us  ( 63.1%)
  CallNative                 30us  ( 15.3%)
  ...

The time for an instruction is measured from when it starts executing until the next instruction begins.

--trace-span

Renders the source code as a heat map, coloring regions from green (cold) to red (hot) based on how much execution time was spent on the bytecode instructions associated with each source span.

cargo run --features trace -- run --trace-span program.ndc

This gives a visual overview of where your program spends its time. The heat is additive: if a character is covered by multiple overlapping spans (e.g. an expression inside a loop body), all their durations contribute, so hot inner code within a hot loop shows as hotter than the surrounding syntax.

Note: The span-based heat map is a rough profiling aid, not a precise profiler. In particular, recursive function calls can produce misleading results because the function body spans overlap with themselves across call depths, and the timing of Call instructions only measures call-setup overhead rather than the total time spent in the callee.

Building with tracing

Tracing is behind a Cargo feature flag so it has zero cost when not compiled in:

# Without tracing (default) — no overhead
cargo build

# With tracing support
cargo build --features trace

The trace flags only appear in --help when compiled with the feature enabled.

Performance

Most programs run fast without any thought about speed. This page collects the few habits that make a real difference when they don’t.

Keep the arguments of a pure function small

A pure function remembers its results by its arguments. To find an earlier result, every call looks at everything in its arguments, so passing a big list or map to a pure function costs time on every call, even when the result is already known.

If a big value stays the same between calls, such as a grid or a graph, don’t pass it in. Use it from outside the function, so that only the small arguments that change are looked at:

let graph = %{"a": ["b", "c"], "b": ["d"], "c": ["b", "d"], "d": []};

pure fn paths(node) {
    if node == "d" {
        return 1;
    }
    [paths(next) for next in graph[node]].sum()
}

print(paths("a"));  // 3

Written as pure fn paths(graph, node), the same program looks through the whole graph on every call. With a graph of a few hundred nodes, that made one solution ten times slower.

A pure function that uses a value from outside keeps the results it remembered, so only do this with a value that no longer changes once the function is called.

Editor support

Andy C++ ships a language server (LSP) so editors can offer rich feedback as you write .ndc files. If you have Andy C++ isntalled you automatically also have the language server.

You can start the language server like this:

ndc lsp --stdio

Most users do not run this command by hand. Editor integrations either launch it automatically or are configured to run it for .ndc files.

What the language server provides

  • Diagnostics — lexer, parser, and semantic/type errors are reported inline as you type.
  • Inlay type hints — inferred types are shown after let bindings and function parameters, and inferred return types after function signatures. Hints are only shown where you didn’t already write an annotation.
  • Hover — hovering an expression shows its inferred type; hovering a built-in function shows its signature and documentation.
  • Completion — typing . offers functions whose first parameter accepts the receiver’s type (method-call style). General completion offers built-in functions, in-scope variables, and language keywords.
  • Document symbols — an outline of the top-level and nested functions and variable declarations in the file.
  • Go-to-definition — jump from a variable or function usage to its declaration.

VS Code and compatible editors

The Andy C++ extension on Open VSX provides syntax highlighting, all of the language-server features listed above, and a Run Script command that executes the current file in the integrated terminal.

Install it from the Extensions view in editors that use the Open VSX registry. For Microsoft VS Code, download the VSIX file from the Open VSX page and install it with Extensions: Install from VSIX… in the command palette.

The extension launches ndc lsp automatically. If ndc is not on the PATH seen by the editor, set andy-cpp.ndcPath to the full path of the binary.

JetBrains IDEs (RustRover, IntelliJ, …)

JetBrains IDEs are supported without a dedicated plugin, in two independent parts.

Syntax highlighting — the bundled TextMate Bundles plugin can import the VS Code extension directory directly:

  1. Go to Settings → Editor → TextMate Bundles, click +, and select the ext/andy-cpp directory from the repository.
  2. Open a .ndc file — it should highlight immediately. If it renders as plain text, check Settings → Editor → File Types and make sure *.ndc is not claimed by another file type.

Language intelligence — the LSP4IJ plugin connects the IDE to the language server:

  1. Build the binary with cargo build --release, then install LSP4IJ from the plugin marketplace.
  2. Open the Language Servers tool window, click +, and configure a new server:
    • Command: /path/to/andy-cpp/target/release/ndc lsp --stdio
    • In the Mappings tab, add a File name patterns mapping with pattern *.ndc and language id ndc.
  3. Open a .ndc file. The server starts automatically and provides everything listed above. ext/lsp4ij-ndc/template.json in the repository contains the same configuration as a reference.

Neovim

Neovim has a built-in Tree-sitter runtime, so nvim-treesitter is not required. The generated parser is committed to the Andy C++ repository and can be compiled with a C compiler; installing it does not require Node.js or npm.

Clone the repository and run the installer:

git clone --depth 1 https://github.com/timfennis/andy-cpp.git
cd andy-cpp/ext/tree-sitter-andy-cpp
./install.sh neovim

The script supports Linux, the BSDs, and macOS. It installs the parser and queries under ${XDG_CONFIG_HOME:-$HOME/.config}/nvim. Set CC to select a different C compiler.

Add the following to init.lua:

-- Treat .ndc files as the `andy_cpp` filetype.
vim.filetype.add({ extension = { ndc = "andy_cpp" } })

-- Start Tree-sitter highlighting for those buffers.
vim.api.nvim_create_autocmd("FileType", {
  pattern = "andy_cpp",
  callback = function(args)
    pcall(vim.treesitter.start, args.buf, "andy_cpp")
  end,
})

-- Language server (Neovim 0.11+).
vim.lsp.config("ndc_lsp", {
  cmd = { "ndc", "lsp", "--stdio" },
  filetypes = { "andy_cpp" },
  root_markers = { ".git" },
})
vim.lsp.enable("ndc_lsp")

-- Optional: show inlay hints once the server attaches.
vim.api.nvim_create_autocmd("LspAttach", {
  callback = function(args)
    local client = vim.lsp.get_client_by_id(args.data.client_id)
    if client and client.name == "ndc_lsp" then
      pcall(vim.lsp.inlay_hint.enable, true, { bufnr = args.buf })
    end
  end,
})

Run ./install.sh neovim again after updating the grammar or its queries, then restart Neovim. After rebuilding ndc, reload the language server with :LspRestart.

If .ndc is already mapped to a different filetype, omit vim.filetype.add and register the parser for that filetype instead:

vim.treesitter.language.register("andy_cpp", "your_filetype")

Use the same filetype in the autocmd pattern and language-server configuration.

Helix

Helix also has built-in Tree-sitter and LSP support. Add the following to ~/.config/helix/languages.toml (or the equivalent path below XDG_CONFIG_HOME):

[[language]]
name = "andy-cpp"
scope = "source.andy-cpp"
file-types = ["ndc"]
comment-tokens = ["//"]
indent = { tab-width = 4, unit = "    " }
language-servers = ["ndc-lsp"]

[language-server.ndc-lsp]
command = "ndc"
args = ["lsp", "--stdio"]

[[grammar]]
name = "andy-cpp"
source = { git = "https://github.com/timfennis/andy-cpp", rev = "master", subpath = "ext/tree-sitter-andy-cpp" }

From a checkout of the Andy C++ repository, install the parser and queries without Node.js or npm:

cd ext/tree-sitter-andy-cpp
./install.sh helix

The files are installed under ${XDG_CONFIG_HOME:-$HOME/.config}/helix/runtime. Check the setup with hx --health andy-cpp (or helix --health andy-cpp on systems where the binary uses that name).

Other editors

Any editor with an LSP client can use the Andy C++ language server. Configure it to run ndc lsp --stdio for .ndc files with the language id andy-cpp.

Notes

  • The server uses full-document synchronisation and re-analyses on each edit.
  • While the buffer is mid-edit and doesn’t parse, the last successful analysis is retained so hints and dot-completion keep working.

Formatter

ndc fmt formats Andy C++ code in place:

ndc fmt solution.ndc lib/*.ndc

Without files it reads standard input and writes the formatted code to standard output, which is how editors usually call a formatter:

ndc fmt < solution.ndc

With --check it changes nothing, lists the files that aren’t formatted and fails if there are any, which suits a CI job:

ndc fmt --check *.ndc