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.

104 lignes · 1821 octetsBrut · Historique
1import std/io
2import std/list
3
4// `ctl` operations natively (M5 part 3): each handler's body runs on its
5// own fiber; `resume` continues it once.
6
7effect gen
8{
9 ctl yield :: x: Int -> ()
10}
11
12effect ask
13{
14 ctl ask :: -> Int
15}
16
17effect stop
18{
19 final ctl stop :: reason: String -> Never
20}
21
22fn count :: i n
23{
24 if i < n
25 {
26 yield i
27 count (i + 1) n
28 }
29 else
30 {
31 ()
32 }
33}
34
35// The sum of everything the action yields.
36fn total :: action: fn() -> () / <gen | e> -> Int / <e>
37{
38 handle
39 {
40 action ()
41 }
42 with
43 { yield x -> x + resume (), return _ -> 0 }
44}
45
46// The first value yielded; the rest of the action is cancelled (it never
47// resumes), so what it holds is released.
48fn first :: action: fn() -> () / <gen | e> -> Int / <e>
49{
50 handle
51 {
52 action ()
53 }
54 with
55 { yield x -> x, return _ -> -1 }
56}
57
58fn guarded :: action: fn() -> Int / <stop | e> -> String / <e>
59{
60 handle
61 {
62 show (action ())
63 }
64 with
65 { stop r -> "stopped: " <> r }
66}
67
68pub fn main :: -> () / <io>
69{
70 // Long enough to be preempted many times inside the fiber.
71 io.println ("sum " <> show (total fn { count 0 20000 }))
72 let held =
73 {
74 use <- first
75 let big = list.range 1 1000
76 yield (list.length big)
77 io.println "never printed"
78 }
79 io.println ("first " <> show held)
80 // `ask` is forwarded through the inner `gen` handler to the outer one.
81 let forwarded = handle
82 {
83 use <- total
84 yield (ask ())
85 yield (ask ())
86 }
87 with
88 { ask -> resume 10 + 1 }
89 io.println ("forwarded " <> show forwarded)
90 // `final ctl` leaves a fiber for a handler outside it.
91 io.println
92 ( guarded
93 fn
94 {
95 use <- total
96 yield 1
97 stop "from inside a generator"
98 }
99 )
100}
101//> sum 199990000
102//> first 1000
103//> forwarded 22
104//> stopped: from inside a generator