aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/lazy.lux
blob: c8f5746b1f0dc12e047de0aa90ad999ad1a8f0e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(.module:
  [lux #*
   ["." io]
   [control
    [functor (#+ Functor)]
    [apply (#+ Apply)]
    [monad (#+ Monad do)]]
   [concurrency
    ["." atom]]
   [macro (#+ with-gensyms)
    ["s" syntax (#+ syntax:)]]
   [type
    abstract]])

(abstract: #export (Lazy a)
  (-> [] a)

  (def: (freeze' generator)
    (All [a] (-> (-> [] a) (Lazy a)))
    (let [cache (atom.atom #.None)]
      (:abstraction (function (_ _)
                      (case (io.run (atom.read cache))
                        (#.Some value)
                        value

                        _
                        (let [value (generator [])]
                          (exec (io.run (atom.compare-and-swap _ (#.Some value) cache))
                            value)))))))

  (def: #export (thaw l-value)
    (All [a] (-> (Lazy a) a))
    ((:representation l-value) [])))

(syntax: #export (freeze expr)
  (with-gensyms [g!_]
    (wrap (list (` ((~! freeze') (function ((~ g!_) (~ g!_)) (~ expr))))))))

(structure: #export functor (Functor Lazy)
  (def: (map f fa)
    (freeze (f (thaw fa)))))

(structure: #export apply (Apply Lazy)
  (def: &functor ..functor)
  (def: (apply ff fa)
    (freeze ((thaw ff) (thaw fa)))))

(structure: #export monad (Monad Lazy)
  (def: &functor ..functor)
  (def: wrap (|>> freeze))
  (def: join thaw))