// Closure-heavy code (ADR 0068): higher-order functions whose closures // capture their environment and are called through values, so no fusion // or devirtualisation removes the calls: a list of capturing closures // folded away, a composed chain, and a function applied n times. import std/io import std/list fn adder :: k: Int -> fn(Int) -> Int { fn x { x + k } } fn compose :: f: fn(Int) -> Int g: fn(Int) -> Int -> fn(Int) -> Int { fn x { f (g x) } } fn apply_n :: f: fn(Int) -> Int n: Int x: Int -> Int { if n == 0 { x } else { apply_n f (n - 1) (f x) } } fn run_all :: fs: List Int> rounds: Int acc: Int -> Int { if rounds == 0 { acc } else { // The closures come from a list: the fold's calls stay opaque. run_all fs (rounds - 1) (acc + list.fold fs 0 fn a f { a + f 1 }) } } pub fn main :: -> () / { // 200 closures, each capturing its own k, each called once per round. let fs = list.map (list.range 1 200) fn k { adder k } let total = run_all fs 1500 0 // A composed chain with three captured offsets, applied 300 000 times // through a list slot (opaque to the specialiser). let hs = [compose (adder 3) (compose (adder 4) (adder 5))] let spun = list.fold hs 0 fn a h { a + apply_n h 300000 0 } io.println (show (total + spun)) } //> 34050000