aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/lazy.lux
blob: adc8458e630d3809178f0aeb30233795f531a516 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
(.module:
  [lux #*
   [abstract
    [functor (#+ Functor)]
    [apply (#+ Apply)]
    [monad (#+ Monad do)]
    [equivalence (#+ Equivalence)]]
   [control
    ["." io]
    [parser
     ["s" code]]
    [concurrency
     ["." atom]]]
   [macro (#+ with_gensyms)
    [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))))))))

(implementation: #export (equivalence (^open "_\."))
  (All [a] (-> (Equivalence a) (Equivalence (Lazy a))))
  
  (def: (= left right)
    (_\= (..thaw left) (..thaw right))))

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

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

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