# A tour of Wisp in seventeen programs Every program below is run by `tests/test_tour_doc.py` with the reference interpreter (saved as `tour.wisp`, then `python -m wisp tour.wisp`): the output shown is what it prints today, or the test fails. The rules behind them are in [SPEC.md](SPEC.md). Programs 1 to 12 are Wisp 0.1; 13 to 16 and the formatter came with 0.2; 17 shows something that was always there and that no page showed. ## 1. Values and interpolation Numbers, strings, booleans, lists. `{...}` inside a string is replaced by the text of the value. `/` on two ints is integer division; there is no implicit conversion and no truthiness. ``` let name = "Wisp" let version = 0.1 print("hello from {name} {version}") print(1 + 2 * 3, 7 / 2, 7.0 / 2, 2 == 2.0) print([1, "two", true, nothing], type([])) ``` prints ``` hello from Wisp 0.1 7 3 3.5 true [1, "two", true, nothing] list ``` ## 2. Values never change `push` gives a new list and leaves the old one alone. A `let` name is fixed; a `var` can be reassigned. ``` let xs = [1, 2, 3] let ys = push(xs, 4) # a new list; xs is untouched print(xs, ys) var total = 0 # var can be reassigned, let cannot for x in ys { total = total + x } print("total: {total}") ``` prints ``` [1, 2, 3] [1, 2, 3, 4] total: 10 ``` ## 3. Functions and closures The last expression of a block is its value. Functions are values and close over the variables around them. ``` fn area(w, h) { w * h } # the last expression is the value fn counter() { var n = 0 fn() { n = n + 1; n } # a closure over n } let next = counter() print(area(3, 4), next(), next(), next()) let twice = fn(f, x) { f(f(x)) } print(twice(fn(x) { x * x }, 3)) ``` prints ``` 12 1 2 3 81 ``` ## 4. Pipelines `x |> f(a)` means `f(x, a)`. Every library function takes its data first, so transformations read left to right, top to bottom. ``` let words = "the quick brown fox jumps over the lazy dog" |> split(" ") let long = words |> filter(fn(w) { len(w) > 3 }) |> map(upper) |> sort() print(long) print(long |> join("-")) print(range(1, 6) |> map(fn(n) { n * n }) |> sum()) ``` prints ``` ["BROWN", "JUMPS", "LAZY", "OVER", "QUICK"] BROWN-JUMPS-LAZY-OVER-QUICK 55 ``` ## 5. Maps Maps keep their insertion order and are immutable too: `put` returns a new map. `m.name` is `m["name"]`. ``` let ada = {name: "Ada", born: 1815} let older = put(ada, "born", 1800) # a new map print(ada.name, ada["born"], older.born) print(keys(ada), has(ada, "email")) for k, v in ada { print("{k} = {v}") } ``` prints ``` Ada 1815 1800 ["name", "born"] false name = Ada born = 1815 ``` ## 6. if and match are expressions Both give a value. `match` takes literals, `_`, names, and list patterns with a `..rest`. ``` fn describe(n) { let size = if n < 10 { "small" } else if n < 100 { "medium" } else { "large" } let kind = match n % 2 { 0 => "even" _ => "odd" } "{n} is {size} and {kind}" } print(describe(7)) print(describe(42)) fn head(xs) { match xs { [] => "empty" [only] => "just {only}" [first, ..rest] => "{first} and {len(rest)} more" } } print(head([]), "|", head([5]), "|", head([1, 2, 3])) ``` prints ``` 7 is small and odd 42 is medium and even empty | just 5 | 1 and 2 more ``` ## 7. Loops `while`, and `for` over a list, a string or a map; a second name gives the index (or the map value). ``` var n = 27 var steps = 0 while n != 1 { n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 } steps = steps + 1 } print("27 reaches 1 in {steps} steps") for i, c in "abc" { if c == "b" { continue } print(i, c) } ``` prints ``` 27 reaches 1 in 111 steps 0 a 2 c ``` ## 8. Results: failure is a value Anything that can fail on data returns `ok(value)` or `err(reason)`. There is no null and no exception. ``` print(parse_int("42"), parse_int("4x2")) print(get([10, 20], 5), get({a: 1}, "a")) match parse_int("4x2") { ok(n) => print("a number:", n) err(e) => print("not a number:", e) } print(is_ok(parse_int("7")), unwrap_or(parse_int("oops"), 0)) ``` prints ``` ok(42) err("not an integer: 4x2") err("index out of range: 5") ok(1) not a number: not an integer: 4x2 true 0 ``` ## 9. `?` passes a failure up After a result, `?` unwraps an `ok` or leaves the function with the `err`. It works at the end of a pipeline. ``` fn parse_point(text) { let parts = split(text, ",") if len(parts) != 2 { return err("expected x,y but got: {text}") } let x = parts[0] |> trim() |> parse_int()? # an err leaves parse_point here let y = parts[1] |> trim() |> parse_int()? ok({x: x, y: y}) } print(parse_point("3, 4")) print(parse_point("3; 4")) print(is_err(parse_point("3, four"))) ``` prints ``` ok({"x": 3, "y": 4}) err("expected x,y but got: 3; 4") true ``` ## 10. `catch` replaces a failure `e catch name { ... }` gives the `ok` value, or runs the block with the reason. ``` fn port_from(text) { let n = parse_int(text)? if n < 1 or n > 65535 { return err("port out of range: {n}") } ok(n) } let a = port_from("8080") catch e { 80 } let b = port_from("http") catch e { 80 } let c = port_from("70000") catch e { print("warning: {e}") 80 } print(a, b, c) ``` prints ``` warning: port out of range: 70000 8080 80 80 ``` ## 11. You cannot drop a result This is the rule Wisp is built around. A result left alone as a statement stops the program. Throwing one away takes an explicit `let _ =`. ``` fn save(text) { if len(text) == 0 { return err("nothing to save") } ok(len(text)) } let _ = save("") # discarding on purpose is allowed, and visible print("still running") save("") # forgetting is not: the program stops here print("never printed") ``` prints ``` still running ``` and then stops with exit code 2 and this on standard error: ``` panic: tour.wisp:8:1: unhandled result 8 | save("") # forgetting is not: the program stops here | ^ the result is err("nothing to save"), returned by save(), made at tour.wisp:2:30 ``` The message names the line and column where the result was left, shows the line, and says where the failure was made. ## 12. A small real program Parse `key = value` lines, keep the good ones, report the bad ones. No failure can vanish along the way. ``` # Read "key = value" lines, keep the good ones, report the bad ones. fn parse_line(line) { let parts = split(line, "=") if len(parts) != 2 { return err("no '=' in: {line}") } let key = trim(parts[0]) let value = parse_int(trim(parts[1]))? ok([key, value]) } let text = "width = 80\nheight = 24\ncolour: blue\ndepth = deep" var config = {} var problems = [] for line in split(text, "\n") { match parse_line(line) { ok([key, value]) => { config = put(config, key, value) } err(e) => { problems = push(problems, e) } } } print(config) print("{len(problems)} bad lines:") for p in problems { print(" -", p) } print("area:", config.width * config.height) ``` prints ``` {"width": 80, "height": 24} 2 bad lines: - no '=' in: colour: blue - not an integer: deep area: 1920 ``` ## 13. A result in a name is still a result Since 0.2 the rule follows a result wherever it goes. Putting it in a name, a list or a map is not looking at it: if the block ends and nothing has handled it, the program stops, even when the result was an `ok`. ``` fn load(text) { let n = parse_int(text) # a result, put in a name... print("loading {text}") 7 # ...and never looked at } print(load("12")) print(load("x9")) ``` prints ``` loading 12 ``` and then stops with exit code 2 and this on standard error: ``` panic: tour.wisp:2:11: unhandled result: n still holds it at the end of its block 2 | let n = parse_int(text) # a result, put in a name... | ^ the result is ok(12), returned by parse_int() ``` `parse_int("12")` worked, and the program still stops: nobody checked, so nobody knows it worked. Write `parse_int(text)?`, a `catch` or a `match` and it runs. ## 14. Modules `import "shapes" as shapes` runs the file `shapes.wisp` next to the program, once, and gives back a map of its top-level `let` and `fn` names. A name starting with `_` stays private. A module is an ordinary value: `shapes.rect(3, 4)` is a field followed by a call. Save this as `shapes.wisp`: ``` let pi = 3.14159 fn _square(x) { x * x } # starts with _: not exported fn circle(r) { pi * _square(r) } fn rect(w, h) { w * h } ``` ``` import "shapes" as shapes print(shapes.rect(3, 4), shapes.circle(2)) print(type(shapes), get(shapes, "_square")) ``` prints ``` 12 12.56636 map err("no key: \"_square\"") ``` ## 15. JSON and files Everything that touches the outside world answers with a result: a file may be missing, a text may not be JSON. `parse_json` says where the text is wrong, and refuses a key written twice instead of silently keeping the last one. In a Wisp string a brace is written `\{`, because `{...}` means "put a value here". ``` let text = "\{\"name\": \"lamp\", \"stock\": 4, \"tags\": [\"home\", \"light\"]\}" let item = parse_json(text)? print(item.name, item.stock + 1, item.tags) print(parse_json("\{\"name\": \"lamp\", \"name\": \"desk\"\}")) write_file("item.json", to_json(put(item, "stock", 5)))? append_file("log.txt", "stock of {item.name} set to 5\n")? print(exists("item.json"), read_file("item.json")?) print(read_file("missing.json")) ``` prints ``` lamp 5 ["home", "light"] err("json: line 1, column 18: duplicate key \"name\"") true {"name":"lamp","stock":5,"tags":["home","light"]} err("no such file: missing.json") ``` ## 16. Reading input, and a failure nobody caught Most small scripts start the same way: for each line of this file, do something. `read_line()` gives the next line of what the program is fed, as a result; when there is nothing left it answers `err("end of input")`, and that is how the loop knows to stop. Save this as `numbers.txt`: ``` 12 30 n/a 5 ``` and feed it to the program with `python -m wisp tour.wisp < numbers.txt`. The `<` hands the file to the program as its input. ``` var total = 0 var n = 0 var reading = true while reading { match read_line() { ok(line) => { n = n + 1 match parse_int(trim(line)) { ok(amount) => { total = total + amount } err(reason) => { print("line {n} skipped: {reason}") } } } err(_) => { reading = false } } } print("{n} lines read, total {total}") let budget = parse_int("a lot")? print("never printed") ``` prints ``` line 3 skipped: not an integer: n/a 4 lines read, total 47 ``` and then stops with exit code 1 and this on standard error: ``` error: not an integer: a lot ``` The bad line is named and left out, never counted as zero. The last two lines show what `?` does outside any function: there is nobody above to pass the failure to, so the program stops, says `error:` and the reason, and its exit code is 1. What it printed before stays printed. Exit code 2 is for a bug (a panic) or a program that cannot be read at all. ## 17. Skip a bad line in one step Program 16 needs a `match` inside a `match` to add one number, and a real file needs more steps: take the line, take its third cell, read it as a number. Nesting one `match` per step puts the line that matters five braces deep. There is a flat way. A `catch` block does not have to give a value: it can `continue` to the next turn of the loop, `break` out of it, or `return` from the function. Then nothing is bound, and the next line only runs when the step worked. Save this as `sales.csv`: ``` tea,2,12.50 coffee,1 cake,3,n/a tea,1,5 ``` and run `python -m wisp tour.wisp < sales.csv`. ``` var total = 0.0 var n = 0 while true { let line = read_line() catch _ { break } n = n + 1 let cells = split(line, ",") let cell = get(cells, 2) catch _ { print("line {n} skipped: no third column") continue } let amount = parse_float(trim(cell)) catch reason { print("line {n} skipped: {reason}") continue } total = total + amount } print("{n} lines read, total {fixed(total, 2)}") ``` prints ``` line 2 skipped: no third column line 3 skipped: not a number: n/a 4 lines read, total 17.50 ``` Read it top to bottom: get a line, or stop when there is none; get the third cell, or say so and go to the next line; read it as a number, or say why not and go to the next line; add it. Every failure still has to be answered (each `catch` is that answer), but each answer sits on the line of the step that can fail. `while true` with `catch _ { break }` also replaces the `reading` flag of program 16. The rule is in [SPEC.md](SPEC.md), section 7, under `catch`. ## One layout for everybody: the formatter `python -m wisp fmt file.wisp` prints the program in the one canonical layout (`--write` changes the file, `--check` only says whether it would change). It moves spaces and line breaks and nothing else: `tests/fmt_proof.py` runs every conformance program and every example before and after, and they print the same. Given ``` let xs=[3,1 ,2] let ys=xs|>sort()|>map(fn(x){x*10}) print( ys ) ``` `python -m wisp fmt` gives back ``` let xs = [3, 1, 2] let ys = xs |> sort() |> map(fn(x) { x * 10 }) print(ys) ``` ## Running these yourself Save a program as `hello.wisp` and run `python -m wisp hello.wisp` from the project folder (Python 3.9+, nothing to install).