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.
Dernier runRéussi#125 · main · 16 min 13 s
0Étoiles
0Forks
40Issues
| 1 | import std/io |
| 2 | import std/list |
| 3 | import std/ref |
| 4 | |
| 5 | // `final ctl` and panics unwind the stack; compiled code drops exactly the |
| 6 | // references each frame holds (M5 part 2), so nothing leaks. |
| 7 | |
| 8 | effect fail |
| 9 | { |
| 10 | final ctl fail :: reason: String -> Never |
| 11 | } |
| 12 | |
| 13 | fn safe_div :: a b |
| 14 | { |
| 15 | if b == 0 |
| 16 | { |
| 17 | fail "division by zero" |
| 18 | } |
| 19 | else |
| 20 | { |
| 21 | a / b |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | fn attempt :: action: fn() -> a / <fail | e> -> Result<a, String> / <e> |
| 26 | { |
| 27 | handle |
| 28 | { |
| 29 | Ok(action ()) |
| 30 | } |
| 31 | with |
| 32 | { fail reason -> Error(reason) } |
| 33 | } |
| 34 | |
| 35 | // Non-tail recursion: every frame holds a list when `fail` unwinds. |
| 36 | fn deep :: n acc |
| 37 | { |
| 38 | if n == 0 |
| 39 | { |
| 40 | fail ("bottom after " <> show (list.length acc)) |
| 41 | } |
| 42 | else |
| 43 | { |
| 44 | let r = deep (n - 1) [n, ..acc] |
| 45 | r + list.length acc |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | fn render :: r |
| 50 | { |
| 51 | match r { Ok(v) -> "ok " <> show v, Error(e) -> "failed: " <> e } |
| 52 | } |
| 53 | |
| 54 | pub fn main :: -> () / <io> |
| 55 | { |
| 56 | io.println (render (attempt fn { safe_div 10 2 })) |
| 57 | io.println (render (attempt fn { safe_div 1 0 })) |
| 58 | io.println (render (attempt fn { deep 100 [] })) |
| 59 | // The inner handler finished normally; `fail` reaches the outer one. |
| 60 | let r = |
| 61 | { |
| 62 | use <- attempt |
| 63 | match attempt fn { 1 } |
| 64 | { Ok(x) -> fail ("outer after " <> show x), Error(_) -> 0 } |
| 65 | } |
| 66 | io.println (render r) |
| 67 | // A region the unwinding passes through still ends. |
| 68 | let s: Result<Int, String> = |
| 69 | { |
| 70 | use <- attempt |
| 71 | region |
| 72 | { |
| 73 | let cell = ref.new [1, 2, 3] |
| 74 | fail ("in a region holding " <> show (list.length (ref.get cell))) |
| 75 | } |
| 76 | } |
| 77 | io.println (render s) |
| 78 | } |
| 79 | //> ok 5 |
| 80 | //> failed: division by zero |
| 81 | //> failed: bottom after 100 |
| 82 | //> failed: outer after 1 |
| 83 | //> failed: in a region holding 3 |