aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/control/concurrency/frp.lux
blob: 452c153f17de49e826ea39784f9133c07d9156c6 (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
(.module:
  [lux #*
   [abstract
    [predicate (#+ Predicate)]
    [equivalence (#+ Equivalence)]
    [functor (#+ Functor)]
    [apply (#+ Apply)]
    ["." monad (#+ Monad do)]]
   [control
    ["." try (#+ Try)]
    ["." exception (#+ exception:)]
    ["." io (#+ IO io)]]
   [data
    ["." maybe ("#\." functor)]]
   [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)

(interface: #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)]
    (implementation
     (def: close
       (loop [_ []]
         (do {! io.monad}
           [current (atom.read sink)
            stopped? (current #.None)]
           (if stopped?
             ## I closed the sink.
             (wrap (exception.return []))
             ## Someone else interacted with the sink.
             (do !
               [latter (atom.read sink)]
               (if (is? current latter)
                 ## Someone else closed the sink.
                 (wrap (exception.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 (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.
                 (wrap (exception.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)]))

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

(implementation: #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))

(implementation: #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))))

(type: #export (Subscriber a)
  (-> a (IO (Maybe Any))))

(def: #export (subscribe subscriber channel)
  (All [a] (-> (Subscriber a) (Channel a) (IO Any)))
  (io (exec (: (Promise Any)
               (loop [channel channel]
                 (do promise.monad
                   [cons channel]
                   (case cons
                     (#.Some [head tail])
                     (case (io.run (subscriber head))
                       (#.Some _)
                       (recur tail)
                       
                       #.None
                       (wrap []))
                     
                     #.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)]
        (wrap (#.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)]
                      (promise.await recur (promise.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 (Promise (Maybe [s o]))) s (Channel o)))
  (do promise.monad
    [?next (f init)]
    (case ?next
      (#.Some [state output])
      (wrap (#.Some [output (iterate f state)]))
      
      #.None
      (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))]))))