// Tail recursion modulo cons (ADR 0039) whose cells hold nothing but // constants besides the hole (issue #331): `Succ(…)`, `[0, ..…]`, // `Link(7, …)`, and a constant second cell after a reused first one. The // hole is unit until the context fills it, so such a cell looked like a // constant tree and was emitted as a static, read-only block, which the // context then wrote into. 30,000 deep, in constant stack. //@ small-stack import std/io import std/list import std/string type Peano { Zero, Succ(prev: Peano) } fn peano :: n: Int -> Peano { if n == 0 { Zero } else { Succ(peano (n - 1)) } } fn back :: p: Peano acc: Int -> Int { match p { Zero -> acc, Succ(prev) -> back prev (acc + 1) } } fn zeros :: n: Int -> List { if n == 0 { [] } else { [0, ..zeros (n - 1)] } } type Chain { End, Link(n: Int, next: Chain) } fn sevens :: n: Int -> Chain { if n == 0 { End } else { Link(7, sevens (n - 1)) } } fn sum :: c: Chain acc: Int -> Int { match c { End -> acc, Link(n, next) -> sum next (acc + n) } } fn spaced :: words: List -> List { match words { [] -> [], [word, ..rest] -> [word, ",", ..spaced rest] } } pub fn main :: -> () / { let n = 30000 io.println "{back (peano n) 0}" io.println "{list.length (zeros n)} {zeros 2}" io.println "{sum (sevens n) 0}" io.println (string.concat (spaced ["a", "b", "c"])) io.println "{list.length (spaced (list.map (list.range 1 n) fn i { "{i}" }))}" // Built twice: no evaluation shares a cell with another. io.println "{zeros 3} {zeros 3}" } //> 30000 //> 30000 [0, 0] //> 210000 //> a,b,c, //> 60000 //> [0, 0, 0] [0, 0, 0]