aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/concurrency/frp.lux
blob: beecb251193b253bfa616db12785f8155e139eb7 (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
(.module:
  [library
   [lux #*
    [abstract
     [equivalence (#+ Equivalence)]
     [functor (#+ Functor)]
     [apply (#+ Apply)]
     ["." monad (#+ Monad do)]]
    [control
     ["." try (#+ Try)]
     ["." exception (#+ exception:)]
     ["." io (#+ IO io)]]
    [data
     ["." maybe ("#\." functor)]]
    [type (#+ :sharing)
     abstract]]]
  [//
   ["." atom (#+ Atom)]
   ["." async (#+ Async) ("#\." functor)]])

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

(exception: #export channel_is_already_closed)

(interface: #export (Sink a)
  {#.doc (doc "The tail-end of a channel, which can be written-to to fee the channel.")}
  (: (IO (Try Any))
     close)
  (: (-> a (IO (Try Any)))
     feed))

(def: (sink resolve)
  (All [a]
    (-> (async.Resolver (Maybe [a (Channel a)]))
        (Sink a)))
  (let [sink (atom.atom resolve)]
    (implementation
     (def: close
       (loop [_ []]
         (do {! io.monad}
           [current (atom.read sink)
            stopped? (current #.None)]
           (if stopped?
             ## I closed the sink.
             (in (exception.return []))
             ## Someone else interacted with the sink.
             (do !
               [latter (atom.read sink)]
               (if (is? current latter)
                 ## Someone else closed the sink.
                 (in (exception.except ..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] (:sharing [a]
                                                (async.Resolver (Maybe [a (Channel a)]))
                                                current
                                                
                                                [(Async (Maybe [a (Channel a)]))
                                                 (async.Resolver (Maybe [a (Channel a)]))]
                                                (async.async []))]
            fed? (current (#.Some [value next]))]
           (if fed?
             ## I fed the sink.
             (do !
               [_ (atom.compare_and_swap current resolve_next sink)]
               (in (exception.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.
                 (in (exception.except ..channel_is_already_closed []))
                 ## Someone else fed the sink.
                 (recur []))))))))))

(def: #export (channel _)
  {#.doc (doc "Creates a brand-new channel and hands it over, along with the sink to write to it.")}
  (All [a] (-> Any [(Channel a) (Sink a)]))
  (let [[async resolve] (async.async [])]
    [async (..sink resolve)]))

(implementation: #export functor
  (Functor Channel)
  
  (def: (map f)
    (async\map
     (maybe\map
      (function (_ [head tail])
        [(f head) (map f tail)])))))

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

  (def: (apply ff fa)
    (do async.monad
      [item_f ff
       item_a fa]
      (case [item_f item_a]
        [(#.Some [head_f tail_f]) (#.Some [head_a tail_a])]
        (in (#.Some [(head_f head_a) (apply tail_f tail_a)]))

        _
        (in #.None)))))

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

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

  (def: (in a)
    (async.resolved (#.Some [a ..empty])))

  (def: (join mma)
    (let [[output sink] (channel [])]
      (exec (: (Async Any)
               (loop [mma mma]
                 (do {! async.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
                                (in []))))]
                       (recur mma'))
                     
                     #.None
                     (in (: Any (io.run (\ sink close))))))))
        output))))

(type: #export (Subscriber a)
  {#.doc (doc "A function that can receive every value fed into a channel.")}
  (-> a (IO (Maybe Any))))

(def: #export (subscribe subscriber channel)
  (All [a] (-> (Subscriber a) (Channel a) (IO Any)))
  (io (exec (: (Async Any)
               (loop [channel channel]
                 (do async.monad
                   [item channel]
                   (case item
                     (#.Some [head tail])
                     (case (io.run (subscriber head))
                       (#.Some _)
                       (recur tail)
                       
                       #.None
                       (in []))
                     
                     #.None
                     (in [])))))
        [])))

(def: #export (only pass? channel)
  {#.doc (doc "Produces a new channel based on the old one, only with values"
              "that pass the test.")}
  (All [a] (-> (-> a Bit) (Channel a) (Channel a)))
  (do async.monad
    [item channel]
    (case item
      (#.Some [head tail])
      (let [tail' (only pass? tail)]
        (if (pass? head)
          (in (#.Some [head tail']))
          tail'))
      
      #.None
      (in #.None))))

(def: #export (of_async async)
  {#.doc (doc "A one-element channel containing the output from an async.")}
  (All [a] (-> (Async a) (Channel a)))
  (async\map (function (_ value)
               (#.Some [value ..empty]))
             async))

(def: #export (fold f init channel)
  {#.doc "Asynchronous fold over channels."}
  (All [a b]
    (-> (-> b a (Async a)) a (Channel b)
        (Async a)))
  (do {! async.monad}
    [item channel]
    (case item
      #.None
      (in init)
      
      (#.Some [head tail])
      (do !
        [init' (f head init)]
        (fold f init' tail)))))

(def: #export (folds f init channel)
  (All [a b]
    (-> (-> b a (Async a)) a (Channel b)
        (Channel a)))
  (do {! async.monad}
    [item channel]
    (case item
      #.None
      (in (#.Some [init (in #.None)]))
      
      (#.Some [head tail])
      (do !
        [init' (f head init)]
        (in (#.Some [init (folds f init' tail)]))))))

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

(def: #export (periodic milli_seconds)
  (-> Nat [(Channel Any) (Sink Any)])
  (..poll milli_seconds (io [])))

(def: #export (iterate f init)
  (All [s o] (-> (-> s (Async (Maybe [s o]))) s (Channel o)))
  (do async.monad
    [?next (f init)]
    (case ?next
      (#.Some [state output])
      (in (#.Some [output (iterate f state)]))
      
      #.None
      (in #.None))))

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

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

(def: #export (consume channel)
  (All [a] (-> (Channel a) (Async (List a))))
  (do {! async.monad}
    [item channel]
    (case item
      (#.Some [head tail])
      (\ ! map (|>> (#.Item head))
         (consume tail))

      #.None
      (in #.End))))

(def: #export (sequential milli_seconds values)
  {#.doc (doc "Transforms the given list into a channel with the same elements.")}
  (All [a] (-> Nat (List a) (Channel a)))
  (case values
    #.End
    ..empty

    (#.Item head tail)
    (async.resolved (#.Some [head (do async.monad
                                    [_ (async.wait milli_seconds)]
                                    (sequential milli_seconds tail))]))))