tobogganSe connecter

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.

55 lignes · 1341 octetsBrut · Historique
1// Closure-heavy code (ADR 0068): higher-order functions whose closures
2// capture their environment and are called through values, so no fusion
3// or devirtualisation removes the calls: a list of capturing closures
4// folded away, a composed chain, and a function applied n times.
5
6import std/io
7import std/list
8
9fn adder :: k: Int -> fn(Int) -> Int
10{
11 fn x { x + k }
12}
13
14fn compose :: f: fn(Int) -> Int g: fn(Int) -> Int -> fn(Int) -> Int
15{
16 fn x { f (g x) }
17}
18
19fn apply_n :: f: fn(Int) -> Int n: Int x: Int -> Int
20{
21 if n == 0
22 {
23 x
24 }
25 else
26 {
27 apply_n f (n - 1) (f x)
28 }
29}
30
31fn run_all :: fs: List<fn(Int) -> Int> rounds: Int acc: Int -> Int
32{
33 if rounds == 0
34 {
35 acc
36 }
37 else
38 {
39 // The closures come from a list: the fold's calls stay opaque.
40 run_all fs (rounds - 1) (acc + list.fold fs 0 fn a f { a + f 1 })
41 }
42}
43
44pub fn main :: -> () / <io>
45{
46 // 200 closures, each capturing its own k, each called once per round.
47 let fs = list.map (list.range 1 200) fn k { adder k }
48 let total = run_all fs 1500 0
49 // A composed chain with three captured offsets, applied 300 000 times
50 // through a list slot (opaque to the specialiser).
51 let hs = [compose (adder 3) (compose (adder 4) (adder 5))]
52 let spun = list.fold hs 0 fn a h { a + apply_n h 300000 0 }
53 io.println (show (total + spun))
54}
55//> 34050000