Learn Nihil

Thirteen short chapters. Every example is a complete program, and the output under it is what it prints. The full reference is SPEC.md.

  1. Hello
  2. Values and types
  3. Conditions and loops
  4. Methods
  5. Arrays, text and the library
  6. Optionals: the value that is not there
  7. Maps
  8. Files and input
  9. Tables on disk
  10. The standard library
  11. Globals and locals: the one rule to remember
  12. Automatic keys
  13. Modeling data

1. Hello

Install Nihil (see the home page), save this as hello.nihil and run nihil run hello.nihil. >> writes to the standard output and adds no line break of its own. nihil hello.nihil compiles it into a native executable, ./hello, instead.

>> "Hello, Nihil!\n";

Output:

Hello, Nihil!

2. Values and types

There are no declarations: a variable is created by its first assignment, and its type comes from the value and stays. The four basic types are INT, FLOAT, BOOL and STRING. Nothing converts implicitly: $ makes text, .n turns an INT into a FLOAT, #f a FLOAT into an INT (and # of a STRING or an ARRAY is its length).

count = 3;                      // INT
price = 2.5;                    // FLOAT
ready = true;                   // BOOL
name = "tea";                   // STRING
total = price * .count;         // .n turns an INT into a FLOAT
>> name + ": " + $count + " x " + $price + " = " + $total + "\n";
>> "whole part: " + $#total + "\n";     // #f turns a FLOAT into an INT
>> "letters: " + $#name + "\n";         // # of a STRING is its length
>> "ready: " + $ready + "\n";           // $ turns a value into text
n = "42".int() || 0;                    // text to number (or 0 if it is not one)
>> $(n + 1) + "\n";

Output:

tea: 3 x 2.5 = 7.5
whole part: 7
letters: 3
ready: true
43

3. Conditions and loops

There are no keywords: the expression before a { decides what the block does. A BOOL makes it an if, and } || … { continues as else if or else. An INT repeats the block that many times. A * before a BOOL makes it a while loop.

x = 7;
x > 10 {
    >> "large\n";
} || x > 5 {
    >> "medium\n";
} || {
    >> "small\n";
}

3 { >> "hip "; }                // an INT before { repeats the block
>> "hooray\n";

i = 1;
* i <= 5 {                      // * is a while loop
    >> $(i * i) + " ";
    i = i + 1;
}
>> "\n";

Output:

medium
hip hip hip hooray
1 4 9 16 25 

4. Methods

A method is a name, parameters and a block. Every parameter has a default, which gives its type, so calls may leave arguments out. : returns a value, and the type of the result is worked out from what is returned.

// every parameter has a default, and the default gives its type
greet(name = "world", times = 1) {
    times { >> "Hello, " + name + "! "; }
    >> "\n";
}

// ":" returns a value
square(n = 0) { : n * n; }

fib(n = 0) {
    n < 2 { : n; }
    : fib(n - 1) + fib(n - 2);
}

greet();
greet("Nihil", 2);
>> $square(12) + " " + $fib(20) + "\n";

Output:

Hello, world! 
Hello, Nihil! Hello, Nihil! 
144 6765

5. Arrays, text and the library

An ARRAY holds values of one type; [0 ; n] makes n copies. The library is called on a value after a ., so its names never take one from your program. $ of an ARRAY of INT makes text from its bytes, which is why show builds the text itself.

// a method to show an ARRAY of INT ($ of an array of INT makes text from its bytes)
show(v = [0]) {
    parts = ["" ; #v];
    i = 0;
    * i < #v { parts[i] = $v[i]; i = i + 1; }
    : "[" + parts.join(", ") + "]";
}

nums = [5, 3, 8, 1];
>> $#nums + " numbers, the first is " + $nums[0] + "\n";
nums = nums + [13];                     // joining makes a new array
>> show(nums.sort()) + "\n";
>> "sum " + $nums.sum() + ", max " + $(nums.max() || 0) + "\n";

zeros = [0 ; 4];                        // 4 copies of 0
zeros[2] = 9;
>> show(zeros) + "\n";
>> $[72, 105] + "\n";                   // bytes to text: Hi

line = "  pear, apple, fig ";
words = line.trim().split(", ");        // an ARRAY of STRING
>> words.sort().join(" < ") + "\n";
>> line.trim().upper() + "\n";
>> $line.contains("apple") + "\n";

Output:

4 numbers, the first is 5
[1, 3, 5, 8, 13]
sum 30, max 13
[0, 0, 9, 0]
Hi
apple < fig < pear
PEAR, APPLE, FIG
true

6. Optionals: the value that is not there

_ is the absence of a value. A variable created with a ? may hold it; an ordinary one never does. The only way to take the value out is || with a fallback, so a missing value can never be used by accident.

// "_" is the value that is not there; a "?" when a variable is created lets it hold _
find(v = [0], x = 0) {
    i = 0;
    * i < #v {
        v[i] == x { : i; }
        i = i + 1;
    }
    : _;                                // so find returns INT?
}

nums = [5, 8, 13];
at? = find(nums, 8);
>> at;                                  // an optional prints its value, or _
>> "\n";
at = find(nums, 99);
at == _ { >> "99 is not there\n"; }
pos = find(nums, 13) || -1;             // || takes the value, or the fallback
>> "13 is at " + $pos + "\n";
n = "12x".int() || 0;                   // the library returns optionals too
>> $n + "\n";

Output:

1
99 is not there
13 is at 2
0

7. Maps

A MAP holds values by key, in memory. Reading a key gives an optional, because the key may not be there; assigning _ deletes it.

age = {"ana": 30, "bob": 25};
age["carla"] = 41;                      // adds or replaces
age["bob"] = _;                         // deletes
>> $#age + " people\n";
>> "ana is " + $(age["ana"] || 0) + "\n";
>> "dan is " + $(age["dan"] || 0) + "\n";   // m[k] is _ when the key is not there

// counting words
counts = {"": 0 ; 16};                  // an empty map of STRING to INT
words = "the cat and the hat and the bat".split(" ");
i = 0;
* i < #words {
    w = words[i];
    counts[w] = (counts[w] || 0) + 1;
    i = i + 1;
}
keys = counts.keys().sort();
i = 0;
* i < #keys { >> keys[i] + "=" + $(counts[keys[i]] || 0) + " "; i = i + 1; }
>> "\n";

