Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ skip: int() cannot parse "x" as an integer.
## Features

- immutable by default (`let` / `let mut`), compile-time `const`
- value semantics: arrays, objects, maps, sets and structs copy lazily, `mut` parameters are inout
- value semantics: arrays, maps, sets and structs copy lazily, `mut` parameters are inout
- structs and enums with fields, `impl` methods
- blocks give their last expression: `fun sq(x) { x * x }`, `if c { a } else { b }`, block match arms
- `match` on literals, ranges (`200..300`, `500..`), types, structs, arrays and enums, exhaustive over enum variants; the same nested patterns in `let`, parameters and `if x is { status: 200, body }`; spread, rest
Expand Down
1 change: 0 additions & 1 deletion docs/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@

- [Built-in Functions](stdlib/builtins.md)
- [Array Methods](stdlib/array.md)
- [Object Methods](stdlib/object.md)
- [String Methods](stdlib/string.md)
- [regex](stdlib/regex.md)
- [math](stdlib/math.md)
Expand Down
8 changes: 5 additions & 3 deletions docs/src/data/arrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,10 +195,12 @@ chains of them read like a pipeline. All of them are in
[Array Methods](../stdlib/array.md).

```rune
struct Order { id, total }

let orders = [
{ id: 1, total: 30 },
{ id: 2, total: 120 },
{ id: 3, total: 75 },
Order { id: 1, total: 30 },
Order { id: 2, total: 120 },
Order { id: 3, total: 75 },
];

let big = orders.filter(o => o.total > 50).map(o => o.id);
Expand Down
8 changes: 4 additions & 4 deletions docs/src/data/enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,11 @@ elements.
```rune
enum Dir { North, East, South, West }

let saved = json.stringify({ facing: Dir.East });
print(saved); // {"facing":"East"}
print(Dir(json.parse(saved).facing)); // Dir.East
let saved = json.stringify(["facing": Dir.East]);
print(saved); // {"facing":"East"}
print(Dir(json.parse(saved)["facing"])); // Dir.East

let visits = map([[Dir.North, 2], [Dir.West, 1]]);
let visits = [Dir.North: 2, Dir.West: 1];
print(visits[Dir.North]); // 2
```

Expand Down
73 changes: 38 additions & 35 deletions docs/src/data/map-and-set.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,13 @@

A **map** stores values by key; a **set** stores unique values. Use a map
to count, group or index things, and a set to remember what you have seen.

Both differ from an object in two ways: their keys may be any hashable
value, not just strings, and they are built up at run time rather than
written out field by field. Like an object, they keep keys in the order
they were first added.
Both keep keys in the order they were first added.

```rune
let mut stock = map();
stock["apple"] = 3;
stock["pear"] = 0;
let mut stock = ["apple": 3, "pear": 0];
stock["plum"] = 7;
print(stock["apple"]); // 3
print(stock); // map {"apple": 3, "pear": 0}
print(stock); // ["apple": 3, "pear": 0, "plum": 7]

let mut visitors = set();
visitors.add("ann");
Expand All @@ -28,23 +23,31 @@ A classic use: counting words.
```rune
let words = "the cat saw the dog and the cat".split(" ");

let mut counts = map();
let mut counts = [:];
for w in words {
counts[w] = (counts?.[w] ?? 0) + 1;
}
print(counts); // map {"the": 3, "cat": 2, "saw": 1, "dog": 1, "and": 1}
print(counts); // ["the": 3, "cat": 2, "saw": 1, "dog": 1, "and": 1]
```

## Making One

`map()` makes an empty map. `map(src)` makes one from an object, a struct,
another map, or an array of `[key, value]` pairs. `set()` and `set(array)`
work the same way; duplicates in the array are dropped.
`[k: v, ...]` is a map literal and `[:]` an empty map. A key is any
expression: `[name: 1]` uses the variable `name`, `["name": 1]` the string.
Writing the same literal key twice is a compile error.

`map(src)` makes a map from a struct, its fields as keys, or from an array
of `[key, value]` pairs. `set()` makes an empty set and `set(array)` one
from an array; duplicates in the array are dropped.

```rune
print(map({ host: "localhost", port: 8080 })); // map {"host": "localhost", "port": 8080}
print(map([[200, "OK"], [404, "Not Found"]])); // map {200: "OK", 404: "Not Found"}
print(set(["a", "b", "a"])); // set {"a", "b"}
struct Server { host, port }

let status = [200: "OK", 404: "Not Found"];
print(status[404]); // Not Found
print(map(Server { host: "localhost", port: 8080 })); // ["host": "localhost", "port": 8080]
print(map([["a", 1], ["b", 2]])); // ["a": 1, "b": 2]
print(set(["a", "b", "a"])); // set {"a", "b"}
```

## Keys
Expand All @@ -62,44 +65,44 @@ A struct makes a natural composite key, such as a grid position:
```rune
struct Pos { x, y }

let mut grid = map();
let mut grid = [:];
grid[Pos { x: 0, y: 1 }] = "wall";
print(grid[Pos { x: 0, y: 1 }]); // wall
print(grid?.[Pos { x: 9, y: 9 }] ?? "floor"); // floor
```

