src/lazy/lazy.bend
bolt@1.17.0.0 · 44 lines · 0 definitions
1# lazy: branches that do not run both ways. Bool.pick, Bool.and and Bool.or
2# are ordinary defs, so every argument is evaluated before the call: a
3# search written as `Bool.pick(T, hit, here, go(rest))` walks the whole list
4# whatever `hit` says (measured native, 100 iterations over 100k cells: the
5# hit at the head costs 0.10 s, the same as the hit at the end, while the
6# forms here cost 0.00 s). A thunk `Unit -> T` is a value, so the branch
7# that is not taken is never applied. Keep them for work that does not
8# recurse: a thunk around a search's own recursive step allocates a closure
9# and leaves the loop on every step, where carrying the test as a Bool into
10# the next call keeps it a loop (the `thunk` rule, U015).
11import Base
12
13# `a` when c, else what rest gives: the early exit of a search
14def stop(-A: Type, cc: Bool, aa: A, rest: Unit -> A) -> A:
15 match cc:
16 case True{}:
17 aa
18 case False{}:
19 rest(Unit{})
20
21# True when a, else what rest gives: `or` that stops at the first True
22def or_else(aa: Bool, rest: Unit -> Bool) -> Bool:
23 match aa:
24 case True{}:
25 True{}
26 case False{}:
27 rest(Unit{})
28
29# what rest gives when a, else False: `and` that stops at the first False
30def and_then(aa: Bool, rest: Unit -> Bool) -> Bool:
31 match aa:
32 case True{}:
33 rest(Unit{})
34 case False{}:
35 False{}
36
37# what yes gives when c, else what no gives: a pick whose two branches each
38# recurse, only the one taken run
39def either(-A: Type, cc: Bool, yes: Unit -> A, no: Unit -> A) -> A:
40 match cc:
41 case True{}:
42 yes(Unit{})
43 case False{}:
44 no(Unit{})