-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathprocesses.jl
1383 lines (1128 loc) · 37.5 KB
/
processes.jl
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
# --- Transducible processes
"""
reducingfunction(xf, step; simd)
xf'(step; simd)
Apply transducer `xf` to the reducing function `step` to create a new
reducing function.
!!! compat "Transducers.jl 0.3"
New in version 0.3.
!!! warning
Be careful using `reducingfunction` with stateful transducers like
[`Scan`](@ref) with mutable `init` (e.g., `Scan(push!, [])`). See
more in Examples below.
# Arguments
- `xf::Transducer`: A transducer.
- `step`: A callable which accepts 1 and 2 arguments. If it only
accepts 2 arguments, wrap it with [`Completing`](@ref) to "add"
1-argument form (i.e., [`complete`](@ref) protocol).
# Keyword Arguments
- `simd`: `false`, `true`, or `:ivdep`. See [`maybe_usesimd`](@ref).
# Examples
```jldoctest
julia> using Transducers
julia> rf = reducingfunction(Map(x -> x + 1), *);
julia> rf(10, 2) === 10 * (2 + 1)
true
```
## Warning: Be careful when using `reducingfunction` with stateful transducers
Stateful `Transducer`s themselves in Transducers.jl are not inherently
broken with `reducingfunction`. However, it can produce incorrect
results when combined with mutable states:
```jldoctest reducingfunction; setup = :(using Transducers)
julia> scan_state = [];
julia> rf_bad = opcompose(Scan(push!, scan_state), Cat())'(string);
julia> transduce(rf_bad, "", 1:3)
"112123"
```
The first run works. However, observe that the vector `scan_state` is
not empty anymore:
```jldoctest reducingfunction
julia> scan_state
3-element Vector{Any}:
1
2
3
```
Thus, the second run produces an incorrect result:
```jldoctest reducingfunction
julia> transduce(rf_bad, "", 1:3)
"123112312123123"
```
One way to solve this issue is to use [`CopyInit`](@ref) or [`OnInit`](@ref).
```jldoctest reducingfunction
julia> scan_state = CopyInit([])
CopyInit(Any[])
julia> rf_good = opcompose(Scan(push!, scan_state), Cat())'(string);
julia> transduce(rf_good, "", 1:3)
"112123"
julia> scan_state
CopyInit(Any[])
julia> transduce(rf_good, "", 1:3)
"112123"
```
"""
@inline reducingfunction(xf::Transducer, step; simd::SIMDFlag = Val(false)) =
maybe_usesimd(Reduction(xf, step), simd)
# Use `_asmonoid` automatically only when `init` is not specified:
@inline _reducingfunction(
xf::XF,
step::Step;
init = DefaultInit,
simd::SIMDFlag = Val(false),
_...,
) where {XF,Step} =
maybe_usesimd(Reduction(xf, init === DefaultInit ? _asmonoid(step) : step), simd)
"""
__foldl__(rf, init, reducible::T)
Left fold a `reducible` with reducing function `rf` and initial value
`init`. This is primary an API for overloading when the reducible
"container" or "context" (e.g., I/O stream) of type `T` can provide a
better reduction mechanism than the default iterator-based one.
For a simple iterable type `MyType`, a valid implementation is:
```julia
function __foldl__(rf, val, itr::MyType)
for x in itr
val = @next(rf, val, x)
end
return complete(rf, val)
end
```
although in this case default ` __foldl__` can handle `MyType` and
thus there is no need for defining it. In general, defining
`__foldl__` is useful only when there is a better way to go over items
in `reducible` than `Base.iterate`.
See also: [`@next`](@ref).
"""
__foldl__
# ** Why calling `complete` inside `__foldl__`? **
#
# Initially I was hoping to stop calling `complete` in `__foldl__` so
# that `skipcomplete` wouldn't be necessary. However, it was
# impossible to make it inferred with some mildly complex cases. This
# is probably expected since `__foldl__` tends to use something like
# tail-call function-barriers to maximize the chance of union
# splitting. So, inside `__foldl__`, `complete` has a better chance
# to be inferred to have a concrete input type. Furthermore, since
# private types are unwrapped inside `complete`, a simpler type would
# be returned from `__foldl__`. This is probably why
# `complete`-inside-`__foldl__` approach is more compiler-friendly.
# On the other hand, if `complete` is called outside `__foldl__`, the
# compiler has to merge various types of nested objects returned from
# multiple locations. This easily leads to non-concrete types in the
# inference.
const FOLDL_RECURSION_LIMIT = Val(1)
# const FOLDL_RECURSION_LIMIT = nothing
_dec(::Nothing) = nothing
_dec(::Val{n}) where n = Val(n - 1)
function __foldl__(rf::RF, init::T, coll) where {RF,T}
ret = iterate(coll)
ret === nothing && return complete(rf, init)
x, state = ret
val = @next(rf, init, x)
@manual_union_split val isa T begin
return _foldl_iter(rf, val, coll, state, FOLDL_RECURSION_LIMIT)
end
end
@inline function _foldl_iter(rf::RF, val::T, iter, state, counter) where {RF,T}
while true
ret = iterate(iter, state)
ret === nothing && break
x, state = ret
y = @next(rf, val, x)
counter === Val(0) || y isa T ||
return _foldl_iter(rf, y, iter, state, _dec(counter))
val = y
end
return complete(rf, val)
end
@inline __foldl__(rf::RF, init, coll::Tuple) where {RF} =
complete(rf, @return_if_reduced foldlargs(rf, init, coll...))
@inline function __foldl__(rf::RF, init, arr0::Union{AbstractArray,Broadcasted}) where {RF}
arr = Broadcast.instantiate(arr0)
isempty(arr) && return complete(rf, init)
return _foldl_array(rf, init, arr, _IndexStyle(arr))
end
@inline function _foldl_array(rf::RF, init::T, arr, ::IndexLinear) where {RF,T}
i = _firstindex(arr)
acc = @next(rf, init, @inbounds arr[i])
@manual_union_split acc isa T begin
if is_prelude(acc)
return _foldl_linear_rec(rf, acc, arr, i + 1, FOLDL_RECURSION_LIMIT)
else
return _foldl_linear_bulk(rf, acc, arr, i + 1)
end
end
end
@inline function _foldl_linear_bulk(rf::RF, acc, arr, i0) where {RF}
@simd_if rf for i in i0:_lastindex(arr)
acc = @next(rf, acc, @inbounds arr[i])
end
return restack(complete(rf, acc))
end
@inline function _foldl_linear_rec(rf::RF, acc::T, arr, i0, counter) where {RF,T}
for i in i0:_lastindex(arr)
y = @next(rf, acc, @inbounds arr[i])
if counter !== Val(0)
if y isa T
elseif is_prelude(y)
return _foldl_linear_rec(rf, y, arr, i + 1, _dec(counter))
else
# Otherwise, maybe it could be something like `Union{Float64,Missing}`
# where Julia's native loop is fast:
return _foldl_linear_bulk(rf, y, arr, i + 1)
end
end
acc = y
end
return complete(rf, acc)
end
@inline function _foldl_array(rf0::RF, init, arr, ::IndexStyle) where {RF}
@inline getvalue(I) = @inbounds arr[I]
rf = Map(getvalue)'(rf0)
return __foldl__(rf, init, _CartesianIndices(arr))
end
@inline _getvalues(i) = ()
@inline _getvalues(i, a, rest...) = ((@inbounds a[i]), _getvalues(i, rest...)...)
# TODO: merge this with array implementation
@inline function __foldl__(
rf, init,
zs::Iterators.Zip{<:Tuple{Vararg{AbstractArray}}})
isempty(zs) && return complete(rf, init)
idxs = eachindex(zs.is...)
val = @next(rf, init, _getvalues(firstindex(idxs), zs.is...))
@simd_if rf for i in firstindex(idxs) + 1:lastindex(idxs)
val = @next(rf, val, _getvalues(i, zs.is...))
end
return complete(rf, val)
end
## Convert zip-of-products (ZoP) to product-of-zips (PoZ).
# Arguments for `product` and alike:
unproduct(x::Iterators.ProductIterator) = x.iterators
unproduct(x::CartesianIndices) = x.indices
unproduct(x::AbstractArray) = axes(x)
# After ZoP-to-PoZ transformation, we need to re-shape the value in
# the form that would be fed to the reducing function if it were
# folding `ZoP`:
@inline function _make_zop_getvalues(iterators)
# Avoid including `iterators` themselves in the closure if
# possible:
iterinfo = map(iterators) do itr
if itr isa CartesianIndices
Val(CartesianIndices)
elseif itr isa AbstractArray
itr
else
nothing
end
end
return function (xs)
map(_unzip((iterinfo, _unzip(xs)))) do (it, x)
if it === Val(CartesianIndices)
return CartesianIndex(x)
elseif it isa AbstractArray
return @inbounds it[x...]
else
return x
end
end
end
end
@inline __foldl__(
rf,
init,
zs::Iterators.Zip{<:Tuple{
Vararg{Union{AbstractArray,Iterators.ProductIterator}},
}},
) = __foldl__(
Reduction(Map(_make_zop_getvalues(zs.is)), rf),
init,
Iterators.product(map(splat(zip), _unzip(map(unproduct, zs.is)))...),
)
@inline function __foldl__(rf0, init, cartesian::CartesianIndices)
rf = Map(CartesianIndex)'(rf0)
val = _foldl_product(rf, init, (), cartesian.indices...)
val isa Reduced && return val
return complete(rf, val)
end
@inline function __foldl__(
rf, init,
prod::Iterators.ProductIterator{<:Tuple{Any,Any,Vararg{Any}}})
val = _foldl_product(rf, init, (), prod.iterators...)
val isa Reduced && return val
return complete(rf, val)
end
@noinline _foldl_product(rf, val, ::Any) = error("Unreachable")
@inline _foldl_product(rf, val, ::Tuple) = next(rf, val, ())
@inline function _foldl_product(rf, val, outer, iterators...)
inner_iterators, outer_iterator = _poptail(iterators)
for input in outer_iterator
val_ = _foldl_product(rf, val, (input, outer...), inner_iterators...)
val_ isa Reduced && return val_
val = val_
end
return val
end
@inline function _foldl_product(rf, val, outer, iterator)
# TODO: Handle the case inner iterators are tuples. In such case,
# inner-most non-tuple iterators should use @simd_if.
@simd_if rf for input in iterator
val = @next(rf, val, (input, outer...))
end
return val
end
function __simple_foldl__(rf, val, itr)
for x in itr
val = @next(rf, val, x)
end
return complete(rf, val)
end
"""
simple_transduce(xform, step, init, coll)
Simplified version of [`transduce`](@ref). For simple transducers Julia
may be able to emit a good code. This function exists only for
performance tuning.
"""
function simple_transduce(xform, f, init, coll)
rf = Reduction(xform, f)
return __simple_foldl__(rf, start(rf, init), coll)
end
"""
foldl_nocomplete(rf, init, coll)
Call [`__foldl__`](@ref) without calling [`complete`](@ref).
"""
@inline foldl_nocomplete(rf::RF, init, coll) where {RF} =
__foldl__(skipcomplete(rf), init, coll)
"""
foldl_basecase(rf, init, coll)
`foldl` for basecase of parallel reduction. Call [`__foldl__`](@ref) without
calling [`complete`](@ref) and then call `completebasecase`.
"""
@inline foldl_basecase(rf::RF, init, coll) where {RF} =
completebasecase(rf, __foldl__(skipcomplete(rf), init, coll))
"""
foldxl(step, xf::Transducer, reducible; init, simd) :: T
foldxl(step, reducible; init, simd) :: T
foldl(step, xf::Transducer, reducible; init, simd) :: T
foldl(step, ed::Eduction; init, simd) :: T
transduce(xf, step, init, reducible, [executor]; simd) :: Union{T, Reduced{T}}
e**X**tended **l**eft fold.
Compose transducer `xf` with reducing step function `step` and reduce
`itr` using it.
!!! note
`transduce` differs from `foldxl` as `Reduced{T}` is returned if
the transducer `xf` or `step` aborts the reduction and `step` is
_not_ automatically wrapped by [`Completing`](@ref).
This API is modeled after $(_cljref("transduce")).
For parallel versions, see [`foldxt`](@ref) and [`foldxd`](@ref).
See also: [Empty result handling](@ref).
# Arguments
- `xf::Transducer`: A transducer.
- `step`: A callable which accepts 1 and 2 arguments. If it only
accepts 2 arguments, wrap it with [`Completing`](@ref) to "add"
1-argument form (i.e., [`complete`](@ref) protocol).
- `reducible`: A reducible object (array, dictionary, any iterator, etc.).
- `executor`: Specify an executor. See [`SequentialEx`](@ref).
- `init`: An initial value fed to the first argument to reducing step
function `step`. This argument can be omitted for well know binary
operations like `+` or `*`. Supported binary operations are listed
in InitialValues.jl documentation. When `Init` (not the result of
`Init`, such as `Init(*)`) is given, it is automatically "instantiated"
as `Init(step)` (where `step` is appropriately unwrapped if `step` is
a `Completing`). See [Empty result handling](@ref) in the manual
for more information.
$_SIMD_OPT_DOCS
# Examples
```jldoctest
julia> using Transducers
julia> foldl(Filter(isodd), 1:4, init=0.0) do state, input
@show state, input
state + input
end
(state, input) = (0.0, 1)
(state, input) = (1.0, 3)
4.0
julia> foldxl(+, 1:5 |> Filter(isodd))
9
julia> 1:5 |> Filter(isodd) |> foldxl(+)
9
```
Since [`TeeRF`](@ref) requires the extended fold protocol,
`foldl(TeeRF(min, max), [5, 2, 6, 8, 3])` does not work while it works
with `foldxl`:
```jldoctest; setup = :(using Transducers)
julia> foldxl(TeeRF(min, max), [5, 2, 6, 8, 3])
(2, 8)
```
The unary method of `foldlx` is useful when combined with `|>`:
```jldoctest; setup = :(using Transducers)
julia> (1:5, 4:-1:1) |> Cat() |> Filter(isodd) |> Enumerate() |> foldxl() do a, b
a[2] < b[2] ? b : a
end
(3, 5)
```
"""
foldxl
foldxl(rf; kw...) = itr -> foldxl(rf, itr; kw...)
foldxl(rf, itr; kw...) = foldl(rf, extract_transducer(itr)...; kw...)
"""
foldl(step, xf::Transducer, reducible; init, simd) :: T
foldl(step, ed::Eduction; init, simd) :: T
See [`foldxl`](@ref).
"""
foldl
"""
transduce(xf, step, init, reducible) :: Union{T, Reduced{T}}
See [`foldxl`](@ref).
"""
transduce
const _MAPFOLDL_DEPWARN = (
"`mapfoldl(::Transducer, rf, itr)` is deprecated. " *
" Use `foldl(rf, ::Transducer, itr)` if you do not need to call single-argument" *
" `rf` on `complete`." *
" Use `foldl(whencomplete(rf, rf), ::Transducer, itr)` to call the" *
" single-argument method of `rf` on complete."
)
"""
mapfoldl(xf::Transducer, step, reducible; init, simd)
!!! warning
$_MAPFOLDL_DEPWARN
Like [`foldl`](@ref) but `step` is _not_ automatically wrapped by
[`Completing`](@ref).
# Examples
```julia
julia> using Transducers
julia> function step_demo(state, input)
@show state, input
state + input
end;
julia> function step_demo(state)
println("Finishing with state = ", state)
state
end;
julia> mapfoldl(Filter(isodd), step_demo, 1:4, init=0.0)
(state, input) = (0.0, 1)
(state, input) = (1.0, 3)
Finishing with state = 4.0
4.0
```
"""
mapfoldl
function transduce(xform::Transducer, f::F, init, coll; kwargs...) where {F}
rf = _reducingfunction(xform, f; init = init, kwargs...)
return transduce(rf, init, coll; kwargs...)
end
_unreduced__foldl__(rf, step, coll) = unreduced(__foldl__(rf, step, coll))
# TODO: should it be an internal?
@inline function transduce(
rf1::RF,
init,
coll;
simd::SIMDFlag = Val(false),
) where {RF<:AbstractReduction}
# Inlining `transduce` and `__foldl__` were essential for the
# `restack` below to work.
rf0, foldable = retransform(rf1, asfoldable(coll))
rf = maybe_usesimd(rf0, simd)
state = start(rf, init)
result = __foldl__(rf, state, foldable)
if unreduced(result) isa DefaultInitOf
throw(EmptyResultError(rf0))
# Should I check if `init` is a `DefaultInit`?
end
# At this point, `return result` is the semantically correct thing
# to do. What follows are some convoluted instructions to
# convince the compiler that this function is type-stable (in some
# cases). Note that return type would be inference-dependent only
# if `init` is a `OptInit` type. In the default case where `init
# isa DefaultInitOf`, the real code pass is the `throw` above.
# Unpacking as `ur_result` and re-packing it later somehow helps
# the compiler to correctly eliminate a possibility in a `Union`.
ur_result = unreduced(result)
if ur_result isa InferableInit
# Using `rf0` instead of `rf` helps the compiler. Note that
# this means that we are relying on that enabling SIMD does
# not change the return type.
realtype = _nonidtype(Core.Compiler.return_type(
_unreduced__foldl__,
typeof((rf0, state, foldable)),
))
if realtype isa Type
realvalue = convert(realtype, ur_result)
if result isa Reduced
return Reduced(realvalue)
else
return realvalue
end
end
end
if result isa Reduced
return Reduced(ur_result)
else
return ur_result
end
end
Base.mapfoldl(f::F, step::OP, itr::Foldable; kw...) where {F, OP} =
foldxl(step, Map(f), itr; kw...)
struct Eduction{F, C} <: Foldable
rf::F
coll::C
end
Eduction(xform::Transducer, coll) =
Eduction(Reduction(xform, Completing(push!!)), coll)
Eduction(xform::Transducer, ed::Eduction) =
Eduction(opcompose(Transducer(ed), xform), ed.coll)
Transducer(ed::Eduction) = Transducer(ed.rf)
transduce(xform::Transducer, f, init, ed::Eduction) =
transduce(opcompose(Transducer(ed), xform), f, init, ed.coll)
Base.IteratorSize(::Type{Eduction{F,C}}) where{F,C} =
outputsize(F) isa SizeStable ? Base.IteratorSize(C) : Base.SizeUnknown()
function Base.length(ed::Eduction)
@argcheck Base.IteratorSize(ed) isa Union{Base.HasLength,Base.HasShape}
return length(ed.coll)
end
function Base.size(ed::Eduction)
@argcheck Base.IteratorSize(ed) isa Base.HasShape
return size(ed.coll)
end
function Base.iterate(ts::Eduction, state = nothing)
if state === nothing
cret = iterate(ts.coll)
cret === nothing && return nothing
input, cstate = cret
result = start(ts.rf, Union{}[])
cdone = false
rdone = false
@goto step
# Assuming the initial `result` can never be `Reduced`.
else
cstate, cdone, result, rdone = state
end
if !cdone && !rdone
while isempty(unwrap_all(result))
cret = iterate(ts.coll, cstate)
if cret === nothing
cdone = true
result = complete(ts.rf, unreduced(result))
# Stateful transducers may have flushed something.
# Let's not `return nothing` yet.
break
end
input, cstate = cret
@label step
result = next(ts.rf, result, input)
if isreduced(result)
rdone = true
result = unreduced(result)
break
end
end
end
buffer = unwrap_all(result)
isempty(buffer) && return nothing
y = popfirst!(buffer)
next_state = (cstate, cdone, result, rdone)
return (y, next_state)
end
"""
eduction(xf::Transducer, coll)
xf(coll)
coll |> xf
Create a iterable and reducible object.
* [Iterable](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-iteration-1).
* Reducible; i.e., it can be handled by [`transduce`](@ref) efficiently.
This API is modeled after $(_cljref("eduction")).
!!! note
Even though `eduction` returns an iterable, it is highly
recommended to use the `foldl`-based method provided by
Transducers.jl when the performance is important.
# Examples
```jldoctest
julia> using Transducers
julia> for x in 1:1000 |> Filter(isodd) |> Take(3) # slow
@show x
end
x = 1
x = 3
x = 5
julia> foreach(1:1000 |> Filter(isodd) |> Take(3)) do x # better
@show x
end;
x = 1
x = 3
x = 5
```
"""
eduction(xform, coll) = Eduction(xform, coll)
# Note on `simd` keyword argument: `eduction` ATM does not support
# `simd` argument which could be done in principle. However, how
# `foldl` and `foreach` with `Eduction` treat `simd` argument must be
# tweaked if that happens.
#
# Note on API:
# Exporting `Eduction` could also work. But `Base` has, e.g.,
# `skipmissing` so maybe this is better for more uniform API.
"""
setinput(ed::Eduction, coll)
Set input collection of eduction `ed` to `coll`.
!!! compat "Transducers.jl 0.3"
Previously, `setinput` combined with `eduction` was a recommended
way to use transducers in a type stable manner. As of v0.3, all
the `foldl`-like functions and `eduction` are type stable for many
cases. This workaround is no more necessary.
# Examples
```jldoctest
julia> using Transducers
julia> ed = eduction(Map(x -> 2x), Float64[]);
julia> xs = ones(2, 3);
julia> foldl(+, setinput(ed, xs))
12.0
```
"""
setinput(ed::Eduction, coll) =
_setinput(eltype(ed.coll), eltype(coll), ed, coll)
_setinput(::Type{T}, ::Type{T}, ed, coll) where T = @set ed.coll = coll
_setinput(::Type, ::Type, ed, coll) = eduction(Transducer(ed), coll)
"""
append!(xf::Transducer, dest, src) -> dest
This API is modeled after $(_cljref("into")).
!!! warning
The performance of `append!(dest, src::Eduction)` is poor.
Use `append!!` instead if two-argument form is preferred.
# Examples
```jldoctest
julia> using Transducers
julia> append!(Drop(2), [-1, -2], 1:5)
5-element Vector{Int64}:
-1
-2
3
4
5
```
"""
Base.append!(xf::Transducer, to, from) =
unreduced(transduce(xf, Completing(push!), to, from))
"""
BangBang.append!!(xf::Transducer, dest, src) -> dest′
BangBang.append!!(dest, src::Eduction) -> dest′
Mutate-or-widen version of [`append!`](@ref).
!!! compat "Transducers.jl 0.4.4"
New in version 0.4.4.
!!! compat "Transducers.jl 0.4.37"
Performance optimization for `append!!(dest, src::Eduction)`
requires version 0.4.37.
# Examples
```jldoctest
julia> using Transducers, BangBang
julia> append!!(opcompose(Drop(2), Map(x -> x + 0.0)), [-1, -2], 1:5)
5-element Vector{Float64}:
-1.0
-2.0
3.0
4.0
5.0
```
"""
BangBang.append!!
BangBang.append!!(xf::Transducer, to, from) = unreduced(transduce(
Map(SingletonVector) ∘ xf,
Completing(append!!),
to,
from,
))
function BangBang.__appendto!!__(to, foldable::Foldable)
xf, from = extract_transducer(foldable)
return append!!(xf, to, from)
end
"""
collect(xf::Transducer, itr) :: Vector
collect(ed::Eduction) :: Vector
Process an iterable `itr` using a transducer `xf` and collect the result
into a `Vector`.
For parallel versions, see [`tcollect`](@ref) and [`dcollect`](@ref).
!!! compat "Transducers.jl 0.4.8"
`collect` now accepts eductions.
# Examples
```jldoctest
julia> using Transducers
julia> collect(Interpose(missing), 1:3)
5-element Vector{Union{Missing, Int64}}:
1
missing
2
missing
3
```
"""
Base.collect(xf::XF, coll) where {XF <: Transducer} = _collect(xf, coll, OutputSize(XF), Base.IteratorSize(coll))
Base.collect(foldable::Foldable) = collect(extract_transducer(foldable)...)
function _collect(xf, coll, ::Any, ::Any)
result = finish!(unreduced(transduce(
Map(SingletonVector) ∘ xf,
wheninit(collector, append!!),
collector(),
coll,
)))
if result isa Vector{Union{}}
et = @default_finaltype(xf, coll)
return et[]
end
return result
end
function _collect(xf, arr::Array, ::SizeStable, ::Union{Base.HasLength, Base.HasShape})
rf(coll, (i, val)) = @inbounds setindex!!(coll, val, i)
dest = UndefArray(size(arr)...)
unreduced(transduce(
Enumerate() ∘ xf,
wheninit(() -> dest, rf),
dest,
arr
))
end
"""
copy(xf::Transducer, T, foldable) :: Union{T, Empty{T}}
copy(xf::Transducer, foldable::T) :: Union{T, Empty{T}}
copy([T,] eduction::Eduction) :: Union{T, Empty{T}}
Process `foldable` with a transducer `xf` and then create a container of type `T`
filled with the result. Return
[`BangBang.Empty{T}`](https://juliafolds.github.io/BangBang.jl/dev/#BangBang.NoBang.Empty)
if the transducer does not produce anything. (This is because there is no
consistent interface to create an empty container given its type and not all
containers support creating an empty container.)
For parallel versions, see [`tcopy`](@ref) and [`dcopy`](@ref).
!!! compat "Transducers.jl 0.4.4"
New in version 0.4.4.
!!! compat "Transducers.jl 0.4.8"
`copy` now accepts eductions.
# Examples
```jldoctest
julia> using Transducers
using BangBang: Empty
julia> copy(Map(x -> x => x^2), Dict, 2:2)
Dict{Int64, Int64} with 1 entry:
2 => 4
julia> @assert copy(Filter(_ -> false), Set, 1:1) === Empty(Set)
julia> using TypedTables
julia> @assert copy(Map(x -> (a=x, b=x^2)), Table, 1:1) == Table(a=[1], b=[1])
julia> using StructArrays
julia> @assert copy(Map(x -> (a=x, b=x^2)), StructVector, 1:1) == StructVector(a=[1], b=[1])
julia> using DataFrames
julia> @assert copy(
Map(x -> (A = x.a + 1, B = x.b + 1)),
DataFrame(a = [1], b = [2]),
) == DataFrame(A = [2], B = [3])
```
"""
function Base.copy(xf::XF, T, foldable::F) where {XF <: Transducer, F}
_copy(xf, T, foldable, OutputSize(XF), Base.IteratorSize(F))
end
Base.copy(xf::Transducer, foldable) = copy(xf, _materializer(foldable), foldable)
function Base.copy(::Type{T}, ed::Foldable) where {T}
xf, foldable = extract_transducer(ed)
return copy(xf, T, foldable)
end
function Base.copy(ed::Foldable)
xf, foldable = extract_transducer(ed)
return copy(xf, foldable)
end
_copy(xf, ::Type{T}, foldable, ::Any, ::Any) where {T} = append!!(xf, Empty(T), foldable)
function _copy(xf, ::Type{Vector{<:Any}}, arr, ::SizeStable, ::Base.HasLength)
rf(coll, (i, val)) = @inbounds setindex!!(coll, val, i)
dest = UndefVector(length(arr))
unreduced(transduce(
Enumerate() ∘ xf,
wheninit(() -> dest, rf),
dest,
arr
))
end
function _copy(xf, ::Type{Array{<:Any, N}}, arr, ::SizeStable, ::Base.HasShape) where {N}
sz_arr = size(arr)
M = length(sz_arr)
if N > M
sz = (sz_arr..., ntuple(_ -> 1, N - ndims(arr))...)
elseif N < M
l, r = sz_arr[1:(N-1)], sz_arr[N:end]
sz = (l..., prod(r))
else
sz = sz_arr
end
rf(coll, (i, val)) = @inbounds setindex!!(coll, val, i)
dest = UndefArray(sz)
unreduced(transduce(
Enumerate() ∘ xf,
wheninit(() -> dest, rf),
dest,
arr
))
end
Base.Set(foldable::Foldable) = copy(Set, foldable)
Base.Dict(foldable::Foldable) = copy(Dict, foldable)
"""
map!(xf::Transducer, dest, src; simd)
Feed `src` to transducer `xf`, storing the result in `dest`.
Collections `dest` and `src` must have the same shape. Transducer
`xf` may contain filtering transducers. If some entries `src` are
skipped, the corresponding entries in `dest` will be unchanged.
Transducer `xf` must not contain any expansive transducers such as
[`MapCat`](@ref).
See also [`copy!`](@ref).
# Examples
```jldoctest
julia> using Transducers
julia> xs = collect(1:5)
ys = zero(xs)
map!(Filter(isodd), ys, xs)
5-element Vector{Int64}:
1
0
3
0
5
julia> ans === ys
true
```
"""
function Base.map!(xf::Transducer, dest::AbstractArray, src::AbstractArray;
simd::SIMDFlag = Val(false))
_map!(_prepare_map(xf, dest, src, simd)...)
return dest
end
_map!(rf, coll, dest) = transduce(restack(rf), nothing, coll)
# The idea behind `restack` (previously called `darkritual`):
# Deep-copy `AbstractReduction` so that compiler can treat the all
# reducing function tree nodes as local variables (???). Aslo, it
# tells compiler that `dest` is a local variable so that it won't
# fetch `dest` via `getproperty` in each iteration. (This is too much
# magic... My reasoning of how it works could be completely wrong.
# But at least it should not change the semantics of the function.)
# Probably related: /~https://github.com/JuliaLang/julia/pull/18632
function _prepare_map(xf, dest, src, simd)
isexpansive(xf) && error("map! only supports non-expanding transducer")
# TODO: support Dict
indices = eachindex(dest, src)
rf = reducingfunction(
opcompose(ZipSource(opcompose(GetIndex{true}(src), xf)), SetIndex{true}(dest)),
(::Vararg) -> nothing,
simd = simd)
return rf, indices, dest
end
"""
copy!(xf::Transducer, dest, src)
Feed `src` to transducer `xf`, storing the result in `dest`.
Collections `dest` and `src` may have the same shape. Source `src`
must be iterable. Destination `dest` must implement `empty!` and
`push!`.
See also [`map!`](@ref).