One program, start to finish

This page builds one small program in steps. Each step is a complete file you can run, and the output under each one is what the build got when it ran it.

1. A statement

A program needs frontmatter and an exec block. Everything else is prose.

hello.md
---
midad: "0.1"
module: hello
---

# hello

```exec
print("hello, midad");
```
output
hello, midad

print writes a line. It is one of 72 builtins, and every one is in the builtin reference.

2. Values and types

There are nine type names: number, float, string, boolean, list, map, option, result and any. A number is a 64-bit integer and a float is a 64-bit float, and they never convert to each other on their own.

values.md
---
midad: "0.1"
module: values
---

# values

```exec
const pages = 412;
const price = 9.99;
const title = "Dune";
const in_print = true;

print(title + " has " + str(pages) + " pages");
print(str(price));
print(str(in_print));
print(str(7 / 2));
print(str(idiv(7, 2)));
```
output
Dune has 412 pages
9.99
true
3.5
3

/ is real division and answers a float; idiv(a, b) is integer division and floors. str() turns anything into a string, and + on two strings joins them.

3. Functions

A function lives in a fn block. Parameters and the return type are typed, and a function that does not return on every path is E0210.

functions.md
---
midad: "0.1"
module: functions
---

# functions

```fn
function pages_per_day(pages: number, days: number): number {
  if (days == 0) {
    return pages;
  }
  return idiv(pages, days);
}

function describe(title: string, days: number): string {
  return title + " in " + str(days) + " days";
}
```

```exec
print(describe("Dune", 4));
print(str(pages_per_day(412, 4)));
```
output
Dune in 4 days
103

4. Lists and maps

A list is written [...] and a map is written {"key": value}. A list is changed in place: push, set_at and sort change their first argument and answer nothing, so they are statements of their own. remove_at changes the list and answers the element it took out. A map is changed by put, which answers the map. Assignment copies the value, so a second binding never sees the change - mutation and copying has the full table.

collections.md
---
midad: "0.1"
module: collections
---

# collections

```exec
let shelf = ["Dune", "Solaris"];
push(shelf, "Piranesi");
print(str(len(shelf)));
print(str(at(shelf, 2)));

let book = {"title": "Dune", "pages": 412};
book = put(book, "read", true);
print(str(keys(book)));
print(str(get(book, "pages")));
print(str(has(book, "author")));
```
output
3
Piranesi
["pages","read","title"]
412
false

at and get answer any, so a value read out of a collection needs int() or str() before you use it as one. That is the most common friction in the language and the limits page says so in its own words.

A map's keys come back in byte order, not insertion order. keys() is how you get a stable order to loop over.

5. Missing values, and errors as values

option is either Some(value) or None. result is either Ok(value) or Err(reason). ? unwraps one or returns the empty case from the function you are in.

options.md
---
midad: "0.1"
module: options
---

# options

```fn
function parse_pages(text: string): option {
  const n = int.parse(text)?;
  if (n < 1) {
    return None;
  }
  return Some(n);
}

function ratio(a: number, b: number): result {
  if (b == 0) {
    return Err("cannot divide by zero");
  }
  return Ok(idiv(a, b));
}
```

```exec
print(unwrap_or(parse_pages("412"), 0));
print(str(is_none(parse_pages("many"))));

if let Ok(v) = ratio(412, 4) {
  print("ratio " + str(v));
}
if let Err(e) = ratio(412, 0) {
  print(e);
}
```
output
412
true
ratio 103
cannot divide by zero

int.parse answers an option instead of aborting, which is what you want on input a user typed.

6. Reading a file

Anything outside the program needs a grant in the frontmatter. Here the program reads a JSON file it declared, parses it once, and walks it.

sales.json
[{"item": "ink", "cents": 1250}, {"item": "paper", "cents": 399}]
report.md
---
midad: "0.1"
module: report
permissions:
  fs_read: ["sales.json"]
---

# report

```exec
const text = unwrap_or(read_file("sales.json"), "[]");
const rows = json.parse(text);
print(str(len(rows)));
print(str(get(at(rows, 0), "item")));
```
output
2
ink

Delete the fs_read line and midad check refuses the call with E0300 before anything runs. That is the point of the frontmatter: a program says what it may touch, and the checker holds it to that.

7. A command

A command: block is a subcommand of the file. args is the list of words after the command name.

rows.json
[{"id": 1}, {"id": 2}, {"id": 3}]
snippet-7.md
---
midad: "0.1"
module: rows
permissions:
  fs_read: ["rows.json"]
---

# rows

```command:count
const text = unwrap_or(read_file("rows.json"), "[]");
print(str(len(json.parse(text))) + " rows");
```
output
3 rows

8. A server

Add route: blocks and the same file serves HTTP. req is a map with method, path, params, query, headers and body, and a route answers with respond or respond_html.

serve-8.md
---
midad: "0.1"
module: app
permissions:
  listen: ["127.0.0.1:18788"]
---

# app

```state
notes: list = [];
```

```route:GET /notes
return respond(200, {"notes": notes});
```

```route:POST /notes
const body = get(req, "body");
push(notes, unwrap_or(get(body, "title"), "untitled"));
return respond(201, {"count": len(notes)});
```

```route:GET /notes/:index
const i = int(get(get(req, "params"), "index"));
if (i >= len(notes)) {
  return respond(404, {"error": "no such note"});
}
return respond(200, {"title": at(notes, i)});
```
requests and responses
POST /notes -> 201 {"count":1}
POST /notes -> 201 {"count":2}
GET /notes -> 200 {"notes":["buy ink","read Dune"]}
GET /notes/1 -> 200 {"title":"read Dune"}
GET /notes/9 -> 404 {"error":"no such note"}

That is the whole language surface a program usually needs. The handbook takes each part apart, and the reference is generated from the compiler.

On this page