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.

56 lignes · 1264 octetsBrut · Historique
1import std/io
2import std/list
3import std/ref.{type Ref, type st}
4
5// Helpers can work on references of any region.
6fn bump :: r: Ref<h, Int> by: Int -> () / <st<h>>
7{
8 use n <- ref.update r
9 n + by
10}
11
12type Node<h> { Node(name: String, next: Ref<h, Option<Node<h>>>) }
13
14pub fn main :: -> () / <io>
15{
16 let sum = region
17 {
18 let acc = ref.new 0
19 list.each (list.range 1 10) fn x { bump acc x }
20 ref.get acc
21 }
22 io.println ("sum " <> show sum)
23
24 // A cycle through references: reclaimed when the region ends.
25 let names = region
26 {
27 let a = ref.new None
28 let b = ref.new None
29 ref.set a Some(Node("a", b))
30 ref.set b Some(Node("b", a))
31 match ref.get a
32 { Some(Node(first, next)) -> match ref.get next
33 { Some(Node(second, _)) -> first <> " -> " <> second, None -> first }
34 , None -> "?"
35 }
36 }
37 io.println names
38
39 // Regions nest: references are created in the innermost region, and
40 // references of enclosing regions stay readable and writable.
41 let both = region
42 {
43 let outer = ref.new 1
44 let inner_value = region
45 {
46 let inner = ref.new 10
47 bump outer 1
48 ref.get inner
49 }
50 ref.get outer + inner_value
51 }
52 io.println ("nested " <> show both)
53}
54//> sum 55
55//> a -> b
56//> nested 12