Arrays, objects, maps and sets cannot be keys. To key by a pair of values,
Arrays, maps and sets cannot be keys. To key by a pair of values,
use a struct as above.

```rune
let mut seen = map();
let mut seen = [:];
seen[[1, 2]] = true; // TypeError: Cannot use an array as a key.
```

## Reading and Writing

`m[k]` reads a key; a missing key is a `KeyError`. `m?.[k]` gives `nil`
instead, so `m?.[k] ?? fallback` reads with a default. `m[k] = v` adds or
replaces a key, which needs `m` to be mutable.
replaces a key, which needs `m` to be mutable. A map is read only by
index; `m.k` is an error.

```rune
let prices = map({ apple: 1.5 });
let prices = ["apple": 1.5];
print(prices?.["kiwi"]); // nil
print(prices?.["kiwi"] ?? 0); // 0
```

```rune
let prices = map({ apple: 1.5 });
let prices = ["apple": 1.5];
print(prices["kiwi"]); // KeyError: Key not found: "kiwi".
```

A value stored in a map can be changed in place through its key:

```rune
let mut groups = map();
groups["admins"] = ["ann"];
let mut groups = ["admins": ["ann"]];
groups["admins"].push("bob");
print(groups); // map {"admins": ["ann", "bob"]}
print(groups); // ["admins": ["ann", "bob"]]
```

## Map Methods
Expand All @@ -111,7 +114,7 @@ print(groups); // map {"admins": ["ann", "bob"]}
- `len()` — the number of keys.

```rune
let mut stock = map({ apple: 3, pear: 0, plum: 7 });
let mut stock = ["apple": 3, "pear": 0, "plum": 7];

print("pear" in stock); // true
print(stock.delete("pear")); // true
Expand Down Expand Up @@ -154,7 +157,7 @@ alone. `for x in s` walks a set, and `for i, x in s` numbers its elements.
The order is always insertion order.

```rune
let stock = map({ apple: 3, plum: 7 });
let stock = ["apple": 3, "plum": 7];
for name, n in stock {
print("{name}: {n}");
}
Expand All @@ -166,28 +169,28 @@ The loop walks the map or set as it was when the loop began, so the body
may change it freely:

```rune
let mut counts = map({ a: 1, b: 2 });
let mut counts = ["a": 1, "b": 2];
for k in counts {
counts[k + "!"] = 0;
}
print(counts); // map {"a": 1, "b": 2, "a!": 0, "b!": 0}
print(counts); // ["a": 1, "b": 2, "a!": 0, "b!": 0]
```

## Equality and Conversion

`==` compares maps and sets by their entries, in any order.

```rune
print(map({ a: 1, b: 2 }) == map({ b: 2, a: 1 })); // true
print(set([1, 2]) == set([2, 1])); // true
print(["a": 1, "b": 2] == ["b": 2, "a": 1]); // true
print(set([1, 2]) == set([2, 1])); // true
```

`json.stringify` writes a set as an array, and a map with string keys as
an object, in insertion order.
a JSON object, in insertion order.

```rune
print(json.stringify(set([3, 1, 2]))); // [3,1,2]
print(json.stringify(map({ a: 1, b: 2 }))); // {"a":1,"b":2}
print(json.stringify(set([3, 1, 2]))); // [3,1,2]
print(json.stringify(["a": 1, "b": 2])); // {"a":1,"b":2}
```

