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.

127 lignes · 2406 octetsBrut · Historique
1// Early `return` from the function's own blocks (ADR 0037): out of `if`,
2// `match` arms and guards, nested blocks and expressions; what the blocks
3// held is released (no leaks natively); `return f(x)` is a tail call, so a
4// million of them run with a small stack.
5//@ small-stack
6
7import std/io
8import std/list
9
10type Shape { Circle(Int), Rect(Int, Int) }
11
12fn sign :: n: Int -> String
13{
14 if n < 0
15 {
16 return "negative"
17 }
18 if n == 0
19 {
20 return "zero"
21 }
22 "positive"
23}
24
25/// The first even number, from a nested block in a `match` arm.
26fn first_even :: xs: List<Int> -> Option<Int>
27{
28 match xs
29 { [] -> None
30 , [x, ..rest] ->
31 {
32 let half =
33 {
34 if x % 2 == 0
35 {
36 return Some(x)
37 }
38 x / 2
39 }
40 let _ = half
41 first_even rest
42 }
43 }
44}
45
46/// A field of a value the caller still holds (a borrowed projection),
47/// returned from under a guard.
48fn width :: s: Shape names: List<String> -> Int
49{
50 let label = list.length names
51 match s
52 { Rect(w, _) if w > 100 -> return w
53 , Rect(w, h) -> w * h + label
54 , Circle(r) ->
55 {
56 if r == 0
57 {
58 return label
59 }
60 r
61 }
62 }
63}
64
65/// `return` alone returns `()`.
66fn greet :: name: String -> () / <io>
67{
68 if name == ""
69 {
70 return
71 }
72 io.println "hello {name}"
73}
74
75/// `return` in an expression: the rest of the expression never runs.
76fn total :: xs: List<Int> -> Int
77{
78 let n =
79 list.fold xs 0 fn acc x { acc + x }
80 + if list.length xs > 3 { return -1 } else { 0 }
81 n * 10
82}
83
84/// A list that is still alive after the `if`: released when it returns.
85fn keep :: xs: List<String> stop: Bool -> Int
86{
87 let copy = ["a", ..xs]
88 if stop
89 {
90 return 0
91 }
92 list.length copy
93}
94
95fn count_down :: n: Int -> Int
96{
97 if n > 0
98 {
99 return count_down (n - 1)
100 }
101 n
102}
103
104pub fn main :: -> () / <io>
105{
106 io.println "{sign (-3)} {sign 0} {sign 7}"
107 io.println "{first_even [1, 3, 6, 7]} {first_even [1, 3]}"
108 io.println
109 "{width Rect(200, 2) ["a"]} {width Rect(2, 3) ["a"]} {width Circle(0) ["a", "b"]} {width Circle(5) []}"
110 greet ""
111 greet "Ada"
112 io.println "{total [1, 2]} {total [1, 2, 3, 4]}"
113 io.println "{keep ["b"] True} {keep ["b"] False}"
114 io.println "{count_down 1000000}"
115 if True
116 {
117 return
118 }
119 io.println "never printed"
120}
121//> negative zero positive
122//> Some(6) None
123//> 200 7 2 5
124//> hello Ada
125//> 30 -1
126//> 0 2
127//> 0