// Tail recursion modulo cons (ADR 0039): `map`, `filter`, `append`, `zip` // and `zip_with` over 30,000 elements (three times the // interpreter's frame limit), and a function of our own, run in // constant stack (`//@ small-stack`). Inputs both unique (their cells are // reused) and shared (another reference keeps them). //@ small-stack import std/io import std/list type Tree { Leaf, Node(Int, Tree) } /// A spine of our own: the recursive result goes into a field of `Node`. fn countdown :: n: Int -> Tree { if n == 0 { Leaf } else { Node(n, countdown (n - 1)) } } fn depth :: t: Tree acc: Int -> Int { match t { Leaf -> acc, Node(_, rest) -> depth rest (acc + 1) } } /// Two cells per element: `[x, x, ..]`, each in the hole of the next. fn doubled :: xs: List -> List { match xs { [] -> [], [x, ..rest] -> [x, x, ..doubled rest] } } /// A site behind an early `return`, in a nested block. fn until_negative :: xs: List -> List { match xs { [] -> [] , [x, ..rest] -> { if x >= 0 { return [x, ..until_negative rest] } [] } } } fn total :: xs: List -> Int { list.fold xs 0 fn acc x { acc + x } } pub fn main :: -> () / { let n = 30000 let xs = list.range 1 n io.println "{total (list.map xs fn x { x * 2 })}" io.println "{list.length (list.filter xs fn x { x % 3 == 0 })}" io.println "{list.length (list.append xs xs)}" io.println "{list.length (list.zip xs xs)}" io.println "{total (list.zip_with xs xs fn a b { a - b })}" // Unique input: the cells of the list are reused for the result. io.println "{total (list.map (list.range 1 n) fn x { x + 1 })}" io.println "{depth (countdown n) 0}" io.println "{list.length (doubled xs)} {doubled [1, 2]}" io.println "{list.length (until_negative (list.append xs [-1, 5]))}" // The shared input is unchanged. io.println "{total xs}" } //> 900030000 //> 10000 //> 60000 //> 30000 //> 0 //> 450045000 //> 30000 //> 60000 [1, 1, 2, 2] //> 30000 //> 450015000