Like every value, a map or a set is [copied](../language/values.md#copies)
Expand Down
28 changes: 13 additions & 15 deletions docs/src/data/methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Money.zero().zero(); // TypeError: 'zero' is a static method of Money; call it a
## Mutating Methods

A method that takes `mut self` may change the instance: set its fields
(`self.balance += 1`, `self["x"] = 1`), change what they hold
(`self.balance += 1`), change what they hold
(`self.items.push(x)`) or replace `self` as a whole. Without `mut`,
`self` is read-only. Mutating methods are the only place a struct's
fields can be set; see [Setting Fields](structs.md#setting-fields).
Expand Down Expand Up @@ -126,8 +126,8 @@ print(acc.balance); // 50
### Where a Mutating Method Can Be Called

The receiver must be something that can be changed: a `let mut`
variable, or an element, property or field reached from one. That
includes structs stored in arrays and objects:
variable, or an element, key or field reached from one. That includes
structs stored in arrays and maps:

```rune
struct Account { owner, balance = 0 }
Expand All @@ -139,6 +139,10 @@ impl Account {
let mut accounts = [Account { owner: "ann" }, Account { owner: "bob" }];
accounts[1].deposit(25);
print(accounts[1]); // Account {owner: "bob", balance: 25}

let mut byOwner = ["ann": Account { owner: "ann" }];
byOwner["ann"].deposit(10);
print(byOwner["ann"].balance); // 10
```

On an immutable variable, a struct literal or the result of a call, there
Expand Down Expand Up @@ -218,30 +222,24 @@ let save = Button { label: "save", onClick: () => "saved" };
save.onClick(); // TypeError: Button has no method 'onClick'; call the function in its field as (x.onClick)().
```

Plain objects hold data only, so a function cannot be the value of an
object property. Put behavior in a struct and its `impl`. For a lookup
table of functions by name, use a [map](map-and-set.md):
For a lookup table of functions by name, use a [map](map-and-set.md):

```rune
let greeters = map([
["en", name => "hello, " + name],
["es", name => "hola, " + name],
]);
let greeters = [
"en": name => "hello, " + name,
"es": name => "hola, " + name,
];

print(greeters["es"]("ann")); // hola, ann
```

```rune
let handlers = { greet: name => "hi " + name }; // Error at 'greet': Property 'greet' of an object cannot hold a function.
```

Functions of a namespace, such as `math.floor(x)` or `fs.join(a, b)`, are
not methods; they are plain functions grouped under a name.

## Methods on Built-in Types

`impl` also works on the built-in types `string`, `number`, `boolean`,
`array`, `object`, `function`, `map`, `set`, `bytes` and `stream`. This
`array`, `function`, `map`, `set`, `bytes` and `stream`. This
lets you add the helpers your program keeps needing:

```rune
Expand Down
42 changes: 21 additions & 21 deletions docs/src/data/structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ print(User { name, role }); // User {name: "bob", role: "admin"}

A default must be a constant: a literal or operators on literals
(`60 * 60`), a [`const`](../language/variables.md#constants), a variant
of an [enum](enums.md) in the same file, an array or object of these,
`map()` or `set()`.
of an [enum](enums.md) in the same file, an array or map literal of
these, or `set()`.

```rune
const DAY = 24 * 60 * 60;
Expand Down Expand Up @@ -117,7 +117,7 @@ let mut ann = User { name: "ann" };
ann.role = "admin"; // TypeError: Cannot set field 'role' of User outside its mut self methods.
```

A struct also owns what its fields hold. An array, object, map, set or
A struct also owns what its fields hold. An array, map, set or
another struct in a field is part of it, so changing it in place,
`ann.tags.push(x)`, counts as setting the field:

Expand All @@ -132,8 +132,8 @@ Inside a `mut self` method all of this is allowed: `self.tags.push(x)`,

## Updating with Spread

A struct literal may spread a struct of its own type, or an object,
then list the fields to change: `Config { ...base, debug: true }`.
A struct literal may spread a struct of its own type, or a map, then
list the fields to change: `Config { ...base, debug: true }`.
Items apply in order, so later ones win.

```rune
Expand All @@ -150,10 +150,10 @@ print(base); // Config {host: "localhost", port: 8080, debug: false}

A struct of another type is a runtime error.

## From an Object
## From a Map

Spreading an object into a struct literal is how data from `json.parse`
becomes a struct:
Spreading a map with string keys into a struct literal is how data from
`json.parse` becomes a struct:

```rune
struct Config { host, port = 8080 }
Expand All @@ -164,52 +164,52 @@ print(cfg.port); // 8080
```

Every key must be a field, and every field without a default must be
given, by the object or by the literal. The check runs when the literal
given, by the map or by the literal. The check runs when the literal
is built:

```rune
struct Config { host, port = 8080 }
Config { ...{ host: "example.com", timeout: 5 } }; // KeyError: Config has no field 'timeout'.
Config { ...["host": "example.com", "timeout": 5] }; // KeyError: Config has no field 'timeout'.
```

```rune
struct Config { host, port = 8080 }
Config { ...{ port: 80 } }; // KeyError: Missing field 'host' of Config.
Config { ...["port": 80] }; // KeyError: Missing field 'host' of Config.
```

## Type Tests and Equality

`v is User` is `true` only for a `User`, never for an object that
happens to have the same keys; see
`v is User` is `true` only for a `User`, never for a map or another
struct with the same fields; see
[Type Tests](../language/values.md#type-tests-and-patterns).

`==` compares two structs of the same type field by field. A struct
never equals an object or a struct of another type.
never equals a map or a struct of another type.

```rune
struct User { name, role = "member" }
let ann = User { name: "ann" };

print(ann is User); // true
print({ name: "ann" } is User); // false
print(ann == User { name: "ann" }); // true
print(ann == { name: "ann", role: "member" }); // false
print(["name": "ann"] is User); // false
print(ann == User { name: "ann" }); // true
print(ann == ["name": "ann", "role": "member"]); // false
```

## Walking the Fields

`{ ...s }` copies a struct into a plain object, its fields in
declaration order. Use it to loop over the fields or count them:
`map(s)` copies a struct into a map, its fields in declaration order.
Use it to loop over the fields or count them:

```rune
struct User { name, role = "member" }
let ann = User { name: "ann" };

for field, value in { ...ann } {
for field, value in map(ann) {
print("{field}: {value}");
}
// name: ann
// role: member

print({ ...ann }.len()); // 2
print(map(ann).len()); // 2
```
Loading
Loading