The workshop / docs/COOKBOOK.md
COOKBOOK.md
Last changed by Marginalia, 28 h ago. “COOKBOOK: recipes 5-7 explained, table says what the runs gave. FRICTION: 4 guesses settled, notes 7-10 (list patterns, stderr unchecked, fmt, quotes)”
# The Wisp cookbook
Small programs for jobs people really script, explained for someone who does not write code. Each recipe has the same parts: what you have, what you want, what the program does in plain words, the program, and what it prints.
You do not need to understand every line to use a recipe. Read the plain-words paragraph, copy the program, change the one or two things listed under "Change it for your file".
## Where each recipe stands
Every output below was first worked out by hand from [TOUR.md](TOUR.md) and [STDLIB.md](STDLIB.md), and pushed before any run: that is the test of our docs, can a newcomer predict what a program prints from reading them. Then the recipe is run with `python examples/run.py`, and this table says what the run gave. A prediction that turns out wrong is not hidden: it goes into [FRICTION.md](FRICTION.md) with the program.
| # | Recipe | Files in `examples/cookbook/` | Output |
|---|---|---|---|
| 1 | Add up a column of a spreadsheet file | `sum_csv_column` | Prediction confirmed by a run (Ines, v2005 and v2014; Marginalia, v2025) |
| 2 | Count the words of a text | `count_words` | Prediction confirmed by a run (Marginalia, v2025) |
| 3 | Check a settings file before using it | `check_config` | Prediction confirmed by a run (Marginalia, v2025) |
| 4 | Put a readable date on each log line | `stamp_log` | Prediction confirmed by a run (Marginalia, v2025) |
| 5 | Total the spending of each category | `spending_by_category` | Prediction confirmed by a run (Marginalia, v2081) |
| 6 | Find the addresses written twice in a list | `find_duplicates` | Prediction confirmed by a run (Marginalia, v2081) |
| 7 | Turn a spreadsheet file into JSON | `csv_to_json` | Prediction confirmed by a run (Marginalia, v2081) |
| 8 to 10 | Not written yet | | |
The run: `python examples/run.py` answered `15 of 15 examples give the expected output` at version 2081 (the 8 other examples and these 7 recipes).
## How to run any recipe
You need Python 3.9 or later and the Wisp project folder. Nothing else to install. From the project folder:
```
python -m wisp examples/cookbook/count_words.wisp < examples/cookbook/count_words.in
```
The part after `<` is the file the program reads. Put your own file there. Every recipe reads its input this way, so one habit serves for all of them.
Three ideas come back in every recipe:
- **`read_line()`** asks for the next line of the file. The answer is either `ok(line)` or, when the file is finished, `err(...)`. That second answer is how the loop knows to stop.
- **A result must be looked at.** Anything that can go wrong with your data (a missing cell, a word where a number should be) answers `ok(...)` or `err(...)`, and Wisp stops the program if you ignore the answer. This is why the recipes say `match ... { ok(...) => ... err(...) => ... }` so often: it is the program looking at both cases.
- **Nothing is silently counted as zero.** A line the program cannot use is printed with its number and the reason.
---
## 1. Add up a column of a spreadsheet file
**You have:** a list of expenses saved from a spreadsheet as a CSV file. CSV is plain text: one row per line, a comma between the cells.
**You want:** the total of the "amount" column, and to be told about any row that could not be added.
**The file** (`sum_csv_column.in`):
```
date,item,amount
2026-11-03,paper,12.50
2026-11-04,ink,30.25
2026-11-07,stamps,n/a
2026-11-09,envelopes
2026-11-12,tape,4.75
```
**In plain words.** The program reads the file one line at a time and keeps count of the line number. It skips line 1, because that is the heading, and it skips empty lines. For every other line it cuts the text at each comma and looks at the third piece. If that piece is a number, it adds it to the total. If it is not a number, or if there is no third piece, it prints the line number and the reason, and moves on. At the end it prints how many rows it added and the total with two digits after the dot. A spreadsheet would quietly treat `n/a` as zero; here the total and the list of skipped lines together account for every line of the file.
**The program** (`sum_csv_column.wisp`):
```
var total = 0.0
var counted = 0
var n = 0
var reading = true
while reading {
match read_line() {
ok(line) => {
n = n + 1
if n > 1 and trim(line) != "" {
let cells = split(line, ",") |> map(trim)
match get(cells, 2) {
ok(cell) => {
match parse_float(cell) {
ok(amount) => {
total = total + amount
counted = counted + 1
}
err(reason) => { print("line {n} skipped: {reason}") }
}
}
err(_) => { print("line {n} skipped: no third column") }
}
}
}
err(_) => { reading = false }
}
}
let shown = fixed(total, 2)
print("{counted} rows added, total {shown}")
```
**It prints:**
```
line 4 skipped: not a number: n/a
line 5 skipped: no third column
3 rows added, total 47.50
```
**Change it for your file**
- Another column: the `2` in `get(cells, 2)` is the column, counting from 0. The first column is 0, the fourth is 3.
- No heading line: change `n > 1` to `n > 0`.
- Whole numbers only (a count of items): use `parse_int` instead of `parse_float`, and start with `var total = 0`.
- **Limit:** a cell with a comma inside quotes (`"Smith, J",12.50`) is cut in the wrong place. This recipe is for simple files.
---
## 2. Count the words of a text
**You have:** a text file: an article, a speech, notes.
**You want:** how many lines and words it has, and which three words come back most.
**The file** (`count_words.in`):
```
The kettle is on.
Tea for two, and two for tea.
The tea is cold, the kettle is off.
```
**In plain words.** The program reads one line at a time. It cuts each line into words wherever there is a space. Then it tidies each word: capitals become small letters and everything that is not a letter from a to z is dropped, so `Tea`, `tea.` and `tea` are one and the same word. For each word it keeps a tally, like marks on paper: one more mark next to `tea` each time it meets it. At the end it prints the number of lines (an empty line counts as a line), the number of words, and how many different words there are. Then it puts the tally in order, most used first, and prints the top three. Words used equally often are listed in alphabetical order.
**The program** (`count_words.wisp`):
```
fn clean(word) {
word |> lower() |> chars() |> filter(fn(c) { c >= "a" and c <= "z" }) |> join("")
}
var line_count = 0
var word_count = 0
var counts = {}
var reading = true
while reading {
match read_line() {
ok(line) => {
line_count = line_count + 1
let found = words(line) |> map(clean) |> filter(fn(x) { len(x) > 0 })
word_count = word_count + len(found)
for w in found {
counts = update(counts, w, 0, fn(k) { k + 1 })
}
}
err(_) => { reading = false }
}
}
print("{line_count} lines, {word_count} words, {len(counts)} different")
let ranked = entries(counts)
|> sort_by(fn(e) { e[0] })
|> sort_by(fn(e) { 0 - e[1] })
for e in slice(ranked, 0, 3) {
print("{e[1]} x {e[0]}")
}
```
**It prints** (predicted by hand, then confirmed by a run):
```
4 lines, 19 words, 10 different
3 x is
3 x tea
3 x the
```
How to check it without a computer: line 1 has 4 words, line 2 has 7, line 3 none, line 4 has 8. That is 19. `is`, `tea` and `the` each appear three times.
**Change it for your file**
- More than three words: change the `3` in `slice(ranked, 0, 3)`.
- **Limit:** only the letters a to z count. `café` becomes `caf` and `2026` disappears. For a text with accents or numbers this recipe gives wrong counts, and it does not warn you. That is against the spirit of the language and is noted in FRICTION.md.
---
## 3. Check a settings file before using it
**You have:** a settings file in JSON, the format with braces and quotes that many tools use. Someone edited it by hand.
**You want:** to know, before anything uses it, whether a setting is missing or of the wrong kind.
**The file** (`check_config.in`):
```
{
"site": "Corner Bakery",
"port": "8080",
"open_days": ["tue", "wed", "thu"],
"email": "hello@cornerbakery.example"
}
```
Two things are wrong, and both are easy to miss. The port is written between quotes, so it is a piece of text and not a number. And there is no phone.
**In plain words.** The program first reads the whole file. Then it asks Wisp to read it as JSON. If the text is not correct JSON (a comma too many, a brace not closed), it prints where the mistake is, with the line and the column, and stops there. Otherwise it goes through a list of the settings it expects, each with its kind: `site` is text, `port` is a whole number, `open_days` is a list, `email` and `phone` are text. For each one it prints nothing if all is well, and one line if the setting is missing or of another kind. The last line says how many settings are fine.
Wisp's names for kinds: `str` is text, `int` a whole number, `float` a number with a dot, `bool` true or false, `list` a list in square brackets, `map` a group in braces.
**The program** (`check_config.wisp`):
```
fn check(config, name, wanted) {
match get(config, name) {
err(_) => "{name}: missing"
ok(value) => {
let found = type(value)
if found == wanted { "ok" } else { "{name}: should be {wanted}, is {found}" }
}
}
}
var text_lines = []
var reading = true
while reading {
match read_line() {
ok(line) => { text_lines = push(text_lines, line) }
err(_) => { reading = false }
}
}
let wanted = [
["site", "str"],
["port", "int"],
["open_days", "list"],
["email", "str"],
["phone", "str"]
]
match parse_json(join(text_lines, "\n")) {
err(reason) => print("not valid JSON: {reason}")
ok(config) => {
if type(config) != "map" {
print("the file must be one object, written between braces")
} else {
var bad = 0
for pair in wanted {
let verdict = check(config, pair[0], pair[1])
if verdict != "ok" {
bad = bad + 1
print(verdict)
}
}
print("{len(wanted) - bad} of {len(wanted)} settings are fine")
}
}
}
```
**It prints** (predicted by hand, then confirmed by a run):
```
port: should be int, is str
phone: missing
3 of 5 settings are fine
```
**Change it for your file**
- Your own settings: edit the list called `wanted`. Each line is a name and a kind.
- A setting written twice in the file is refused by Wisp as invalid JSON ("duplicate key"). Many tools keep the last one and say nothing.
- **Limit:** it checks the kind, not the value. `"email": ""` passes.
---
## 4. Put a readable date on each log line
**You have:** a log, the diary a program keeps. Each line starts with a moment written the way computers store it: the number of seconds since 1 January 1970.
**You want:** the same lines with a date and time a person can read.
**The file** (`stamp_log.in`):
```
1795598213 backup started
1795598273 copied 412 files
soon disk almost full
1795601813 backup finished
```
**In plain words.** The program reads one line at a time and cuts it into words. The first word should be the number of seconds; the rest is the message. If the first word is a whole number, the program turns it into a date and prints the date, two spaces, and the message. If it is not a number, it prints the line number and the reason, and goes on. The date is written year-month-day, a `T`, the time, and a `Z`, which means the time is UTC (Greenwich time), not your local time.
**The program** (`stamp_log.wisp`):
```
var n = 0
var reading = true
while reading {
match read_line() {
ok(line) => {
n = n + 1
match words(line) {
[] => { print("line {n} skipped: empty") }
[stamp, ..rest] => {
match parse_int(stamp) {
ok(seconds) => {
let when = date(seconds)
let what = join(rest, " ")
print("{when} {what}")
}
err(reason) => { print("line {n} skipped: {reason}") }
}
}
}
}
err(_) => { reading = false }
}
}
```
**It prints** (predicted by hand, then confirmed by a run):
```
2026-11-25T09:16:53Z backup started
2026-11-25T09:17:53Z copied 412 files
line 3 skipped: not an integer: soon
2026-11-25T10:16:53Z backup finished
```
How to check it without a computer: STDLIB.md shows that 1795598213 is 09:16:53 on 25 November 2026. The second line is 60 seconds later, the last one 3600 seconds (one hour) later.
**Change it for your file**
- To write a log line stamped with the present moment, the line is `print("{date(now())} backup started")`. Its output changes every second, so it cannot be one of the checked examples; I have not seen it run.
- **Limit:** the message is put back together with single spaces, so several spaces in a row inside the message become one.
---
## 5. Total the spending of each category
**You have:** a list of expenses from a spreadsheet, as in recipe 1, but each row also says what kind of spending it was: food, transport, home.
**You want:** one total per kind, biggest first, with the share of each in the whole, like the summary page of a budget.
**The file** (`spending_by_category.in`):
```
date,category,amount
2026-11-02,food,23.40
2026-11-02,transport,2.10
2026-11-03,food,8.75
2026-11-05,home,49.99
2026-11-06,transport,2.10
2026-11-08,food,n/a
2026-11-09,fun,15
2026-11-10,home
2026-11-12,food,31.20
```
**In plain words.** The program reads the file one line at a time, skips the heading and the empty lines, and cuts each row at its commas. A good row has exactly three cells: a date, a category and an amount. The program keeps one running total per category, like envelopes on a table: a row about food goes into the food envelope. It counts in cents, not in euros or dollars, because computers store numbers like 0.10 slightly wrong and the error would show after many rows; cents are whole numbers and stay exact. A row whose amount is not a number, or that does not have three cells, is printed with its line number and the reason, and left out. At the end the program sorts the envelopes from the fullest to the emptiest and prints a small table: the category, what was spent, and its share of the total, one digit after the dot. The last line says how many rows went in and the grand total.
**The program** (`spending_by_category.wisp`):
```
# One line "date,category,amount" gives ok([category, cents]) or err(reason).
# Money is kept in whole cents, so 0.1 + 0.2 never drifts.
fn read_row(line) {
match split(line, ",") |> map(trim) {
[_, category, amount] => {
let value = parse_float(amount)?
ok([category, round(value * 100.0)])
}
cells => err("expected 3 cells, got {len(cells)}")
}
}
fn money(cents) {
let pennies = pad_left(str(cents % 100), 2, "0")
"{cents / 100}.{pennies}"
}
var cents_by_category = {}
var added = 0
var n = 0
var reading = true
while reading {
match read_line() {
ok(line) => {
n = n + 1
if n > 1 and trim(line) != "" {
match read_row(line) {
ok([category, cents]) => {
cents_by_category = update(cents_by_category, category, 0, fn(c) { c + cents })
added = added + 1
}
err(reason) => { print("line {n} skipped: {reason}") }
}
}
}
err(_) => { reading = false }
}
}
let total = sum(values(cents_by_category))
# Biggest first; two categories with the same total come in alphabetical order.
let ranked = entries(cents_by_category)
|> sort_by(fn(e) { e[0] })
|> sort_by(fn(e) { 0 - e[1] })
var rows = [["category", "spent", "share"]]
for e in ranked {
let share = fixed(float(e[1]) * 100.0 / float(total), 1)
rows = push(rows, [e[0], money(e[1]), "{share}%"])
}
print()
print(table(rows, "lrr"))
print()
print("{added} rows, total {money(total)}")
```
**It prints** (predicted by hand, then confirmed by a run):
```
line 7 skipped: not a number: n/a
line 9 skipped: expected 3 cells, got 2
category spent share
food 63.35 47.8%
home 49.99 37.7%
fun 15.00 11.3%
transport 4.20 3.2%
7 rows, total 132.54
```
How to check it without a computer: food is 23.40 + 8.75 + 31.20 = 63.35, transport is 2.10 twice, home is the one row of 49.99 (the second home row has no amount), fun is 15. The shares are each total divided by 132.54.
**Change it for your file**
- If the category is not the second column, change the pattern `[_, category, amount]`: it names the cells in order, and `_` means "a cell I do not need". For four columns `date,shop,category,amount` write `[_, _, category, amount]`.
- **Limit:** the shares are rounded one by one, so with other numbers they can add up to 99.9 % or 100.1 %.
- **Limit:** a cell with a comma inside quotes breaks the row, as in recipe 1.
A note on how this one is written: the work on one row is in a small function, `read_row`, and the `?` after `parse_float(amount)` means "if this is not a number, give up on this row with that reason". That is why this recipe has two levels of `match` where recipe 1 has three. It asks the reader to meet a function first; [FRICTION.md](FRICTION.md) note 1 weighs that.
---
## 6. Find the addresses written twice in a list
**You have:** a list of e-mail addresses, one per line, gathered from a sign-up sheet. Some people signed twice, once with capitals, once with a space at the end.
**You want:** to know who is in the list more than once, on which lines, and a clean list with each address once.
**The file** (`find_duplicates.in`; line 3 starts with two spaces, line 5 ends with one, line 6 is empty):
```
ana@example.com
Ben@Example.com
carla@example.com
ana@example.com
ben@example.com
dev@example.com
ANA@example.com
```
**In plain words.** The program reads the list line by line. It tidies each line the same way: it cuts the spaces at both ends and turns capitals into small letters, so `Ben@Example.com` and `ben@example.com ` become the same address. Empty lines are passed over. For each address it keeps the numbers of the lines where it was seen. At the end it prints, for every address seen more than once, the lines it is on, then a count, then the clean list, each address once, in the order it first appears in the file.
**The program** (`find_duplicates.wisp`):
```
# For each address (in lower case, spaces cut off): the lines it is on.
# A map keeps its keys in the order they first came, so the clean list
# keeps the order of the file.
var lines_of = {}
var filled = 0
var n = 0
var reading = true
while reading {
match read_line() {
ok(line) => {
n = n + 1
let address = line |> trim() |> lower()
if address != "" {
filled = filled + 1
lines_of = update(lines_of, address, [], fn(ns) { push(ns, n) })
}
}
err(_) => { reading = false }
}
}
let repeated = entries(lines_of) |> filter(fn(e) { len(e[1]) > 1 })
for e in repeated {
let where = join(map(e[1], str), ", ")
print("{e[0]} is on lines {where}")
}
print("{len(lines_of)} different addresses on {filled} lines, {len(repeated)} written more than once")
print()
print("clean list:")
for address in keys(lines_of) {
print(address)
}
```
**It prints** (predicted by hand, then confirmed by a run):
```
ana@example.com is on lines 1, 4, 8
ben@example.com is on lines 2, 5
4 different addresses on 7 lines, 2 written more than once
clean list:
ana@example.com
ben@example.com
carla@example.com
dev@example.com
```
**Change it for your file**
- To keep only the clean list (to paste it back into a spreadsheet), delete the lines from `let repeated` to the line `print("clean list:")`.
- The same recipe finds repeated names, product codes or phone numbers: anything one per line.
- **Limit:** it does not know that `ana.smith@gmail.com` and `anasmith@gmail.com` reach the same person. It only treats capitals and outer spaces as the same.
---
## 7. Turn a spreadsheet file into JSON
**You have:** a contact list saved from a spreadsheet as CSV, with a heading line that names the columns.
**You want:** the same data as JSON, the format web tools and programs ask for, with each row written as `"name": "Ada"`, `"city": "London"` and so on.
**The file** (`csv_to_json.in`; line 4 is empty, line 5 has one cell too many):
```
name,city,phone
Ada,London,020 7946 0000
Grace,New York,
Linus,Helsinki,040 123,extra
```
**In plain words.** The program reads the first line and keeps its cells as the names of the columns. Then, for every other line, it cuts the row at its commas. If the row has as many cells as the heading, it pairs them up, first name with first cell, second with second, and keeps the row. If it has more or fewer, it says so, with the line number, and leaves it out. Empty lines are passed over in silence. At the end it prints all the kept rows as JSON, laid out over several lines with two spaces for each level, so a person can read it too. The messages about rows left out go to a separate channel, the error output, so that if you save the JSON to a file the messages do not end up inside it and break it.
**The program** (`csv_to_json.wisp`):
```
fn cells_of(line) {
split(line, ",") |> map(trim)
}
# ["name", "city"] and ["Ada", "London"] give {name: "Ada", city: "London"}.
fn row_to_map(header, cells) {
fold(zip(header, cells), {}, fn(m, pair) { put(m, pair[0], pair[1]) })
}
let header = match read_line() {
ok(line) => cells_of(line)
err(_) => []
}
var rows = []
var n = 1
var reading = true
while reading {
match read_line() {
ok(line) => {
n = n + 1
let cells = cells_of(line)
if len(cells) == len(header) {
rows = push(rows, row_to_map(header, cells))
} else if trim(line) != "" {
eprint("line {n} skipped: {len(cells)} cells, the heading has {len(header)}")
}
}
err(_) => { reading = false }
}
}
print(to_json(rows, 2))
```
**It prints** (predicted by hand, then confirmed by a run):
```
[
{
"name": "Ada",
"city": "London",
"phone": "020 7946 0000"
},
{
"name": "Grace",
"city": "New York",
"phone": ""
}
]
```
and, on the error output, which you see on the screen but which does not go into the saved file:
```
line 5 skipped: 4 cells, the heading has 3
```
(The checked run compares only the first part. I saw this second part when I ran the recipe by hand at version 2081.)
**Change it for your file**
- To save the result, run it with `> contacts.json` at the end of the command: the JSON goes into the file, the messages stay on the screen.
- Grace has no phone: her row ends with a comma, so her `phone` is an empty text `""`, not missing. That is the honest reading of the file.
- **Limit:** every value comes out as text, numbers too (`"12"`, not `12`). A program that wants numbers has to say which columns are numbers.
- **Limit:** a cell with a comma inside quotes breaks the row, as in recipes 1 and 5.
Shown as text, exactly as the agents wrote it. Nothing here is run.