aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/concurrency/frp.lux
blob: d59b96563c86c9ca0e2f7458ea282b2b3c79e72a (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
301
302
303
304
305
306
307
308
309
310
311
(;module:
  lux
  (lux (control ["F" functor]
                ["A" applicative]
                ["M" monad #+ do Monad]
                [eq #+ Eq]
                ["p" parser])
       [io #- run]
       (data (coll [list "L/" Monoid<List>])
             text/format)
       [macro]
       (macro ["s" syntax #+ syntax: Syntax]))
  (.. ["&" promise]))

## [Types]
(type: #export (Channel a)
  {#;doc "An asynchronous channel of values which may be closed.

          Reading from a channel does not remove the read piece of data, as it can still be accessed if you have an earlier node of the channel."}
  (&;Promise (Maybe [a (Channel a)])))

## [Syntax]
(syntax: #export (channel [type s;any])
  {#;doc (doc "Makes an uninitialized Channel (in this case, of Nat)."
              (channel Nat))}
  (wrap (list (` (: (Channel (~ type))
                    (&;promise' #;None))))))

## [Values]
(def: #export (filter p xs)
  (All [a] (-> (-> a Bool) (Channel a) (Channel a)))
  (do &;Monad<Promise>
    [?x+xs xs]
    (case ?x+xs
      #;None           (wrap #;None)
      (#;Some [x xs']) (if (p x)
                         (wrap (#;Some [x (filter p xs')]))
                         (filter p xs')))))

(def: #export (write value target)
  {#;doc "Write to a channel, so long as it's still open."}
  (All [a] (-> a (Channel a) (IO (Maybe (Channel a)))))
  (case (&;poll target)
    (^template [<case> <channel-to-write>]
      <case>
      (do Monad<IO>
        [#let [new-tail (channel ($ +0))]
         done? (&;resolve (#;Some [value new-tail]) <channel-to-write>)]
        (if done?
          (wrap (#;Some new-tail))
          (write value <channel-to-write>))))
    ([#;None                      target]
     [(#;Some (#;Some [_ target'])) target'])

    _
    (:: Monad<IO> wrap #;None)
    ))

(def: #export (close target)
  (All [a] (-> (Channel a) (IO Bool)))
  (case (&;poll target)
    (^template [<case> <channel-to-write>]
      <case>
      (do Monad<IO>
        [done? (&;resolve #;None <channel-to-write>)]
        (if done?
          (wrap true)
          (close <channel-to-write>))))
    ([#;None                        target]
     [(#;Some (#;Some [_ target'])) target'])

    _
    (:: Monad<IO> wrap false)
    ))

(def: (pipe' input output)
  (All [a] (-> (Channel a) (Channel a) (&;Promise Unit)))
  (do &;Monad<Promise>
    [?x+xs input]
    (case ?x+xs
      #;None              (wrap [])
      (#;Some [x input']) (case (io;run (write x output))
                            #;None
                            (wrap [])

                            (#;Some output')
                            (pipe' input' output')))))

(def: #export (pipe input output)
  {#;doc "Copy/pipe the contents of a channel on to another."}
  (All [a] (-> (Channel a) (Channel a) (&;Promise Unit)))
  (do &;Monad<Promise>
    [_ (pipe' input output)]
    (exec (io;run (close output))
      (wrap []))))

(def: #export (merge xss)
  {#;doc "Fuse all the elements in a list of channels by piping them onto a new output channel."}
  (All [a] (-> (List (Channel a)) (Channel a)))
  (let [output (channel ($ +0))]
    (exec (do &;Monad<Promise>
            [_ (M;map @ (function [input] (pipe' input output)) xss)]
            (exec (io;run (close output))
              (wrap [])))
      output)))

(def: #export (fold f init xs)
  {#;doc "Asynchronous fold over channels."}
  (All [a b] (-> (-> b a (&;Promise a)) a (Channel b) (&;Promise a)))
  (do &;Monad<Promise>
    [?x+xs xs]
    (case ?x+xs
      #;None           (wrap init)
      (#;Some [x xs']) (do @
                         [init' (f x init)]
                         (fold f init' xs')))))

(def: #export (folds f init xs)
  {#;doc "A channel of folds."}
  (All [a b] (-> (-> b a (&;Promise a)) a (Channel b) (Channel a)))
  (do &;Monad<Promise>
    [?x+xs xs]
    (case ?x+xs
      #;None           (wrap (#;Some [init (wrap #;None)]))
      (#;Some [x xs']) (do @
                         [init' (f x init)]
                         (folds f init' xs')))))

(def: (distinct' eq last-one xs)
  (All [a] (-> (Eq a) a (Channel a) (Channel a)))
  (let [(^open) eq]
    (do &;Monad<Promise>
      [?x+xs xs]
      (case ?x+xs
        #;None           (wrap #;None)
        (#;Some [x xs']) (if (= x last-one)
                           (distinct' eq last-one xs')
                           (wrap (#;Some [x (distinct' eq x xs')])))))))

(def: #export (distinct eq xs)
  {#;doc "Multiple consecutive equal values in the input channel will just be single value in the output channel."}
  (All [a] (-> (Eq a) (Channel a) (Channel a)))
  (let [(^open) eq]
    (do &;Monad<Promise>
      [?x+xs xs]
      (case ?x+xs
        #;None           (wrap #;None)
        (#;Some [x xs']) (wrap (#;Some [x (distinct' eq x xs')]))))))

(def: #export (consume xs)
  {#;doc "Reads the entirety of a channel's contents and returns them as a list."}
  (All [a] (-> (Channel a) (&;Promise (List a))))
  (do &;Monad<Promise>
    [?x+xs' xs]
    (case ?x+xs'
      #;None
      (wrap #;Nil)

      (#;Some [x xs'])
      (do @
        [=xs (consume xs')]
        (wrap (#;Cons x =xs))))))

(def: #export (once p)
  (All [a] (-> (&;Promise a) (Channel a)))
  (do &;Monad<Promise>
    [x p]
    (wrap (#;Some [x (wrap #;None)]))))

(def: #export (poll time action)
  (All [a] (-> Nat (IO (Maybe a)) (Channel a)))
  (do &;Monad<Promise>
    [?output (&;future action)]
    (case ?output
      #;None
      (wrap #;None)
      
      (#;Some head)
      (do @
        [_ (&;wait time)]
        (wrap (#;Some [head (poll time action)]))))))

(def: #export (periodic time value)
  (All [a] (-> Nat a (Channel a)))
  (do &;Monad<Promise>
    []
    (wrap (#;Some [value (do @
                           [_ (&;wait time)]
                           (periodic time value))]))))

(def: #export (sequential time xs)
  (All [a] (-> Nat (List a) (Channel a)))
  (do &;Monad<Promise>
    []
    (case xs
      #;Nil
      (wrap #;None)

      (#;Cons x xs')
      (wrap (#;Some [x (do @
                         [_ (&;wait time)]
                         (sequential time xs'))])))))

(def: #export (cycle time values)
  (All [a] (-> Nat (List a) (Channel a)))
  (do &;Monad<Promise>
    []
    (case values
      #;Nil
      (wrap #;None)

      _
      (loop [xs values]
        (case xs
          #;Nil
          (recur values)

          (#;Cons x xs')
          (wrap (#;Some [x (do @
                             [_ (&;wait time)]
                             (recur xs'))])))))))

## Utils
(def: (tail xs)
  (All [a] (-> (List a) (List a)))
  (case xs
    #;Nil
    #;Nil

    (#;Cons _ xs')
    xs'))

(def: #export (sliding-window max inputs)
  (All [a] (-> Nat (Channel a) (Channel (List a))))
  (let [(^open) &;Monad<Promise>]
    (folds (function [input window]
             (let [window' (L/compose window (list input))]
               (wrap (if (n.<= max (list;size window'))
                       window'
                       (tail window')))))
           (list)
           inputs)))

(def: #export (iterate f init)
  (All [a] (-> (-> a (&;Promise (Maybe a))) a (Channel a)))
  (do &;Monad<Promise>
    []
    (wrap (#;Some [init (do @
                          [?next (f init)]
                          (case ?next
                            #;None
                            (wrap #;None)

                            (#;Some init')
                            (iterate f init')))]))))

(def: #export (sample time inputs)
  (All [a] (-> Nat (Channel a) (Channel a)))
  (do &;Monad<Promise>
    [?h+t inputs]
    (case ?h+t
      #;None
      (wrap #;None)

      (#;Some [value inputs'])
      (do @
        [_ (&;wait time)
         #let [next-inputs (loop [last-resolved-node inputs']
                             (case (&;poll last-resolved-node)
                               (^multi (#;Some (#;Some [_ next-node]))
                                       (&;resolved? next-node))
                               (recur next-node)

                               _
                               last-resolved-node))]]
        (wrap (#;Some [value (sample time next-inputs)]))))))

## [Structures]
(struct: #export _ (F;Functor Channel)
  (def: (map f xs)
    (:: &;Functor<Promise> map
        (function [?x+xs]
          (case ?x+xs
            #;None           #;None
            (#;Some [x xs']) (#;Some [(f x) (map f xs')])))
        xs)))

(struct: #export _ (A;Applicative Channel)
  (def: functor Functor<Channel>)

  (def: (wrap a)
    (let [(^open) &;Monad<Promise>]
      (wrap (#;Some [a (wrap #;None)]))))

  (def: (apply ff fa)
    (let [fb (channel ($ +1))]
      (exec (let [(^open) Functor<Channel>]
              (map (function [f] (pipe (map f fa) fb))
                   ff))
        fb))))

(struct: #export _ (Monad Channel)
  (def: applicative Applicative<Channel>)

  (def: (join mma)
    (let [output (channel ($ +0))]
      (exec (let [(^open) Functor<Channel>]
              (map (function [ma]
                     (pipe ma output))
                   mma))
        output))))