Output:

2 people
ana is 30
dan is 0
and=2 bat=1 cat=1 hat=1 the=3 

8. Files and input

@ reads a whole file, @>> replaces it atomically and @+>> appends to it. @? gives _ instead of an error when the file is not there. << reads a line from the input into a variable of any basic type. (The output below is with Ana typed as the input.)

@>> "notes.txt", "first line\n";        // write a file (atomically)
@+>> "notes.txt", "second line\n";      // append to it
text = @ "notes.txt";                   // read it whole
lines = text.trim().split("\n");
>> $#lines + " lines; the last: " + lines[#lines - 1] + "\n";
missing? = @? "nope.txt";               // @? gives _ instead of an error
missing == _ { >> "nope.txt is not there\n"; }

>> "Your name? ";
name = "";
<< name;                                // reads a line from the input
>> "Hello, " + name + "!\n";

Output:

2 lines; the last: second line
nope.txt is not there
Your name? Hello, Ana!

9. Tables on disk

A data model describes a record of fixed width; # marks its key. A table is a plain text file, one record per line, with a hash index on disk for reading, writing and deleting by key. Queries like where, sort and sum take an expression of the fields.

PRODUCT = @[#code: INT(4); name: STRING(12); price: FLOAT(6)];   // a data model; # marks the key
FILE = "products.dat";

@{}>> FILE, PRODUCT(1, "Coffee", 12.5);    // write by key: adds it, or replaces it
@{}>> FILE, PRODUCT(2, "Tea", 8.0);
@{}>> FILE, PRODUCT(3, "Cake", 15.0);

p = PRODUCT @{2} FILE;                      // one record by its key
p.price = 7.5;
@{}>> FILE, p;

rows = PRODUCT @ FILE;                      // the whole table
>> $rows.where(price < 13.0).sort(name);    // a query; $ turns records into table lines
>> "total: " + $rows.sum(price) + "\n";
PRODUCT @{3} FILE = _;                      // delete by key
>> $#(PRODUCT @ FILE) + " records left\n";

Output:

   1Coffee        12.5
   2Tea            7.5
total: 35.0
2 records left

10. The standard library

Libraries that ship with the compiler are included with @ "std:name.nihil";: std:env.nihil (configuration from .env and the environment), std:json.nihil (writing JSON) and std:mcp.nihil (an MCP server for AI agents). Reading JSON is built into the library: a JSON value stays text, and each call takes a part of it.

@ "std:env.nihil";                          // libraries that ship with the compiler
@ "std:json.nihil";

port = env_int("PORT", 8080);               // the .env file or the environment, or the default
user = env("USER", "nobody");

item = "{\"name\": \"Tea\", \"price\": 7.5, \"tags\": [\"hot\", \"green\"]}";
name = (item.json("name") || "\"\"").json_text() || "";
price = (item.json("price") || "0").float() || 0.0;
tags = (item.json("tags") || "[]").json_items();
>> name + " costs " + $price + ", " + $#tags + " tags\n";
>> "{\"port\": " + $port + ", \"ok\": " + json_bool(port > 0) + "}\n";

Output:

Tea costs 7.5, 2 tags
{"port": 8080, "ok": true}

11. Globals and locals: the one rule to remember

Variables assigned at the top level are globals, and a name that belongs to a global always means that global, even inside a method: there, total = … changes the global instead of creating a local. Give locals names no global uses. Only a parameter may share a global's name, and then it hides the global inside its method.

total = 0;                      // a global: assigned at the top level

add(n = 0) {
    total = total + n;          // changes the global: a name that is global is always the global
}

reset_counter() {
    i = 0;                      // a local: no global is called i
    * i < 3 { i = i + 1; }
}

add(5);
add(7);
>> "total: " + $total + "\n";   // 12

// a parameter may have a global's name, and then it hides the global inside its method
double(total = 0) { : total * 2; }
>> $double(21) + " " + $total + "\n";

Output:

total: 12
42 12

12. Automatic keys

A key marked #+ is numbered by the table: write a record with key 0 by key (@{}>>) and it gets the next number, which the record then holds. The counter is kept next to the table, so a deleted number is never given again and a second run goes on from where the first stopped. In the IDE, orders.dat then appears under Database, where its records can be filtered, added, changed and deleted.

ORDER = @[#+id: INT(6); client: STRING(12); total: FLOAT(8)];   // #+ : the table numbers the key
FILE = "orders.dat";

a = ORDER(0, "Ana", 42.5);              // key 0: the table gives it the next number
@{}>> FILE, a;
>> "Ana's order is #" + $a.id + "\n";    // the record now has its number

b = ORDER(0, "Bruno", 18.0);
@{}>> FILE, b;
ORDER @{b.id} FILE = _;                 // Bruno's order is deleted: its number is never given again

c = ORDER(0, "Carla", 7.25);
@{}>> FILE, c;
>> "Carla's order is #" + $c.id + "\n";

rows = ORDER @ FILE;
i = 0;
* i < #rows {
    >> "  #" + $rows[i].id + " " + rows[i].client.trim() + ": " + $rows[i].total + "\n";
    i = i + 1;
}

// Run it again: the numbers go on from where they stopped (orders.dat.nihil-seq keeps the
// counter). In the IDE, click orders.dat under Database to see, filter and change its records;
// in + Record, leave id empty and the table numbers it.

Output:

Ana's order is #1
Carla's order is #3
  #1 Ana: 42.5
  #3 Carla: 7.25

13. Modeling data

There is no database apart from the program and no schema file: the model is the schema, declared in the code, and each model is a type, so the compiler checks every field name. A table is a text file in which every line is one record of the same width: it opens in an editor, goes into git, and record i starts at byte i × the width, so one record is read or changed without loading the rest. Next to it, .nihil-idx (the index of the key) and .nihil-seq (the counter of an automatic key) are caches that are rebuilt when they are missing or out of date.

Relations are keys: a field holds the key of a record in another table (customer below holds a CUSTOMER id). The table does not enforce the link, so the program checks it when it writes (sell), and a join is a lookup by key (CUSTOMER @{s.customer} CUSTOMERS), a few small reads through the index. Behaviour goes in methods of the model (c.owes(sales)), and where, count, first, sort and sum are compiled into loops where they are called.

Changing a model changes the width of its lines, so the old table no longer reads with the new model. Convert it once, reading it with the old model and writing it with the new one:

OLD = @[#id: INT(4); name: STRING(12)];
NEW = @[#id: INT(4); name: STRING(12); city: STRING(14)];

old = OLD @ "customers.dat";
new = [NEW() ; #old];
i = 0;
* i < #old { new[i] = NEW(old[i].id, old[i].name, ""); i = i + 1; }
@>> "customers.dat", new;               // the same table, with the new field (empty)

Not there yet: links checked by the table, group/min/max over records, indexes on other fields than the key, and several programs writing one table at the same time (a table is meant for one writer). How fast all this is, from a thousand records to a million: Performance. The full rules are in SPEC §20.

// Two models, and the link between them: a sale names its customer by the customer's key.
CUSTOMER = @[#id: INT(4); name: STRING(12); city: STRING(14)];
SALE = @[#+id: INT(6); customer: INT(4); total: FLOAT(8); paid: BOOL];

CUSTOMERS = "customers.dat";
SALES = "sales.dat";

// a method of a model: what a customer owes, from the sales that point to it
CUSTOMER.owes(c = CUSTOMER(), sales = [SALE()]) {
    : sales.where(customer == c.id && !paid).sum(total);
}

// a fresh start on every run: the customers rewritten, the sales (and their counter) removed
@>> CUSTOMERS, [CUSTOMER(1, "Ana", "Lajeado"),
               CUSTOMER(2, "Bruno", "Porto Alegre"),
               CUSTOMER(3, "Carla", "Lajeado")];
SALES.remove();
(SALES + ".nihil-seq").remove();

sell(customer = 0, total = 0.0, paid = false) {
    known? = CUSTOMER @?{customer} CUSTOMERS;          // the link is checked here
    known == _ { >> "no customer " + $customer + ": sale refused\n"; :; }
    @{}>> SALES, SALE(0, customer, total, paid);
}
sell(1, 120.0, true);
sell(3, 45.5, false);
sell(1, 80.0, false);
sell(2, 300.0, true);
sell(9, 10.0, false);                   // refused: there is no customer 9

// a join by hand: each sale finds its customer by key (a few small reads, through the index)
sales = SALE @ SALES;
i = 0;
* i < #sales {
    s = sales[i];
    c = CUSTOMER @{s.customer} CUSTOMERS;
    status = "open";
    s.paid { status = "paid"; }
    >> "sale #" + $s.id + "  " + c.name.trim() + " (" + c.city.trim() + ")  ";
    >> $s.total + "  " + status + "\n";
    i = i + 1;
}

// per customer: the model's method, and queries over the sales
customers = CUSTOMER @ CUSTOMERS;
i = 0;
* i < #customers {
    c = customers[i];
    n = sales.count(customer == c.id);
    >> c.name.trim() + ": " + $n + " sale(s), owes " + $c.owes(sales) + "\n";
    i = i + 1;
}
// a join inside a query: the city of each sale's customer
lajeado = sales.where((CUSTOMER @{customer} CUSTOMERS).city == "Lajeado");
>> "sold in Lajeado: " + $lajeado.sum(total) + "\n";

Output:

no customer 9: sale refused
sale #1  Ana (Lajeado)  120.0  paid
sale #2  Carla (Lajeado)  45.5  open
sale #3  Ana (Lajeado)  80.0  open
sale #4  Bruno (Porto Alegre)  300.0  paid
Ana: 2 sale(s), owes 80.0
Bruno: 1 sale(s), owes 0.0
Carla: 1 sale(s), owes 45.5
sold in Lajeado: 245.5

Next

The library reference lists every call on texts, arrays, tables, JSON and maps. Questions: [email protected].