louise
The Louise language: compiler, runtime, std, tooling
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#121 · main · 16 min 23 s
0Étoiles
0Forks
40Issues
| 1 | // Tail recursion modulo cons (ADR 0039): `map`, `filter`, `append`, `zip` |
| 2 | // and `zip_with` over 30,000 elements (three times the |
| 3 | // interpreter's frame limit), and a function of our own, run in |
| 4 | // constant stack (`//@ small-stack`). Inputs both unique (their cells are |
| 5 | // reused) and shared (another reference keeps them). |
| 6 | //@ small-stack |
| 7 | |
| 8 | import std/io |
| 9 | import std/list |
| 10 | |
| 11 | type Tree { Leaf, Node(Int, Tree) } |
| 12 | |
| 13 | /// A spine of our own: the recursive result goes into a field of `Node`. |
| 14 | fn countdown :: n: Int -> Tree |
| 15 | { |
| 16 | if n == 0 |
| 17 | { |
| 18 | Leaf |
| 19 | } |
| 20 | else |
| 21 | { |
| 22 | Node(n, countdown (n - 1)) |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | fn depth :: t: Tree acc: Int -> Int |
| 27 | { |
| 28 | match t { Leaf -> acc, Node(_, rest) -> depth rest (acc + 1) } |
| 29 | } |
| 30 | |
| 31 | /// Two cells per element: `[x, x, ..]`, each in the hole of the next. |
| 32 | fn doubled :: xs: List<Int> -> List<Int> |
| 33 | { |
| 34 | match xs { [] -> [], [x, ..rest] -> [x, x, ..doubled rest] } |
| 35 | } |
| 36 | |
| 37 | /// A site behind an early `return`, in a nested block. |
| 38 | fn until_negative :: xs: List<Int> -> List<Int> |
| 39 | { |
| 40 | match xs |
| 41 | { [] -> [] |
| 42 | , [x, ..rest] -> |
| 43 | { |
| 44 | if x >= 0 |
| 45 | { |
| 46 | return [x, ..until_negative rest] |
| 47 | } |
| 48 | [] |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | fn total :: xs: List<Int> -> Int |
| 54 | { |
| 55 | list.fold xs 0 fn acc x { acc + x } |
| 56 | } |
| 57 | |
| 58 | pub fn main :: -> () / <io> |
| 59 | { |
| 60 | let n = 30000 |
| 61 | let xs = list.range 1 n |
| 62 | io.println "{total (list.map xs fn x { x * 2 })}" |
| 63 | io.println "{list.length (list.filter xs fn x { x % 3 == 0 })}" |
| 64 | io.println "{list.length (list.append xs xs)}" |
| 65 | io.println "{list.length (list.zip xs xs)}" |
| 66 | io.println "{total (list.zip_with xs xs fn a b { a - b })}" |
| 67 | // Unique input: the cells of the list are reused for the result. |
| 68 | io.println "{total (list.map (list.range 1 n) fn x { x + 1 })}" |
| 69 | io.println "{depth (countdown n) 0}" |
| 70 | io.println "{list.length (doubled xs)} {doubled [1, 2]}" |
| 71 | io.println "{list.length (until_negative (list.append xs [-1, 5]))}" |
| 72 | // The shared input is unchanged. |
| 73 | io.println "{total xs}" |
| 74 | } |
| 75 | //> 900030000 |
| 76 | //> 10000 |
| 77 | //> 60000 |
| 78 | //> 30000 |
| 79 | //> 0 |
| 80 | //> 450045000 |
| 81 | //> 30000 |
| 82 | //> 60000 [1, 1, 2, 2] |
| 83 | //> 30000 |
| 84 | //> 450015000 |