-
Notifications
You must be signed in to change notification settings - Fork 59
/
AsyncSeq.fs
1841 lines (1607 loc) · 67.9 KB
/
AsyncSeq.fs
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ----------------------------------------------------------------------------
// F# async extensions (AsyncSeq.fs)
// (c) Tomas Petricek, 2011, Available under Apache 2.0 license.
// ----------------------------------------------------------------------------
namespace FSharp.Control
open System
open System.Diagnostics
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks
open System.Runtime.ExceptionServices
#if !FABLE_COMPILER
open System.Linq
#endif
#nowarn "40" "3218"
// ----------------------------------------------------------------------------
type IAsyncEnumerator<'T> =
abstract MoveNext : unit -> Async<'T option>
inherit IDisposable
type IAsyncEnumerable<'T> =
abstract GetEnumerator : unit -> IAsyncEnumerator<'T>
type AsyncSeq<'T> = IAsyncEnumerable<'T>
#if !FABLE_COMPILER
type AsyncSeqSrc<'a> = private { tail : AsyncSeqSrcNode<'a> ref }
and private AsyncSeqSrcNode<'a> =
val tcs : TaskCompletionSource<('a * AsyncSeqSrcNode<'a>) option>
new (tcs) = { tcs = tcs }
#endif
[<AutoOpen>]
module internal Utils =
[<RequireQualifiedAccess>]
module Choice =
/// Maps over the left result type.
let mapl (f:'T -> 'U) = function
| Choice1Of2 a -> f a |> Choice1Of2
| Choice2Of2 e -> Choice2Of2 e
module Disposable =
let empty : IDisposable =
{ new IDisposable with member __.Dispose () = () }
// ----------------------------------------------------------------------------
#if FABLE_COMPILER
type ExceptionDispatchInfo private (err: exn) =
member _.SourceException = err
member _.Throw () = raise err
static member Capture (err: exn) = ExceptionDispatchInfo(err)
static member Throw (err: exn) = raise err
#endif
[<RequireQualifiedAccess>]
module Observable =
/// Union type that represents different messages that can be sent to the
/// IObserver interface. The IObserver type is equivalent to a type that has
/// just OnNext method that gets 'ObservableUpdate' as an argument.
type internal ObservableUpdate<'T> =
| Next of 'T
| Error of ExceptionDispatchInfo
| Completed
/// Turns observable into an observable that only calls OnNext method of the
/// observer, but gives it a discriminated union that represents different
/// kinds of events (error, next, completed)
let asUpdates (source:IObservable<'T>) =
{ new IObservable<_> with
member x.Subscribe(observer) =
source.Subscribe
({ new IObserver<_> with
member x.OnNext(v) = observer.OnNext(Next v)
member x.OnCompleted() = observer.OnNext(Completed)
member x.OnError(e) = observer.OnNext(Error (ExceptionDispatchInfo.Capture e)) }) }
type Microsoft.FSharp.Control.Async with
static member bind (f:'a -> Async<'b>) (a:Async<'a>) : Async<'b> = async.Bind(a, f)
#if !FABLE_COMPILER
static member awaitTaskUnitCancellationAsError (t:Task) : Async<unit> =
Async.FromContinuations <| fun (ok,err,_) ->
t.ContinueWith (fun (t:Task) ->
if t.IsFaulted then err t.Exception
elif t.IsCanceled then err (OperationCanceledException("Task wrapped with Async has been cancelled."))
elif t.IsCompleted then ok ()
else failwith "invalid Task state!") |> ignore
static member awaitTaskCancellationAsError (t:Task<'a>) : Async<'a> =
Async.FromContinuations <| fun (ok,err,_) ->
t.ContinueWith (fun (t:Task<'a>) ->
if t.IsFaulted then err t.Exception
elif t.IsCanceled then err (OperationCanceledException("Task wrapped with Async has been cancelled."))
elif t.IsCompleted then ok t.Result
else failwith "invalid Task state!") |> ignore
#endif
/// Starts the specified operation using a new CancellationToken and returns
/// IDisposable object that cancels the computation. This method can be used
/// when implementing the Subscribe method of IObservable interface.
static member StartDisposable(op:Async<unit>) =
let ct = new System.Threading.CancellationTokenSource()
Async.Start(op, ct.Token)
{ new IDisposable with
member x.Dispose() = ct.Cancel() }
static member map f a = async.Bind(a, f >> async.Return)
#if !FABLE_COMPILER
static member internal chooseTasks (a:Task<'T>) (b:Task<'U>) : Async<Choice<'T * Task<'U>, 'U * Task<'T>>> =
async {
let ta, tb = a :> Task, b :> Task
let! i = Task.WhenAny( ta, tb ) |> Async.AwaitTask
if i = ta then return (Choice1Of2 (a.Result, b))
elif i = tb then return (Choice2Of2 (b.Result, a))
else return! failwith "unreachable" }
static member internal chooseTasks2 (a:Task<'T>) (b:Task) : Async<Choice<'T * Task, Task<'T>>> =
async {
let ta = a :> Task
let! i = Task.WhenAny( ta, b ) |> Async.AwaitTask
if i = ta then return (Choice1Of2 (a.Result, b))
elif i = b then return (Choice2Of2 (a))
else return! failwith "unreachable" }
type MailboxProcessor<'Msg> with
member __.PostAndAsyncReplyTask (f:TaskCompletionSource<'a> -> 'Msg) : Task<'a> =
let tcs = new TaskCompletionSource<'a>()
__.Post (f tcs)
tcs.Task
[<RequireQualifiedAccess>]
module Task =
let inline join (t:Task<Task<'a>>) : Task<'a> =
t.Unwrap()
let inline extend (f:Task<'a> -> 'b) (t:Task<'a>) : Task<'b> =
t.ContinueWith f
let chooseTaskAsTask (t:Task<'a>) (a:Async<'a>) = async {
let! a = Async.StartChildAsTask a
return Task.WhenAny (t, a) |> join }
let chooseTask (t:Task<'a>) (a:Async<'a>) : Async<'a> =
chooseTaskAsTask t a |> Async.bind Async.awaitTaskCancellationAsError
let toUnit (t:Task) : Task<unit> =
t.ContinueWith (Func<_, _>(fun (_:Task) -> ()))
let taskFault (t:Task<'a>) : Task<'b> =
t
|> extend (fun t ->
let ivar = TaskCompletionSource<_>()
if t.IsFaulted then
ivar.SetException t.Exception
else if t.IsCanceled then
ivar.SetCanceled()
ivar.Task)
|> join
#endif
// via: https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/seq.fs
module AsyncGenerator =
type Step<'a> =
| Stop
| Yield of 'a
/// Jump to another generator.
| Goto of AsyncGenerator<'a>
and AsyncGenerator<'a> =
abstract Apply : unit -> Async<Step<'a>>
abstract Disposer : (unit -> unit) option
let disposeG (g:AsyncGenerator<'a>) =
match g.Disposer with
| None -> ()
| Some f -> f ()
let appG (g:AsyncGenerator<'a>) = async {
let! res = g.Apply ()
match res with
| Goto next -> return Goto next
| Yield _ -> return res
| Stop ->
disposeG g
return res }
type GenerateCont<'a> (g:AsyncGenerator<'a>, cont:unit -> AsyncGenerator<'a>) =
member __.Generator = g
member __.Cont = cont
interface AsyncGenerator<'a> with
member x.Apply () = async {
let! step = appG g
match step with
| Stop -> return Goto (cont ())
| Yield _ as res -> return res
| Goto next -> return Goto (GenerateCont<_>.Bind (next, cont)) }
member x.Disposer =
g.Disposer
static member Bind (g:AsyncGenerator<'a>, cont:unit -> AsyncGenerator<'a>) : AsyncGenerator<'a> =
match g with
| :? GenerateCont<'a> as g -> GenerateCont<_>.Bind (g.Generator, (fun () -> GenerateCont<_>.Bind (g.Cont(), cont)))
| _ -> (new GenerateCont<'a>(g, cont) :> AsyncGenerator<'a>)
/// Right-associating binder.
let bindG (g:AsyncGenerator<'a>) (cont:unit -> AsyncGenerator<'a>) : AsyncGenerator<'a> =
GenerateCont<_>.Bind (g, cont)
/// Converts a generator to an enumerator.
/// The generator can point to another generator using Goto, in which case
/// the enumerator mutates its current generator and continues.
type AsyncGeneratorEnumerator<'a> (g:AsyncGenerator<'a>) =
let mutable g = g
let mutable fin = false
member __.Generator = g
interface IAsyncEnumerator<'a> with
member x.MoveNext () = async {
let! step = appG g
match step with
| Stop ->
fin <- true
return None
| Yield a ->
return Some a
| Goto next ->
g <- next
return! (x :> IAsyncEnumerator<_>).MoveNext() }
member __.Dispose () =
disposeG g
/// Converts an enumerator to a generator.
/// The resulting generator will either yield or stop.
type AsyncEnumeratorGenerator<'a> (enum:IAsyncEnumerator<'a>) =
member __.Enumerator = enum
interface AsyncGenerator<'a> with
member __.Apply () = async {
let! next = enum.MoveNext()
match next with
| Some a ->
return Yield a
| None ->
return Stop }
member __.Disposer = Some ((fun () -> (enum :> IDisposable).Dispose()))
let enumeratorFromGenerator (g:AsyncGenerator<'a>) : IAsyncEnumerator<'a> =
match g with
| :? AsyncEnumeratorGenerator<'a> as g -> g.Enumerator
| _ -> (new AsyncGeneratorEnumerator<_>(g) :> _)
let generatorFromEnumerator (e:IAsyncEnumerator<'a>) : AsyncGenerator<'a> =
match e with
| :? AsyncGeneratorEnumerator<'a> as e -> e.Generator
| _ -> (new AsyncEnumeratorGenerator<_>(e) :> _)
let delay (f:unit -> AsyncSeq<'T>) : AsyncSeq<'T> =
{ new IAsyncEnumerable<'T> with
member x.GetEnumerator() = f().GetEnumerator() }
let emitEnum (e:IAsyncEnumerator<'a>) : AsyncSeq<'a> =
{ new IAsyncEnumerable<_> with
member __.GetEnumerator () = e }
let fromGeneratorDelay (f:unit -> AsyncGenerator<'a>) : AsyncSeq<'a> =
delay (fun () -> emitEnum (enumeratorFromGenerator (f ())))
let toGenerator (s:AsyncSeq<'a>) : AsyncGenerator<'a> =
generatorFromEnumerator (s.GetEnumerator())
let append (s1:AsyncSeq<'a>) (s2:AsyncSeq<'a>) : AsyncSeq<'a> =
fromGeneratorDelay (fun () -> bindG (toGenerator s1) (fun () -> toGenerator s2))
// let collect (f:'a -> AsyncSeq<'b>) (s:AsyncSeq<'a>) : AsyncSeq<'b> =
// fromGeneratorDelay (fun () -> collectG (toGenerator s) (f >> toGenerator))
[<AbstractClass>]
type AsyncSeqOp<'T> () =
abstract member ChooseAsync : ('T -> Async<'U option>) -> AsyncSeq<'U>
abstract member FoldAsync : ('S -> 'T -> Async<'S>) -> 'S -> Async<'S>
abstract member MapAsync : ('T -> Async<'U>) -> AsyncSeq<'U>
abstract member IterAsync : ('T -> Async<unit>) -> Async<unit>
default x.MapAsync (f:'T -> Async<'U>) : AsyncSeq<'U> =
x.ChooseAsync (f >> Async.map Some)
default x.IterAsync (f:'T -> Async<unit>) : Async<unit> =
x.FoldAsync (fun () t -> f t) ()
[<AutoOpen>]
module AsyncSeqOp =
type UnfoldAsyncEnumerator<'S, 'T> (f:'S -> Async<('T * 'S) option>, init:'S) =
inherit AsyncSeqOp<'T> ()
override x.IterAsync g = async {
let rec go s = async {
let! next = f s
match next with
| None -> return ()
| Some (t,s') ->
do! g t
return! go s' }
return! go init }
override __.FoldAsync (g:'S2 -> 'T -> Async<'S2>) (init2:'S2) = async {
let rec go s s2 = async {
let! next = f s
match next with
| None -> return s2
| Some (t,s') ->
let! s2' = g s2 t
return! go s' s2' }
return! go init init2 }
override __.ChooseAsync (g:'T -> Async<'U option>) : AsyncSeq<'U> =
let rec h s = async {
let! res = f s
match res with
| None ->
return None
| Some (t,s) ->
let! res' = g t
match res' with
| Some u ->
return Some (u, s)
| None ->
return! h s }
new UnfoldAsyncEnumerator<'S, 'U> (h, init) :> _
override __.MapAsync (g:'T -> Async<'U>) : AsyncSeq<'U> =
let h s = async {
let! r = f s
match r with
| Some (t,s) ->
let! u = g t
return Some (u,s)
| None ->
return None }
new UnfoldAsyncEnumerator<'S, 'U> (h, init) :> _
interface IAsyncEnumerable<'T> with
member __.GetEnumerator () =
let s = ref init
{ new IAsyncEnumerator<'T> with
member __.MoveNext () : Async<'T option> = async {
let! next = f !s
match next with
| None ->
return None
| Some (a,s') ->
s := s'
return Some a }
member __.Dispose () = () }
/// Module with helper functions for working with asynchronous sequences
module AsyncSeq =
let inline dispose (d:System.IDisposable) = try d.Dispose() with _ -> ()
[<GeneralizableValue>]
let empty<'T> : AsyncSeq<'T> =
{ new IAsyncEnumerable<'T> with
member x.GetEnumerator() =
{ new IAsyncEnumerator<'T> with
member x.MoveNext() = async { return None }
member x.Dispose() = () } }
let singleton (v:'T) : AsyncSeq<'T> =
{ new IAsyncEnumerable<'T> with
member x.GetEnumerator() =
let state = ref 0
{ new IAsyncEnumerator<'T> with
member x.MoveNext() = async { let res = state.Value = 0
incr state;
return (if res then Some v else None) }
member x.Dispose() = () } }
let append (inp1: AsyncSeq<'T>) (inp2: AsyncSeq<'T>) : AsyncSeq<'T> =
AsyncGenerator.append inp1 inp2
let inline delay (f: unit -> AsyncSeq<'T>) : AsyncSeq<'T> =
AsyncGenerator.delay f
let bindAsync (f:'T -> AsyncSeq<'U>) (inp:Async<'T>) : AsyncSeq<'U> =
{ new IAsyncEnumerable<'U> with
member x.GetEnumerator () =
{ new AsyncGenerator.AsyncGenerator<'U> with
member x.Apply () = async {
let! v = inp
let cont =
(f v).GetEnumerator()
|> AsyncGenerator.generatorFromEnumerator
return AsyncGenerator.Goto cont
}
member x.Disposer = None
}
|> AsyncGenerator.enumeratorFromGenerator
}
type AsyncSeqBuilder() =
member x.Yield(v) =
singleton v
// This looks weird, but it is needed to allow:
//
// while foo do
// do! something
//
// because F# translates body as Bind(something, fun () -> Return())
member x.Return () = empty
member x.YieldFrom(s:AsyncSeq<'T>) =
s
member x.Zero () = empty
member x.Bind (inp:Async<'T>, body : 'T -> AsyncSeq<'U>) : AsyncSeq<'U> = bindAsync body inp
member x.Combine (seq1:AsyncSeq<'T>, seq2:AsyncSeq<'T>) =
AsyncGenerator.append seq1 seq2
member x.While (guard, body:AsyncSeq<'T>) =
// Use F#'s support for Landin's knot for a low-allocation fixed-point
let rec fix = delay (fun () -> if guard() then AsyncGenerator.append body fix else empty)
fix
member x.Delay (f:unit -> AsyncSeq<'T>) =
delay f
let asyncSeq = new AsyncSeqBuilder()
let emitEnumerator (ie: IAsyncEnumerator<'T>) = asyncSeq {
let! moven = ie.MoveNext()
let b = ref moven
while b.Value.IsSome do
yield b.Value.Value
let! moven = ie.MoveNext()
b := moven }
[<RequireQualifiedAccess>]
type TryWithState<'T> =
| NotStarted of AsyncSeq<'T>
| HaveBodyEnumerator of IAsyncEnumerator<'T>
| HaveHandlerEnumerator of IAsyncEnumerator<'T>
| Finished
/// Implements the 'TryWith' functionality for computation builder
let tryWith (inp: AsyncSeq<'T>) (handler : exn -> AsyncSeq<'T>) : AsyncSeq<'T> =
// Note: this is put outside the object deliberately, so the object doesn't permanently capture inp1 and inp2
{ new IAsyncEnumerable<'T> with
member x.GetEnumerator() =
let state = ref (TryWithState.NotStarted inp)
{ new IAsyncEnumerator<'T> with
member x.MoveNext() =
async { match !state with
| TryWithState.NotStarted inp ->
let res = ref Unchecked.defaultof<_>
try
res := Choice1Of2 (inp.GetEnumerator())
with exn ->
res := Choice2Of2 exn
match res.Value with
| Choice1Of2 r ->
return!
(state := TryWithState.HaveBodyEnumerator r
x.MoveNext())
| Choice2Of2 exn ->
return!
(x.Dispose()
let enum = (handler exn).GetEnumerator()
state := TryWithState.HaveHandlerEnumerator enum
x.MoveNext())
| TryWithState.HaveBodyEnumerator e ->
let res = ref Unchecked.defaultof<_>
try
let! r = e.MoveNext()
res := Choice1Of2 r
with exn ->
res := Choice2Of2 exn
match res.Value with
| Choice1Of2 res ->
return
(match res with
| None -> x.Dispose()
| _ -> ()
res)
| Choice2Of2 exn ->
return!
(x.Dispose()
let e = (handler exn).GetEnumerator()
state := TryWithState.HaveHandlerEnumerator e
x.MoveNext())
| TryWithState.HaveHandlerEnumerator e ->
let! res = e.MoveNext()
return (match res with
| Some _ -> res
| None -> x.Dispose(); None)
| _ ->
return None }
member x.Dispose() =
match !state with
| TryWithState.HaveBodyEnumerator e | TryWithState.HaveHandlerEnumerator e ->
state := TryWithState.Finished
dispose e
| _ -> () } }
[<RequireQualifiedAccess>]
type TryFinallyState<'T> =
| NotStarted of AsyncSeq<'T>
| HaveBodyEnumerator of IAsyncEnumerator<'T>
| Finished
// This pushes the handler through all the async computations
// The (synchronous) compensation is run when the Dispose() is called
let tryFinally (inp: AsyncSeq<'T>) (compensation : unit -> unit) : AsyncSeq<'T> =
{ new IAsyncEnumerable<'T> with
member x.GetEnumerator() =
let state = ref (TryFinallyState.NotStarted inp)
{ new IAsyncEnumerator<'T> with
member x.MoveNext() =
async { match !state with
| TryFinallyState.NotStarted inp ->
return!
(let e = inp.GetEnumerator()
state := TryFinallyState.HaveBodyEnumerator e
x.MoveNext())
| TryFinallyState.HaveBodyEnumerator e ->
let! res = e.MoveNext()
return
(match res with
| None -> x.Dispose()
| Some _ -> ()
res)
| _ ->
return None }
member x.Dispose() =
match !state with
| TryFinallyState.HaveBodyEnumerator e->
state := TryFinallyState.Finished
dispose e
compensation()
| _ -> () } }
[<RequireQualifiedAccess>]
type CollectState<'T,'U> =
| NotStarted of AsyncSeq<'T>
| HaveInputEnumerator of IAsyncEnumerator<'T>
| HaveInnerEnumerator of IAsyncEnumerator<'T> * IAsyncEnumerator<'U>
| Finished
let collect (f: 'T -> AsyncSeq<'U>) (inp: AsyncSeq<'T>) : AsyncSeq<'U> =
{ new IAsyncEnumerable<'U> with
member x.GetEnumerator() =
let state = ref (CollectState.NotStarted inp)
{ new IAsyncEnumerator<'U> with
member x.MoveNext() =
async { match !state with
| CollectState.NotStarted inp ->
return!
(let e1 = inp.GetEnumerator()
state := CollectState.HaveInputEnumerator e1
x.MoveNext())
| CollectState.HaveInputEnumerator e1 ->
let! res1 = e1.MoveNext()
return!
(match res1 with
| Some v1 ->
let e2 = (f v1).GetEnumerator()
state := CollectState.HaveInnerEnumerator (e1, e2)
| None ->
x.Dispose()
x.MoveNext())
| CollectState.HaveInnerEnumerator (e1, e2) ->
let! res2 = e2.MoveNext()
match res2 with
| None ->
state := CollectState.HaveInputEnumerator e1
dispose e2
return! x.MoveNext()
| Some _ ->
return res2
| _ ->
return None }
member x.Dispose() =
match !state with
| CollectState.HaveInputEnumerator e1 ->
state := CollectState.Finished
dispose e1
| CollectState.HaveInnerEnumerator (e1, e2) ->
state := CollectState.Finished
dispose e2
dispose e1
| _ -> () } }
// let collect (f: 'T -> AsyncSeq<'U>) (inp: AsyncSeq<'T>) : AsyncSeq<'U> =
// AsyncGenerator.collect f inp
[<RequireQualifiedAccess>]
type CollectSeqState<'T,'U> =
| NotStarted of seq<'T>
| HaveInputEnumerator of IEnumerator<'T>
| HaveInnerEnumerator of IEnumerator<'T> * IAsyncEnumerator<'U>
| Finished
// Like collect, but the input is a sequence, where no bind is required on each step of the enumeration
let collectSeq (f: 'T -> AsyncSeq<'U>) (inp: seq<'T>) : AsyncSeq<'U> =
{ new IAsyncEnumerable<'U> with
member x.GetEnumerator() =
let state = ref (CollectSeqState.NotStarted inp)
{ new IAsyncEnumerator<'U> with
member x.MoveNext() =
async { match !state with
| CollectSeqState.NotStarted inp ->
return!
(let e1 = inp.GetEnumerator()
state := CollectSeqState.HaveInputEnumerator e1
x.MoveNext())
| CollectSeqState.HaveInputEnumerator e1 ->
return!
(if e1.MoveNext() then
let e2 = (f e1.Current).GetEnumerator()
state := CollectSeqState.HaveInnerEnumerator (e1, e2)
else
x.Dispose()
x.MoveNext())
| CollectSeqState.HaveInnerEnumerator (e1, e2)->
let! res2 = e2.MoveNext()
match res2 with
| None ->
return!
(state := CollectSeqState.HaveInputEnumerator e1
dispose e2
x.MoveNext())
| Some _ ->
return res2
| _ -> return None}
member x.Dispose() =
match !state with
| CollectSeqState.HaveInputEnumerator e1 ->
state := CollectSeqState.Finished
dispose e1
| CollectSeqState.HaveInnerEnumerator (e1, e2) ->
state := CollectSeqState.Finished
dispose e2
dispose e1
x.Dispose()
| _ -> () } }
[<RequireQualifiedAccess>]
type MapState<'T> =
| NotStarted of seq<'T>
| HaveEnumerator of IEnumerator<'T>
| Finished
let ofSeq (inp: seq<'T>) : AsyncSeq<'T> =
{ new IAsyncEnumerable<'T> with
member x.GetEnumerator() =
let state = ref (MapState.NotStarted inp)
{ new IAsyncEnumerator<'T> with
member x.MoveNext() =
async { match !state with
| MapState.NotStarted inp ->
let e = inp.GetEnumerator()
state := MapState.HaveEnumerator e
return! x.MoveNext()
| MapState.HaveEnumerator e ->
return
(if e.MoveNext() then
Some e.Current
else
x.Dispose()
None)
| _ -> return None }
member x.Dispose() =
match !state with
| MapState.HaveEnumerator e ->
state := MapState.Finished
dispose e
| _ -> () } }
let iteriAsync f (source : AsyncSeq<_>) =
async {
use ie = source.GetEnumerator()
let count = ref 0
let! move = ie.MoveNext()
let b = ref move
while b.Value.IsSome do
do! f !count b.Value.Value
let! moven = ie.MoveNext()
do incr count
b := moven
}
let iterAsync (f: 'T -> Async<unit>) (source: AsyncSeq<'T>) =
match source with
| :? AsyncSeqOp<'T> as source -> source.IterAsync f
| _ -> iteriAsync (fun i x -> f x) source
let iteri (f: int -> 'T -> unit) (inp: AsyncSeq<'T>) = iteriAsync (fun i x -> async.Return (f i x)) inp
// Add additional methods to the 'asyncSeq' computation builder
type AsyncSeqBuilder with
member x.TryFinally (body: AsyncSeq<'T>, compensation) =
tryFinally body compensation
member x.TryWith (body: AsyncSeq<_>, handler: (exn -> AsyncSeq<_>)) =
tryWith body handler
member x.Using (resource: 'T, binder: 'T -> AsyncSeq<'U>) =
tryFinally (binder resource) (fun () ->
if box resource <> null then dispose resource)
member x.For (seq:seq<'T>, action:'T -> AsyncSeq<'TResult>) =
collectSeq action seq
member x.For (seq:AsyncSeq<'T>, action:'T -> AsyncSeq<'TResult>) =
collect action seq
let unfoldAsync (f:'State -> Async<('T * 'State) option>) (s:'State) : AsyncSeq<'T> =
new UnfoldAsyncEnumerator<_, _>(f, s) :> _
let replicateInfinite (v:'T) : AsyncSeq<'T> =
let gen _ = async {
return Some (v,0) }
unfoldAsync gen 0
let replicateInfiniteAsync (v:Async<'T>) : AsyncSeq<'T> =
let gen _ = async {
let! v = v
return Some (v,0) }
unfoldAsync gen 0
let replicate (count:int) (v:'T) : AsyncSeq<'T> =
let gen i = async {
if i = count then return None
else return Some (v,i + 1) }
unfoldAsync gen 0
let replicateUntilNoneAsync (next:Async<'a option>) : AsyncSeq<'a> =
unfoldAsync
(fun () -> next |> Async.map (Option.map (fun a -> a,())))
()
let intervalMs (periodMs:int) = asyncSeq {
yield DateTime.UtcNow
while true do
do! Async.Sleep periodMs
yield DateTime.UtcNow }
// --------------------------------------------------------------------------
// Additional combinators (implemented as async/asyncSeq computations)
let mapAsync f (source : AsyncSeq<'T>) : AsyncSeq<'TResult> =
match source with
| :? AsyncSeqOp<'T> as source -> source.MapAsync f
| _ ->
asyncSeq {
for itm in source do
let! v = f itm
yield v }
let mapiAsync f (source : AsyncSeq<'T>) : AsyncSeq<'TResult> = asyncSeq {
let i = ref 0L
for itm in source do
let! v = f i.Value itm
i := i.Value + 1L
yield v }
#if !FABLE_COMPILER
let mapAsyncParallel (f:'a -> Async<'b>) (s:AsyncSeq<'a>) : AsyncSeq<'b> = asyncSeq {
use mb = MailboxProcessor.Start (fun _ -> async.Return())
let! err =
s
|> iterAsync (fun a -> async {
let! b = Async.StartChild (f a)
mb.Post (Some b) })
|> Async.map (fun _ -> mb.Post None)
|> Async.StartChildAsTask
yield!
replicateUntilNoneAsync (Task.chooseTask (err |> Task.taskFault) (async.Delay mb.Receive))
|> mapAsync id }
#endif
let chooseAsync f (source:AsyncSeq<'T>) =
match source with
| :? AsyncSeqOp<'T> as source -> source.ChooseAsync f
| _ ->
asyncSeq {
for itm in source do
let! v = f itm
match v with
| Some v -> yield v
| _ -> () }
let ofSeqAsync (source:seq<Async<'T>>) : AsyncSeq<'T> =
asyncSeq {
for asyncElement in source do
let! v = asyncElement
yield v
}
let filterAsync f (source : AsyncSeq<'T>) = asyncSeq {
for v in source do
let! b = f v
if b then yield v }
let tryLast (source : AsyncSeq<'T>) = async {
use ie = source.GetEnumerator()
let! v = ie.MoveNext()
let b = ref v
let res = ref None
while b.Value.IsSome do
res := b.Value
let! moven = ie.MoveNext()
b := moven
return res.Value }
let lastOrDefault def (source : AsyncSeq<'T>) = async {
let! v = tryLast source
match v with
| None -> return def
| Some v -> return v }
let tryFirst (source : AsyncSeq<'T>) = async {
use ie = source.GetEnumerator()
let! v = ie.MoveNext()
let b = ref v
if b.Value.IsSome then
return b.Value
else
return None }
let firstOrDefault def (source : AsyncSeq<'T>) = async {
let! v = tryFirst source
match v with
| None -> return def
| Some v -> return v }
let scanAsync f (state:'TState) (source : AsyncSeq<'T>) = asyncSeq {
yield state
let z = ref state
use ie = source.GetEnumerator()
let! moveRes0 = ie.MoveNext()
let b = ref moveRes0
while b.Value.IsSome do
let! zNext = f z.Value b.Value.Value
z := zNext
yield z.Value
let! moveResNext = ie.MoveNext()
b := moveResNext }
let pairwise (source : AsyncSeq<'T>) = asyncSeq {
use ie = source.GetEnumerator()
let! v = ie.MoveNext()
let b = ref v
let prev = ref None
while b.Value.IsSome do
let v = b.Value.Value
match prev.Value with
| None -> ()
| Some p -> yield (p, v)
prev := Some v
let! moven = ie.MoveNext()
b := moven }
let pickAsync (f:'T -> Async<'U option>) (source:AsyncSeq<'T>) = async {
use ie = source.GetEnumerator()
let! v = ie.MoveNext()
let b = ref v
let res = ref None
while b.Value.IsSome && not res.Value.IsSome do
let! fv = f b.Value.Value
match fv with
| None ->
let! moven = ie.MoveNext()
b := moven
| Some _ as r ->
res := r
match res.Value with
| Some _ -> return res.Value.Value
| None -> return raise(KeyNotFoundException()) }
let pick f (source:AsyncSeq<'T>) =
pickAsync (f >> async.Return) source
let tryPickAsync f (source : AsyncSeq<'T>) = async {
use ie = source.GetEnumerator()
let! v = ie.MoveNext()
let b = ref v
let res = ref None
while b.Value.IsSome && not res.Value.IsSome do
let! fv = f b.Value.Value
match fv with
| None ->
let! moven = ie.MoveNext()
b := moven
| Some _ as r ->
res := r
return res.Value }
let tryPick f (source : AsyncSeq<'T>) =
tryPickAsync (f >> async.Return) source
let contains value (source : AsyncSeq<'T>) =
source |> tryPick (fun v -> if v = value then Some () else None) |> Async.map Option.isSome
let tryFind f (source : AsyncSeq<'T>) =
source |> tryPick (fun v -> if f v then Some v else None)
let exists f (source : AsyncSeq<'T>) =
source |> tryFind f |> Async.map Option.isSome
let forall f (source : AsyncSeq<'T>) =
source |> exists (f >> not) |> Async.map not
let foldAsync f (state:'State) (source : AsyncSeq<'T>) =
match source with
| :? AsyncSeqOp<'T> as source -> source.FoldAsync f state
| _ -> source |> scanAsync f state |> lastOrDefault state
let fold f (state:'State) (source : AsyncSeq<'T>) =
foldAsync (fun st v -> f st v |> async.Return) state source
let length (source : AsyncSeq<'T>) =
fold (fun st _ -> st + 1L) 0L source
let inline sum (source : AsyncSeq<'T>) : Async<'T> =
(LanguagePrimitives.GenericZero, source) ||> fold (+)
let scan f (state:'State) (source : AsyncSeq<'T>) =
scanAsync (fun st v -> f st v |> async.Return) state source
let unfold f (state:'State) =
unfoldAsync (f >> async.Return) state
let initInfiniteAsync f =
0L |> unfoldAsync (fun n ->
async { let! x = f n
return Some (x,n+1L) })
let initAsync (count:int64) f =
0L |> unfoldAsync (fun n ->
async {
if n >= count then return None
else
let! x = f n
return Some (x,n+1L) })
let init count f =
initAsync count (f >> async.Return)
let initInfinite f =
initInfiniteAsync (f >> async.Return)
let mapi f (source : AsyncSeq<'T>) =
mapiAsync (fun i x -> f i x |> async.Return) source
let map f (source : AsyncSeq<'T>) =
mapAsync (f >> async.Return) source
let indexed (source : AsyncSeq<'T>) =
mapi (fun i x -> (i,x)) source
let iter f (source : AsyncSeq<'T>) =
iterAsync (f >> async.Return) source
let choose f (source : AsyncSeq<'T>) =
chooseAsync (f >> async.Return) source
let filter f (source : AsyncSeq<'T>) =
filterAsync (f >> async.Return) source
#if !FABLE_COMPILER
let iterAsyncParallel (f:'a -> Async<unit>) (s:AsyncSeq<'a>) : Async<unit> = async {
use mb = MailboxProcessor.Start (ignore >> async.Return)
let! err =
s
|> iterAsync (fun a -> async {
let! b = Async.StartChild (f a)
mb.Post (Some b) })
|> Async.map (fun _ -> mb.Post None)
|> Async.StartChildAsTask
return!
replicateUntilNoneAsync (Task.chooseTask (err |> Task.taskFault) (async.Delay mb.Receive))
|> iterAsync id }