aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/control/concurrency/frp.lux
blob: 2be15ea23f71af2901842820a2cdab259c1e0c34 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
(.module:
  [lux #*
   [abstract
    [predicate (#+ Predicate)]
    [equivalence (#+ Equivalence)]
    [functor (#+ Functor)]
    [apply (#+ Apply)]
    ["." monad (#+ Monad do)]]
   [control
    ["." try (#+ Try)]
    ["ex" exception (#+ exception:)]
    ["." io (#+ IO io)]]
   [data
    ["." maybe ("#@." functor)]
    [collection
     ["." list ("#@." monoid)]]]
   [type (#+ :share)
    abstract]]
  [//
   ["." atom (#+ Atom)]
   ["." promise (#+ Promise) ("#@." functor)]])

(type: #export (Channel a)
  {#.doc "An asynchronous channel to distribute values."}
  (Promise (Maybe [a (Channel a)])))

(exception: #export channel-is-already-closed)

(signature: #export (Sink a)
  (: (IO (Try Any))
     close)
  (: (-> a (IO (Try Any)))
     feed))

(def: (sink resolve)
  (All [a]
    (-> (promise.Resolver (Maybe [a (Channel a)]))
        (Sink a)))
  (let [sink (atom.atom resolve)]
    (structure
     (def: close
       (loop [_ []]
         (do io.monad
           [current (atom.read sink)
            stopped? (current #.None)]
           (if stopped?
             ## I closed the sink.
             (wrap (ex.return []))
             ## Someone else interacted with the sink.
             (do @
               [latter (atom.read sink)]
               (if (is? current latter)
                 ## Someone else closed the sink.
                 (wrap (ex.throw channel-is-already-closed []))
                 ## Someone else fed the sink while I was closing it.
                 (recur [])))))))
     
     (def: (feed value)
       (loop [_ []]
         (do io.monad
           [current (atom.read sink)
            #let [[next resolve-next] (:share [a]
                                              {(promise.Resolver (Maybe [a (Channel a)]))
                                               current}
                                              {[(Promise (Maybe [a (Channel a)]))
                                                (promise.Resolver (Maybe [a (Channel a)]))]
                                               (promise.promise [])})]
            fed? (current (#.Some [value next]))]
           (if fed?
             ## I fed the sink.
             (do @
               [_ (atom.compare-and-swap current resolve-next sink)]
               (wrap (ex.return [])))
             ## Someone else interacted with the sink.
             (do @
               [latter (atom.read sink)]
               (if (is? current latter)
                 ## Someone else closed the sink while I was feeding it.
                 (wrap (ex.throw channel-is-already-closed []))
                 ## Someone else fed the sink.
                 (recur []))))))))))

(def: #export (channel _)
  (All [a] (-> Any [(Channel a) (Sink a)]))
  (let [[promise resolve] (promise.promise [])]
    [promise (..sink resolve)]))

(structure: #export functor (Functor Channel)
  (def: (map f)
    (promise@map
     (maybe@map
      (function (_ [head tail])
        [(f head) (map f tail)])))))

(structure: #export apply (Apply Channel)
  (def: &functor ..functor)

  (def: (apply ff fa)
    (do promise.monad
      [cons-f ff
       cons-a fa]
      (case [cons-f cons-a]
        [(#.Some [head-f tail-f]) (#.Some [head-a tail-a])]
        (wrap (#.Some [(head-f head-a) (apply tail-f tail-a)]))

        _
        (wrap #.None)))))

(def: empty Channel (promise.resolved #.None))

(structure: #export monad (Monad Channel)
  (def: &functor ..functor)

  (def: (wrap a)
    (promise.resolved (#.Some [a ..empty])))

  (def: (join mma)
    (let [[output sink] (channel [])]
      (exec (: (Promise Any)
               (loop [mma mma]
                 (do promise.monad
                   [?mma mma]
                   (case ?mma
                     (#.Some [ma mma'])
                     (do @
                       [_ (loop [ma ma]
                            (do @
                              [?ma ma]
                              (case ?ma
                                (#.Some [a ma'])
                                (exec (io.run (:: sink feed a))
                                  (recur ma'))
                                
                                #.None
                                (wrap []))))]
                       (recur mma'))
                     
                     #.None
                     (wrap (: Any (io.run (:: sink close))))))))
        output))))

(def: #export (listen listener channel)
  (All [a] (-> (-> a (IO Any)) (Channel a) (IO Any)))
  (io (exec (: (Promise Any)
               (loop [channel channel]
                 (do promise.monad
                   [cons channel]
                   (case cons
                     (#.Some [head tail])
                     (exec (io.run (listener head))
                       (recur tail))
                     
                     #.None
                     (wrap [])))))
        [])))

(def: #export (filter pass? channel)
  (All [a] (-> (Predicate a) (Channel a) (Channel a)))
  (do promise.monad
    [cons channel]
    (case cons
      (#.Some [head tail])
      (let [tail' (filter pass? tail)]
        (if (pass? head)
          (wrap (#.Some [head tail']))
          tail'))
      
      #.None
      (wrap #.None))))

(def: #export (from-promise promise)
  (All [a] (-> (Promise a) (Channel a)))
  (promise@map (function (_ value)
                 (#.Some [value ..empty]))
               promise))

(def: #export (fold f init channel)
  {#.doc "Asynchronous fold over channels."}
  (All [a b]
    (-> (-> b a (Promise a)) a (Channel b)
        (Promise a)))
  (do promise.monad
    [cons channel]
    (case cons
      #.None
      (wrap init)
      
      (#.Some [head tail])
      (do @
        [init' (f head init)]
        (fold f init' tail)))))

(def: #export (folds f init channel)
  {#.doc "A channel of folds."}
  (All [a b]
    (-> (-> b a (Promise a)) a (Channel b)
        (Channel a)))
  (do promise.monad
    [cons channel]
    (case cons
      #.None
      (wrap (#.Some [init (wrap #.None)]))
      
      (#.Some [head tail])
      (do @
        [init' (f head init)]
        (folds f init' tail)))))

(def: #export (poll milli-seconds action)
  (All [a] (-> Nat (IO a) (Channel a)))
  (let [[output sink] (channel [])]
    (exec (io.run (loop [_ []]
                    (do io.monad
                      [value action
                       _ (:: sink feed value)]
                      (promise.await recur (promise.wait milli-seconds)))))
      output)))

(def: #export (periodic milli-seconds)
  (-> Nat (Channel Any))
  (poll milli-seconds (io [])))

(def: #export (iterate f init)
  (All [a] (-> (-> a (Promise (Maybe a))) a (Channel a)))
  (do promise.monad
    [?next (f init)]
    (case ?next
      (#.Some next)
      (wrap (#.Some [init (iterate f next)]))
      
      #.None
      (wrap (#.Some [init (wrap #.None)])))))

(def: (distinct' equivalence previous channel)
  (All [a] (-> (Equivalence a) a (Channel a) (Channel a)))
  (do promise.monad
    [cons channel]
    (case cons
      (#.Some [head tail])
      (if (:: equivalence = previous head)
        (distinct' equivalence previous tail)
        (wrap (#.Some [head (distinct' equivalence head tail)])))
      
      #.None
      (wrap #.None))))

(def: #export (distinct equivalence channel)
  (All [a] (-> (Equivalence a) (Channel a) (Channel a)))
  (do promise.monad
    [cons channel]
    (case cons
      (#.Some [head tail])
      (wrap (#.Some [head (distinct' equivalence head tail)]))
      
      #.None
      (wrap #.None))))

(def: #export (consume channel)
  {#.doc "Reads the entirety of a channel's content and returns it as a list."}
  (All [a] (-> (Channel a) (Promise (List a))))
  (do promise.monad
    [cons channel]
    (case cons
      (#.Some [head tail])
      (:: @ map (|>> (#.Cons head))
          (consume tail))

      #.None
      (wrap #.Nil))))

(def: #export (sequential milli-seconds values)
  (All [a] (-> Nat (List a) (Channel a)))
  (case values
    #.Nil
    ..empty

    (#.Cons head tail)
    (promise.resolved (#.Some [head (do promise.monad
                                      [_ (promise.wait milli-seconds)]
                                      (sequential milli-seconds tail))]))))