-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
enum.ex
4869 lines (3710 loc) · 139 KB
/
enum.ex
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
defprotocol Enumerable do
@moduledoc """
Enumerable protocol used by `Enum` and `Stream` modules.
When you invoke a function in the `Enum` module, the first argument
is usually a collection that must implement this protocol.
For example, the expression `Enum.map([1, 2, 3], &(&1 * 2))`
invokes `Enumerable.reduce/3` to perform the reducing operation that
builds a mapped list by calling the mapping function `&(&1 * 2)` on
every element in the collection and consuming the element with an
accumulated list.
Internally, `Enum.map/2` is implemented as follows:
def map(enumerable, fun) do
reducer = fn x, acc -> {:cont, [fun.(x) | acc]} end
Enumerable.reduce(enumerable, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()
end
Note that the user-supplied function is wrapped into a `t:reducer/0` function.
The `t:reducer/0` function must return a tagged tuple after each step,
as described in the `t:acc/0` type. At the end, `Enumerable.reduce/3`
returns `t:result/0`.
This protocol uses tagged tuples to exchange information between the
reducer function and the data type that implements the protocol. This
allows enumeration of resources, such as files, to be done efficiently
while also guaranteeing the resource will be closed at the end of the
enumeration. This protocol also allows suspension of the enumeration,
which is useful when interleaving between many enumerables is required
(as in the `zip/1` and `zip/2` functions).
This protocol requires four functions to be implemented, `reduce/3`,
`count/1`, `member?/2`, and `slice/1`. The core of the protocol is the
`reduce/3` function. All other functions exist as optimizations paths
for data structures that can implement certain properties in better
than linear time.
"""
@typedoc """
An enumerable of elements of type `element`.
This type is equivalent to `t:t/0` but is especially useful for documentation.
For example, imagine you define a function that expects an enumerable of
integers and returns an enumerable of strings:
@spec integers_to_strings(Enumerable.t(integer())) :: Enumerable.t(String.t())
def integers_to_strings(integers) do
Stream.map(integers, &Integer.to_string/1)
end
"""
@typedoc since: "1.14.0"
@type t(_element) :: t()
@typedoc """
The accumulator value for each step.
It must be a tagged tuple with one of the following "tags":
* `:cont` - the enumeration should continue
* `:halt` - the enumeration should halt immediately
* `:suspend` - the enumeration should be suspended immediately
Depending on the accumulator value, the result returned by
`Enumerable.reduce/3` will change. Please check the `t:result/0`
type documentation for more information.
In case a `t:reducer/0` function returns a `:suspend` accumulator,
it must be explicitly handled by the caller and never leak.
"""
@type acc :: {:cont, term} | {:halt, term} | {:suspend, term}
@typedoc """
The reducer function.
Should be called with the `enumerable` element and the
accumulator contents.
Returns the accumulator for the next enumeration step.
"""
@type reducer :: (element :: term, current_acc :: acc -> updated_acc :: acc)
@typedoc """
The result of the reduce operation.
It may be *done* when the enumeration is finished by reaching
its end, or *halted*/*suspended* when the enumeration was halted
or suspended by the tagged accumulator.
In case the tagged `:halt` accumulator is given, the `:halted` tuple
with the accumulator must be returned. Functions like `Enum.take_while/2`
use `:halt` underneath and can be used to test halting enumerables.
In case the tagged `:suspend` accumulator is given, the caller must
return the `:suspended` tuple with the accumulator and a continuation.
The caller is then responsible of managing the continuation and the
caller must always call the continuation, eventually halting or continuing
until the end. `Enum.zip/2` uses suspension, so it can be used to test
whether your implementation handles suspension correctly. You can also use
`Stream.zip/2` with `Enum.take_while/2` to test the combination of
`:suspend` with `:halt`.
"""
@type result ::
{:done, term}
| {:halted, term}
| {:suspended, term, continuation}
@typedoc """
A partially applied reduce function.
The continuation is the closure returned as a result when
the enumeration is suspended. When invoked, it expects
a new accumulator and it returns the result.
A continuation can be trivially implemented as long as the reduce
function is defined in a tail recursive fashion. If the function
is tail recursive, all the state is passed as arguments, so
the continuation is the reducing function partially applied.
"""
@type continuation :: (acc -> result)
@typedoc """
A slicing function that receives the initial position,
the number of elements in the slice, and the step.
The `start` position is a number `>= 0` and guaranteed to
exist in the `enumerable`. The length is a number `>= 1`
in a way that `start + length * step <= count`, where
`count` is the maximum amount of elements in the enumerable.
The function should return a non empty list where
the amount of elements is equal to `length`.
"""
@type slicing_fun ::
(start :: non_neg_integer, length :: pos_integer, step :: pos_integer -> [term()])
@typedoc """
Receives an enumerable and returns a list.
"""
@type to_list_fun :: (t -> [term()])
@doc """
Reduces the `enumerable` into an element.
Most of the operations in `Enum` are implemented in terms of reduce.
This function should apply the given `t:reducer/0` function to each
element in the `enumerable` and proceed as expected by the returned
accumulator.
See the documentation of the types `t:result/0` and `t:acc/0` for
more information.
## Examples
As an example, here is the implementation of `reduce` for lists:
def reduce(_list, {:halt, acc}, _fun), do: {:halted, acc}
def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}
def reduce([], {:cont, acc}, _fun), do: {:done, acc}
def reduce([head | tail], {:cont, acc}, fun), do: reduce(tail, fun.(head, acc), fun)
"""
@spec reduce(t, acc, reducer) :: result
def reduce(enumerable, acc, fun)
@doc """
Retrieves the number of elements in the `enumerable`.
It should return `{:ok, count}` if you can count the number of elements
in `enumerable` in a faster way than fully traversing it.
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
built on top of `reduce/3` that runs in linear time will be used.
"""
@spec count(t) :: {:ok, non_neg_integer} | {:error, module}
def count(enumerable)
@doc """
Checks if an `element` exists within the `enumerable`.
It should return `{:ok, boolean}` if you can check the membership of a
given element in `enumerable` with `===/2` without traversing the whole
of it.
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
built on top of `reduce/3` that runs in linear time will be used.
When called outside guards, the [`in`](`in/2`) and [`not in`](`in/2`)
operators work by using this function.
"""
@spec member?(t, term) :: {:ok, boolean} | {:error, module}
def member?(enumerable, element)
@doc """
Returns a function that slices the data structure contiguously.
It should return either:
* `{:ok, size, slicing_fun}` - if the `enumerable` has a known
bound and can access a position in the `enumerable` without
traversing all previous elements. The `slicing_fun` will receive
a `start` position, the `amount` of elements to fetch, and a
`step`.
* `{:ok, size, to_list_fun}` - if the `enumerable` has a known bound
and can access a position in the `enumerable` by first converting
it to a list via `to_list_fun`.
* `{:error, __MODULE__}` - the enumerable cannot be sliced efficiently
and a default algorithm built on top of `reduce/3` that runs in
linear time will be used.
## Differences to `count/1`
The `size` value returned by this function is used for boundary checks,
therefore it is extremely important that this function only returns `:ok`
if retrieving the `size` of the `enumerable` is cheap, fast, and takes
constant time. Otherwise the simplest of operations, such as
`Enum.at(enumerable, 0)`, will become too expensive.
On the other hand, the `count/1` function in this protocol should be
implemented whenever you can count the number of elements in the collection
without traversing it.
"""
@spec slice(t) ::
{:ok, size :: non_neg_integer(), slicing_fun() | to_list_fun()}
| {:error, module()}
def slice(enumerable)
end
defmodule Enum do
import Kernel, except: [max: 2, min: 2]
@moduledoc """
Functions for working with collections (known as enumerables).
In Elixir, an enumerable is any data type that implements the
`Enumerable` protocol. `List`s (`[1, 2, 3]`), `Map`s (`%{foo: 1, bar: 2}`)
and `Range`s (`1..3`) are common data types used as enumerables:
iex> Enum.map([1, 2, 3], fn x -> x * 2 end)
[2, 4, 6]
iex> Enum.sum([1, 2, 3])
6
iex> Enum.map(1..3, fn x -> x * 2 end)
[2, 4, 6]
iex> Enum.sum(1..3)
6
iex> map = %{"a" => 1, "b" => 2}
iex> Enum.map(map, fn {k, v} -> {k, v * 2} end)
[{"a", 2}, {"b", 4}]
However, many other enumerables exist in the language, such as `MapSet`s
and the data type returned by `File.stream!/3` which allows a file to be
traversed as if it was an enumerable.
The functions in this module work in linear time. This means that, the
time it takes to perform an operation grows at the same rate as the length
of the enumerable. This is expected on operations such as `Enum.map/2`.
After all, if we want to traverse every element on a list, the longer the
list, the more elements we need to traverse, and the longer it will take.
This linear behaviour should also be expected on operations like `count/1`,
`member?/2`, `at/2` and similar. While Elixir does allow data types to
provide performant variants for such operations, you should not expect it
to always be available, since the `Enum` module is meant to work with a
large variety of data types and not all data types can provide optimized
behaviour.
Finally, note the functions in the `Enum` module are eager: they will
traverse the enumerable as soon as they are invoked. This is particularly
dangerous when working with infinite enumerables. In such cases, you should
use the `Stream` module, which allows you to lazily express computations,
without traversing collections, and work with possibly infinite collections.
See the `Stream` module for examples and documentation.
"""
@compile :inline_list_funcs
@type t :: Enumerable.t()
@type acc :: any
@type element :: any
@typedoc "Zero-based index. It can also be a negative integer."
@type index :: integer
@type default :: any
require Stream.Reducers, as: R
defmacrop skip(acc) do
acc
end
defmacrop next(_, entry, acc) do
quote(do: [unquote(entry) | unquote(acc)])
end
defmacrop acc(head, state, _) do
quote(do: {unquote(head), unquote(state)})
end
defmacrop next_with_acc(_, entry, head, state, _) do
quote do
{[unquote(entry) | unquote(head)], unquote(state)}
end
end
@doc """
Returns `true` if all elements in `enumerable` are truthy.
When an element has a falsy value (`false` or `nil`) iteration stops immediately
and `false` is returned. In all other cases `true` is returned.
## Examples
iex> Enum.all?([1, 2, 3])
true
iex> Enum.all?([1, nil, 3])
false
iex> Enum.all?([])
true
"""
@spec all?(t) :: boolean
def all?(enumerable) when is_list(enumerable) do
all_list(enumerable)
end
def all?(enumerable) do
Enumerable.reduce(enumerable, {:cont, true}, fn entry, _ ->
if entry, do: {:cont, true}, else: {:halt, false}
end)
|> elem(1)
end
@doc """
Returns `true` if `fun.(element)` is truthy for all elements in `enumerable`.
Iterates over `enumerable` and invokes `fun` on each element. If `fun` ever
returns a falsy value (`false` or `nil`), iteration stops immediately and
`false` is returned. Otherwise, `true` is returned.
## Examples
iex> Enum.all?([2, 4, 6], fn x -> rem(x, 2) == 0 end)
true
iex> Enum.all?([2, 3, 4], fn x -> rem(x, 2) == 0 end)
false
iex> Enum.all?([], fn _ -> nil end)
true
As the last example shows, `Enum.all?/2` returns `true` if `enumerable` is
empty, regardless of `fun`. In an empty enumerable there is no element for
which `fun` returns a falsy value, so the result must be `true`. This is a
well-defined logical argument for empty collections.
"""
@spec all?(t, (element -> as_boolean(term))) :: boolean
def all?(enumerable, fun) when is_list(enumerable) do
predicate_list(enumerable, true, fun)
end
def all?(first..last//step, fun) do
predicate_range(first, last, step, true, fun)
end
def all?(enumerable, fun) do
Enumerable.reduce(enumerable, {:cont, true}, fn entry, _ ->
if fun.(entry), do: {:cont, true}, else: {:halt, false}
end)
|> elem(1)
end
@doc """
Returns `true` if at least one element in `enumerable` is truthy.
When an element has a truthy value (neither `false` nor `nil`) iteration stops
immediately and `true` is returned. In all other cases `false` is returned.
## Examples
iex> Enum.any?([false, false, false])
false
iex> Enum.any?([false, true, false])
true
iex> Enum.any?([])
false
"""
@spec any?(t) :: boolean
def any?(enumerable) when is_list(enumerable) do
any_list(enumerable)
end
def any?(enumerable) do
Enumerable.reduce(enumerable, {:cont, false}, fn entry, _ ->
if entry, do: {:halt, true}, else: {:cont, false}
end)
|> elem(1)
end
@doc """
Returns `true` if `fun.(element)` is truthy for at least one element in `enumerable`.
Iterates over the `enumerable` and invokes `fun` on each element. When an invocation
of `fun` returns a truthy value (neither `false` nor `nil`) iteration stops
immediately and `true` is returned. In all other cases `false` is returned.
## Examples
iex> Enum.any?([2, 4, 6], fn x -> rem(x, 2) == 1 end)
false
iex> Enum.any?([2, 3, 4], fn x -> rem(x, 2) == 1 end)
true
iex> Enum.any?([], fn x -> x > 0 end)
false
"""
@spec any?(t, (element -> as_boolean(term))) :: boolean
def any?(enumerable, fun) when is_list(enumerable) do
predicate_list(enumerable, false, fun)
end
def any?(first..last//step, fun) do
predicate_range(first, last, step, false, fun)
end
def any?(enumerable, fun) do
Enumerable.reduce(enumerable, {:cont, false}, fn entry, _ ->
if fun.(entry), do: {:halt, true}, else: {:cont, false}
end)
|> elem(1)
end
@doc """
Finds the element at the given `index` (zero-based).
Returns `default` if `index` is out of bounds.
A negative `index` can be passed, which means the `enumerable` is
enumerated once and the `index` is counted from the end (for example,
`-1` finds the last element).
## Examples
iex> Enum.at([2, 4, 6], 0)
2
iex> Enum.at([2, 4, 6], 2)
6
iex> Enum.at([2, 4, 6], 4)
nil
iex> Enum.at([2, 4, 6], 4, :none)
:none
"""
@spec at(t, index, default) :: element | default
def at(enumerable, index, default \\ nil) when is_integer(index) do
case slice_forward(enumerable, index, 1, 1) do
[value] -> value
[] -> default
end
end
@doc false
@deprecated "Use Enum.chunk_every/2 instead"
def chunk(enumerable, count), do: chunk(enumerable, count, count, nil)
@doc false
@deprecated "Use Enum.chunk_every/3 instead"
def chunk(enum, n, step) do
chunk_every(enum, n, step, :discard)
end
@doc false
@deprecated "Use Enum.chunk_every/4 instead"
def chunk(enumerable, count, step, leftover) do
chunk_every(enumerable, count, step, leftover || :discard)
end
@doc """
Shortcut to `chunk_every(enumerable, count, count)`.
"""
@doc since: "1.5.0"
@spec chunk_every(t, pos_integer) :: [list]
def chunk_every(enumerable, count), do: chunk_every(enumerable, count, count, [])
@doc """
Returns list of lists containing `count` elements each, where
each new chunk starts `step` elements into the `enumerable`.
`step` is optional and, if not passed, defaults to `count`, i.e.
chunks do not overlap. Chunking will stop as soon as the collection
ends or when we emit an incomplete chunk.
If the last chunk does not have `count` elements to fill the chunk,
elements are taken from `leftover` to fill in the chunk. If `leftover`
does not have enough elements to fill the chunk, then a partial chunk
is returned with less than `count` elements.
If `:discard` is given in `leftover`, the last chunk is discarded
unless it has exactly `count` elements.
## Examples
iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 2)
[[1, 2], [3, 4], [5, 6]]
iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, :discard)
[[1, 2, 3], [3, 4, 5]]
iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, [7])
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
iex> Enum.chunk_every([1, 2, 3, 4], 3, 3, [])
[[1, 2, 3], [4]]
iex> Enum.chunk_every([1, 2, 3, 4], 10)
[[1, 2, 3, 4]]
iex> Enum.chunk_every([1, 2, 3, 4, 5], 2, 3, [])
[[1, 2], [4, 5]]
iex> Enum.chunk_every([1, 2, 3, 4], 3, 3, Stream.cycle([0]))
[[1, 2, 3], [4, 0, 0]]
"""
@doc since: "1.5.0"
@spec chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list]
def chunk_every(enumerable, count, step, leftover \\ [])
when is_integer(count) and count > 0 and is_integer(step) and step > 0 do
R.chunk_every(&chunk_while/4, enumerable, count, step, leftover)
end
@doc """
Chunks the `enumerable` with fine grained control when every chunk is emitted.
`chunk_fun` receives the current element and the accumulator and must return:
* `{:cont, chunk, acc}` to emit a chunk and continue with the accumulator
* `{:cont, acc}` to not emit any chunk and continue with the accumulator
* `{:halt, acc}` to halt chunking over the `enumerable`.
`after_fun` is invoked with the final accumulator when iteration is
finished (or `halt`ed) to handle any trailing elements that were returned
as part of an accumulator, but were not emitted as a chunk by `chunk_fun`.
It must return:
* `{:cont, chunk, acc}` to emit a chunk. The chunk will be appended to the
list of already emitted chunks.
* `{:cont, acc}` to not emit a chunk
The `acc` in `after_fun` is required in order to mirror the tuple format
from `chunk_fun` but it will be discarded since the traversal is complete.
Returns a list of emitted chunks.
## Examples
iex> chunk_fun = fn element, acc ->
...> if rem(element, 2) == 0 do
...> {:cont, Enum.reverse([element | acc]), []}
...> else
...> {:cont, [element | acc]}
...> end
...> end
iex> after_fun = fn
...> [] -> {:cont, []}
...> acc -> {:cont, Enum.reverse(acc), []}
...> end
iex> Enum.chunk_while(1..10, [], chunk_fun, after_fun)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
iex> Enum.chunk_while([1, 2, 3, 5, 7], [], chunk_fun, after_fun)
[[1, 2], [3, 5, 7]]
"""
@doc since: "1.5.0"
@spec chunk_while(
t,
acc,
(element, acc -> {:cont, chunk, acc} | {:cont, acc} | {:halt, acc}),
(acc -> {:cont, chunk, acc} | {:cont, acc})
) :: Enumerable.t()
when chunk: any
def chunk_while(enumerable, acc, chunk_fun, after_fun) do
{_, {res, acc}} =
Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn entry, {buffer, acc} ->
case chunk_fun.(entry, acc) do
{:cont, chunk, acc} -> {:cont, {[chunk | buffer], acc}}
{:cont, acc} -> {:cont, {buffer, acc}}
{:halt, acc} -> {:halt, {buffer, acc}}
end
end)
case after_fun.(acc) do
{:cont, _acc} -> :lists.reverse(res)
{:cont, chunk, _acc} -> :lists.reverse([chunk | res])
end
end
@doc """
Splits enumerable on every element for which `fun` returns a new
value.
Returns a list of lists.
## Examples
iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))
[[1], [2, 2], [3], [4, 4, 6], [7, 7]]
"""
@spec chunk_by(t, (element -> any)) :: [list]
def chunk_by(enumerable, fun) do
R.chunk_by(&chunk_while/4, enumerable, fun)
end
@doc """
Given an enumerable of enumerables, concatenates the `enumerables` into
a single list.
## Examples
iex> Enum.concat([1..3, 4..6, 7..9])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
iex> Enum.concat([[1, [2], 3], [4], [5, 6]])
[1, [2], 3, 4, 5, 6]
"""
@spec concat(t) :: t
def concat(enumerables)
def concat(list) when is_list(list) do
concat_list(list)
end
def concat(enums) do
concat_enum(enums)
end
@doc """
Concatenates the enumerable on the `right` with the enumerable on the
`left`.
This function produces the same result as the `++/2` operator
for lists.
## Examples
iex> Enum.concat(1..3, 4..6)
[1, 2, 3, 4, 5, 6]
iex> Enum.concat([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
"""
@spec concat(t, t) :: t
def concat(left, right) when is_list(left) and is_list(right) do
left ++ right
end
def concat(left, right) do
concat_enum([left, right])
end
@doc """
Returns the size of the `enumerable`.
## Examples
iex> Enum.count([1, 2, 3])
3
"""
@spec count(t) :: non_neg_integer
def count(enumerable) when is_list(enumerable) do
length(enumerable)
end
def count(enumerable) do
case Enumerable.count(enumerable) do
{:ok, value} when is_integer(value) ->
value
{:error, module} ->
enumerable |> module.reduce({:cont, 0}, fn _, acc -> {:cont, acc + 1} end) |> elem(1)
end
end
@doc """
Returns the count of elements in the `enumerable` for which `fun` returns
a truthy value.
## Examples
iex> Enum.count([1, 2, 3, 4, 5], fn x -> rem(x, 2) == 0 end)
2
"""
@spec count(t, (element -> as_boolean(term))) :: non_neg_integer
def count(enumerable, fun) do
reduce(enumerable, 0, fn entry, acc ->
if(fun.(entry), do: acc + 1, else: acc)
end)
end
@doc """
Counts the enumerable stopping at `limit`.
This is useful for checking certain properties of the count of an enumerable
without having to actually count the entire enumerable. For example, if you
wanted to check that the count was exactly, at least, or more than a value.
If the enumerable implements `c:Enumerable.count/1`, the enumerable is
not traversed and we return the lower of the two numbers. To force
enumeration, use `count_until/3` with `fn _ -> true end` as the second
argument.
## Examples
iex> Enum.count_until(1..20, 5)
5
iex> Enum.count_until(1..20, 50)
20
iex> Enum.count_until(1..10, 10) == 10 # At least 10
true
iex> Enum.count_until(1..11, 10 + 1) > 10 # More than 10
true
iex> Enum.count_until(1..5, 10) < 10 # Less than 10
true
iex> Enum.count_until(1..10, 10 + 1) == 10 # Exactly ten
true
"""
@doc since: "1.12.0"
@spec count_until(t, pos_integer) :: non_neg_integer
def count_until(enumerable, limit) when is_integer(limit) and limit > 0 do
stop_at = limit - 1
case Enumerable.count(enumerable) do
{:ok, value} ->
Kernel.min(value, limit)
{:error, module} ->
enumerable
|> module.reduce(
{:cont, 0},
fn
_, ^stop_at ->
{:halt, limit}
_, acc ->
{:cont, acc + 1}
end
)
|> elem(1)
end
end
@doc """
Counts the elements in the enumerable for which `fun` returns a truthy value, stopping at `limit`.
See `count/2` and `count_until/2` for more information.
## Examples
iex> Enum.count_until(1..20, fn x -> rem(x, 2) == 0 end, 7)
7
iex> Enum.count_until(1..20, fn x -> rem(x, 2) == 0 end, 11)
10
"""
@doc since: "1.12.0"
@spec count_until(t, (element -> as_boolean(term)), pos_integer) :: non_neg_integer
def count_until(enumerable, fun, limit) when is_integer(limit) and limit > 0 do
stop_at = limit - 1
Enumerable.reduce(enumerable, {:cont, 0}, fn
entry, ^stop_at ->
if fun.(entry) do
{:halt, limit}
else
{:cont, stop_at}
end
entry, acc ->
if fun.(entry) do
{:cont, acc + 1}
else
{:cont, acc}
end
end)
|> elem(1)
end
@doc """
Enumerates the `enumerable`, returning a list where all consecutive
duplicated elements are collapsed to a single element.
Elements are compared using `===/2`.
If you want to remove all duplicated elements, regardless of order,
see `uniq/1`.
## Examples
iex> Enum.dedup([1, 2, 3, 3, 2, 1])
[1, 2, 3, 2, 1]
iex> Enum.dedup([1, 1, 2, 2.0, :three, :three])
[1, 2, 2.0, :three]
"""
@spec dedup(t) :: list
def dedup(enumerable) when is_list(enumerable) do
dedup_list(enumerable, []) |> :lists.reverse()
end
def dedup(enumerable) do
Enum.reduce(enumerable, [], fn x, acc ->
case acc do
[^x | _] -> acc
_ -> [x | acc]
end
end)
|> :lists.reverse()
end
@doc """
Enumerates the `enumerable`, returning a list where all consecutive
duplicated elements are collapsed to a single element.
The function `fun` maps every element to a term which is used to
determine if two elements are duplicates.
## Examples
iex> Enum.dedup_by([{1, :a}, {2, :b}, {2, :c}, {1, :a}], fn {x, _} -> x end)
[{1, :a}, {2, :b}, {1, :a}]
iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end)
[5, 1, 3, 2]
"""
@spec dedup_by(t, (element -> term)) :: list
def dedup_by(enumerable, fun) do
{list, _} = reduce(enumerable, {[], []}, R.dedup(fun))
:lists.reverse(list)
end
@doc """
Drops the `amount` of elements from the `enumerable`.
If a negative `amount` is given, the `amount` of last values will be dropped.
The `enumerable` will be enumerated once to retrieve the proper index and
the remaining calculation is performed from the end.
## Examples
iex> Enum.drop([1, 2, 3], 2)
[3]
iex> Enum.drop([1, 2, 3], 10)
[]
iex> Enum.drop([1, 2, 3], 0)
[1, 2, 3]
iex> Enum.drop([1, 2, 3], -1)
[1, 2]
"""
@spec drop(t, integer) :: list
def drop(enumerable, amount)
when is_list(enumerable) and is_integer(amount) and amount >= 0 do
drop_list(enumerable, amount)
end
def drop(enumerable, 0) do
to_list(enumerable)
end
def drop(enumerable, amount) when is_integer(amount) and amount > 0 do
{result, _} = reduce(enumerable, {[], amount}, R.drop())
if is_list(result), do: :lists.reverse(result), else: []
end
def drop(enumerable, amount) when is_integer(amount) and amount < 0 do
{count, fun} = slice_count_and_fun(enumerable, 1)
amount = Kernel.min(amount + count, count)
if amount > 0 do
fun.(0, amount, 1)
else
[]
end
end
@doc """
Returns a list of every `nth` element in the `enumerable` dropped,
starting with the first element.
The first element is always dropped, unless `nth` is 0.
The second argument specifying every `nth` element must be a non-negative
integer.
## Examples
iex> Enum.drop_every(1..10, 2)
[2, 4, 6, 8, 10]
iex> Enum.drop_every(1..10, 0)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
iex> Enum.drop_every([1, 2, 3], 1)
[]
"""
@spec drop_every(t, non_neg_integer) :: list
def drop_every(enumerable, nth)
def drop_every(_enumerable, 1), do: []
def drop_every(enumerable, 0), do: to_list(enumerable)
def drop_every([], nth) when is_integer(nth), do: []
def drop_every(enumerable, nth) when is_integer(nth) and nth > 1 do
{res, _} = reduce(enumerable, {[], :first}, R.drop_every(nth))
:lists.reverse(res)
end
@doc """
Drops elements at the beginning of the `enumerable` while `fun` returns a
truthy value.
## Examples
iex> Enum.drop_while([1, 2, 3, 2, 1], fn x -> x < 3 end)
[3, 2, 1]
"""
@spec drop_while(t, (element -> as_boolean(term))) :: list
def drop_while(enumerable, fun) when is_list(enumerable) do
drop_while_list(enumerable, fun)
end
def drop_while(enumerable, fun) do
{res, _} = reduce(enumerable, {[], true}, R.drop_while(fun))
:lists.reverse(res)
end
@doc """
Invokes the given `fun` for each element in the `enumerable`.
Returns `:ok`.
## Examples
Enum.each(["some", "example"], fn x -> IO.puts(x) end)
"some"
"example"
#=> :ok
"""
@spec each(t, (element -> any)) :: :ok
def each(enumerable, fun) when is_list(enumerable) do
:lists.foreach(fun, enumerable)
end
def each(enumerable, fun) do
reduce(enumerable, nil, fn entry, _ ->
fun.(entry)
nil
end)
:ok
end
@doc """
Determines if the `enumerable` is empty.
Returns `true` if `enumerable` is empty, otherwise `false`.