-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
lists.erl
3982 lines (3444 loc) · 117 KB
/
lists.erl
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
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(lists).
-moduledoc """
List processing functions.
This module contains functions for list processing.
Unless otherwise stated, all functions assume that position numbering starts
at 1. That is, the first element of a list is at position 1.
Two terms `T1` and `T2` compare equal if `T1 == T2` evaluates to `true`. They
match if `T1 =:= T2` evaluates to `true`.
Whenever an _ordering function_{: #ordering_function } `F` is expected as
argument, it is assumed that the following properties hold of `F` for all x, y,
and z:
- If x `F` y and y `F` x, then x = y (`F` is antisymmetric).
- If x `F` y and y `F` z, then x `F` z (`F` is transitive).
- x `F` y or y `F` x (`F` is total).
An example of a typical ordering function is less than or equal to: `=</2`.
""".
-compile({no_auto_import,[max/2]}).
-compile({no_auto_import,[min/2]}).
%% BIFs (implemented in the runtime system).
-export([keyfind/3, keymember/3, keysearch/3, member/2, reverse/2]).
%% Miscellaneous list functions that don't take funs as
%% arguments. Please keep in alphabetical order.
-export([append/1, append/2, concat/1,
delete/2, droplast/1, duplicate/2,
enumerate/1, enumerate/2, enumerate/3,
flatlength/1, flatten/1, flatten/2,
join/2, last/1, min/1, max/1,
nth/2, nthtail/2,
prefix/2, reverse/1, seq/2, seq/3,
split/2, sublist/2, sublist/3,
subtract/2, suffix/2, sum/1,
uniq/1, unzip/1, unzip3/1,
zip/2, zip/3, zip3/3, zip3/4]).
%% Functions taking a list of tuples and a position within the tuple.
-export([keydelete/3, keyreplace/4, keymap/3,
keytake/3, keystore/4]).
%% Sort functions that operate on list of tuples.
-export([keymerge/3, keysort/2, ukeymerge/3, ukeysort/2]).
%% Sort and merge functions.
-export([merge/1, merge/2, merge/3, merge3/3,
sort/1, sort/2,
umerge/1, umerge/2, umerge/3, umerge3/3,
usort/1, usort/2]).
%% Functions that take fun arguments (high-order functions). Please
%% keep in alphabetical order.
-export([all/2, any/2, dropwhile/2,
filter/2, filtermap/2, flatmap/2,
foldl/3, foldr/3, foreach/2,
map/2, mapfoldl/3, mapfoldr/3,
partition/2, search/2,
splitwith/2, takewhile/2, uniq/2,
zipwith/3, zipwith/4, zipwith3/4, zipwith3/5]).
%% Undocumented, but used within Erlang/OTP.
-export([zf/2]).
%% Undocumented and unused merge functions for lists sorted in reverse
%% order. They are exported so that the fundamental building blocks
%% for the sort functions can be tested. (Removing them would save
%% very little because they are thin wrappers calling helper functions
%% used by the documented sort functions.)
-export([rkeymerge/3, rmerge/2, rmerge/3, rmerge3/3,
rukeymerge/3, rumerge/2, rumerge/3, rumerge3/3]).
%% Shadowed by erl_bif_types: lists:keyfind/3
-doc """
Searches the list of tuples `TupleList` for a tuple whose `N`th element compares
equal to `Key`. Returns `Tuple` if such a tuple is found, otherwise `false`.
""".
-spec keyfind(Key, N, TupleList) -> Tuple | false when
Key :: term(),
N :: pos_integer(),
TupleList :: [Tuple],
Tuple :: tuple().
keyfind(_, _, _) ->
erlang:nif_error(undef).
%% Shadowed by erl_bif_types: lists:keymember/3
-doc """
Returns `true` if there is a tuple in `TupleList` whose `N`th element compares
equal to `Key`, otherwise `false`.
""".
-spec keymember(Key, N, TupleList) -> boolean() when
Key :: term(),
N :: pos_integer(),
TupleList :: [Tuple],
Tuple :: tuple().
keymember(_, _, _) ->
erlang:nif_error(undef).
%% Shadowed by erl_bif_types: lists:keysearch/3
-doc """
Searches the list of tuples `TupleList` for a tuple whose `N`th element compares
equal to `Key`. Returns `{value, Tuple}` if such a tuple is found, otherwise
`false`.
> #### Note {: .info }
>
> This function is retained for backward compatibility. Function `keyfind/3` is
> usually more convenient.
""".
-spec keysearch(Key, N, TupleList) -> {value, Tuple} | false when
Key :: term(),
N :: pos_integer(),
TupleList :: [Tuple],
Tuple :: tuple().
keysearch(_, _, _) ->
erlang:nif_error(undef).
%% Shadowed by erl_bif_types: lists:member/2
-doc "Returns `true` if `Elem` matches some element of `List`, otherwise `false`.".
-spec member(Elem, List) -> boolean() when
Elem :: T,
List :: [T],
T :: term().
member(_, _) ->
erlang:nif_error(undef).
%% Shadowed by erl_bif_types: lists:reverse/2
-doc """
Returns a list with the elements in `List1` in reverse order, with tail `Tail`
appended.
_Example:_
```erlang
> lists:reverse([1, 2, 3, 4], [a, b, c]).
[4,3,2,1,a,b,c]
```
""".
-spec reverse(List1, Tail) -> List2 when
List1 :: [T],
Tail :: term(),
List2 :: [T],
T :: term().
reverse(_, _) ->
erlang:nif_error(undef).
%%% End of BIFs
%% member(X, L) -> (true | false)
%% test if X is a member of the list L
%% Now a BIF!
%member(X, [X|_]) -> true;
%member(X, [_|Y]) ->
% member(X, Y);
%member(X, []) -> false.
%% append(X, Y) appends lists X and Y
-doc """
Returns a new list `List3`, which is made from the elements of `List1` followed
by the elements of `List2`.
_Example:_
```erlang
> lists:append("abc", "def").
"abcdef"
```
`lists:append(A, B)` is equivalent to `A ++ B`.
""".
-spec append(List1, List2) -> List3 when
List1 :: [T],
List2 :: [T],
List3 :: [T],
T :: term().
append(L1, L2) -> L1 ++ L2.
%% append(L) appends the list of lists L
-doc """
Returns a list in which all the sublists of `ListOfLists` have been appended.
_Example:_
```erlang
> lists:append([[1, 2, 3], [a, b], [4, 5, 6]]).
[1,2,3,a,b,4,5,6]
```
""".
-spec append(ListOfLists) -> List1 when
ListOfLists :: [List],
List :: [T],
List1 :: [T],
T :: term().
append([E]) -> E;
append([H|T]) -> H ++ append(T);
append([]) -> [].
%% subtract(List1, List2) subtract elements in List2 form List1.
-doc """
Returns a new list `List3` that is a copy of `List1`, subjected to the following
procedure: for each element in `List2`, its first occurrence in `List1` is
deleted.
_Example:_
```erlang
> lists:subtract("123212", "212").
"312".
```
`lists:subtract(A, B)` is equivalent to `A -- B`.
""".
-spec subtract(List1, List2) -> List3 when
List1 :: [T],
List2 :: [T],
List3 :: [T],
T :: term().
subtract(L1, L2) -> L1 -- L2.
%% reverse(L) reverse all elements in the list L. reverse/2 is now a BIF!
-doc "Returns a list with the elements in `List1` in reverse order.".
-spec reverse(List1) -> List2 when
List1 :: [T],
List2 :: [T],
T :: term().
reverse([] = L) ->
L;
reverse([_] = L) ->
L;
reverse([A, B]) ->
[B, A];
reverse([A, B | L]) ->
lists:reverse(L, [B, A]).
%reverse([H|T], Y) ->
% reverse(T, [H|Y]);
%reverse([], X) -> X.
%% nth(N, L) returns the N`th element of the list L
%% nthtail(N, L) returns the N`th tail of the list L
-doc """
Returns the `N`th element of `List`.
_Example:_
```erlang
> lists:nth(3, [a, b, c, d, e]).
c
```
""".
-spec nth(N, List) -> Elem when
N :: pos_integer(),
List :: [T,...],
Elem :: T,
T :: term().
nth(1, [H|_]) -> H;
nth(N, [_|_]=L) when is_integer(N), N > 1 ->
nth_1(N, L).
nth_1(1, [H|_]) -> H;
nth_1(N, [_|T]) ->
nth_1(N - 1, T).
-doc """
Returns the `N`th tail of `List`, that is, the sublist of `List` starting at
`N+1` and continuing up to the end of the list.
_Example_
```erlang
> lists:nthtail(3, [a, b, c, d, e]).
[d,e]
> tl(tl(tl([a, b, c, d, e]))).
[d,e]
> lists:nthtail(0, [a, b, c, d, e]).
[a,b,c,d,e]
> lists:nthtail(5, [a, b, c, d, e]).
[]
```
""".
-spec nthtail(N, List) -> Tail when
N :: non_neg_integer(),
List :: [T,...],
Tail :: [T],
T :: term().
nthtail(0, []) -> [];
nthtail(0, [_|_]=L) -> L;
nthtail(1, [_|T]) -> T;
nthtail(N, [_|_]=L) when is_integer(N), N > 1 ->
nthtail_1(N, L).
nthtail_1(1, [_|T]) -> T;
nthtail_1(N, [_|T]) ->
nthtail_1(N - 1, T).
%% prefix(Prefix, List) -> (true | false)
-doc "Returns `true` if `List1` is a prefix of `List2`, otherwise `false`.".
-spec prefix(List1, List2) -> boolean() when
List1 :: [T],
List2 :: [T],
T :: term().
prefix([X|PreTail], [X|Tail]) ->
prefix(PreTail, Tail);
prefix([], List) when is_list(List) -> true;
prefix([_|_], List) when is_list(List) -> false.
%% suffix(Suffix, List) -> (true | false)
-doc "Returns `true` if `List1` is a suffix of `List2`, otherwise `false`.".
-spec suffix(List1, List2) -> boolean() when
List1 :: [T],
List2 :: [T],
T :: term().
suffix(Suffix, List) ->
Delta = length(List) - length(Suffix),
Delta >= 0 andalso nthtail(Delta, List) =:= Suffix.
%% droplast(List) returns the list dropping its last element
-doc """
Drops the last element of a `List`. The list is to be non-empty, otherwise the
function crashes with a `function_clause`.
""".
-doc(#{since => <<"OTP 17.0">>}).
-spec droplast(List) -> InitList when
List :: [T, ...],
InitList :: [T],
T :: term().
%% This is the simple recursive implementation
%% reverse(tl(reverse(L))) is faster on average,
%% but creates more garbage.
droplast([_T]) -> [];
droplast([H|T]) -> [H|droplast(T)].
%% last(List) returns the last element in a list.
-doc "Returns the last element in `List`.".
-spec last(List) -> Last when
List :: [T,...],
Last :: T,
T :: term().
last([E|Es]) -> last(E, Es).
last(_, [E|Es]) -> last(E, Es);
last(E, []) -> E.
%% seq(Min, Max) -> [Min,Min+1, ..., Max]
%% seq(Min, Max, Incr) -> [Min,Min+Incr, ..., Max]
%% returns the sequence Min..Max
%% Min <= Max and Min and Max must be integers
-doc(#{equiv => seq(From, To, 1)}).
-spec seq(From, To) -> Seq when
From :: integer(),
To :: integer(),
Seq :: [integer()].
seq(First, Last)
when is_integer(First), is_integer(Last), First-1 =< Last ->
seq_loop(Last-First+1, Last, []).
seq_loop(N, X, L) when N >= 4 ->
seq_loop(N-4, X-4, [X-3,X-2,X-1,X|L]);
seq_loop(N, X, L) when N >= 2 ->
seq_loop(N-2, X-2, [X-1,X|L]);
seq_loop(1, X, L) ->
[X|L];
seq_loop(0, _, L) ->
L.
-doc """
Returns a sequence of integers that starts with `From` and contains the
successive results of adding `Incr` to the previous element, until `To` is
reached or passed (in the latter case, `To` is not an element of the sequence).
`Incr` defaults to 1.
Failures:
- If `To < From - Incr` and `Incr > 0`.
- If `To > From - Incr` and `Incr < 0`.
- If `Incr =:= 0` and `From =/= To`.
The following equalities hold for all sequences:
```erlang
length(lists:seq(From, To)) =:= To - From + 1
length(lists:seq(From, To, Incr)) =:= (To - From + Incr) div Incr
```
_Examples:_
```erlang
> lists:seq(1, 10).
[1,2,3,4,5,6,7,8,9,10]
> lists:seq(1, 20, 3).
[1,4,7,10,13,16,19]
> lists:seq(1, 0, 1).
[]
> lists:seq(10, 6, 4).
[]
> lists:seq(1, 1, 0).
[1]
```
""".
-spec seq(From, To, Incr) -> Seq when
From :: integer(),
To :: integer(),
Incr :: integer(),
Seq :: [integer()].
seq(First, Last, Inc)
when is_integer(First), is_integer(Last), is_integer(Inc),
(Inc > 0 andalso First - Inc =< Last) orelse
(Inc < 0 andalso First - Inc >= Last) ->
N = (Last - First + Inc) div Inc,
seq_loop(N, Inc * (N - 1) + First, Inc, []);
seq(Same, Same, 0) when is_integer(Same) ->
[Same];
seq(First, Last, Inc) ->
erlang:error(badarg, [First, Last, Inc], [{error_info, #{module => erl_stdlib_errors}}]).
seq_loop(N, X, D, L) when N >= 4 ->
Y = X-D, Z = Y-D, W = Z-D,
seq_loop(N-4, W-D, D, [W,Z,Y,X|L]);
seq_loop(N, X, D, L) when N >= 2 ->
Y = X-D,
seq_loop(N-2, Y-D, D, [Y,X|L]);
seq_loop(1, X, _, L) ->
[X|L];
seq_loop(0, _, _, L) ->
L.
%% sum(L) returns the sum of the elements in L
-doc "Returns the sum of the elements in `List`.".
-spec sum(List) -> number() when
List :: [number()].
sum(L) -> sum(L, 0).
sum([H|T], Sum) -> sum(T, Sum + H);
sum([], Sum) -> Sum.
%% duplicate(N, X) -> [X,X,X,.....,X] (N times)
%% return N copies of X
-doc """
Returns a list containing `N` copies of term `Elem`.
_Example:_
```erlang
> lists:duplicate(5, xx).
[xx,xx,xx,xx,xx]
```
""".
-spec duplicate(N, Elem) -> List when
N :: non_neg_integer(),
Elem :: T,
List :: [T],
T :: term().
duplicate(N, X) when is_integer(N), N >= 0 -> duplicate(N, X, []).
duplicate(0, _, L) -> L;
duplicate(N, X, L) -> duplicate(N-1, X, [X|L]).
%% min(L) -> returns the minimum element of the list L
-doc """
Returns the first element of `List` that compares less than or equal to all
other elements of `List`.
""".
-spec min(List) -> Min when
List :: [T,...],
Min :: T,
T :: term().
min([H|T]) -> min(T, H).
min([H|T], Min) when H < Min -> min(T, H);
min([_|T], Min) -> min(T, Min);
min([], Min) -> Min.
%% max(L) -> returns the maximum element of the list L
-doc """
Returns the first element of `List` that compares greater than or equal to all
other elements of `List`.
""".
-spec max(List) -> Max when
List :: [T,...],
Max :: T,
T :: term().
max([H|T]) -> max(T, H).
max([H|T], Max) when H > Max -> max(T, H);
max([_|T], Max) -> max(T, Max);
max([], Max) -> Max.
%% sublist(List, Start, Length)
%% Returns the sub-list starting at Start of length Length.
-doc """
Returns the sublist of `List1` starting at `Start` and with (maximum) `Len`
elements. It is not an error for `Start+Len` to exceed the length of the list.
_Examples:_
```erlang
> lists:sublist([1,2,3,4], 2, 2).
[2,3]
> lists:sublist([1,2,3,4], 2, 5).
[2,3,4]
> lists:sublist([1,2,3,4], 5, 2).
[]
```
""".
-spec sublist(List1, Start, Len) -> List2 when
List1 :: [T],
List2 :: [T],
Start :: pos_integer(),
Len :: non_neg_integer(),
T :: term().
sublist(List, 1, L) when is_list(List), is_integer(L), L >= 0 ->
sublist(List, L);
sublist([], S, _L) when is_integer(S), S >= 2 ->
[];
sublist([_H|T], S, L) when is_integer(S), S >= 2 ->
sublist(T, S-1, L).
-doc """
Returns the sublist of `List1` starting at position 1 and with (maximum) `Len`
elements. It is not an error for `Len` to exceed the length of the list, in that
case the whole list is returned.
""".
-spec sublist(List1, Len) -> List2 when
List1 :: [T],
List2 :: [T],
Len :: non_neg_integer(),
T :: term().
sublist(List, L) when is_integer(L), is_list(List) ->
sublist_2(List, L).
sublist_2([H|T], L) when L > 0 ->
[H|sublist_2(T, L-1)];
sublist_2(_, 0) ->
[];
sublist_2(List, L) when is_list(List), L > 0 ->
[].
%% delete(Item, List) -> List'
%% Delete the first occurrence of Item from the list L.
-doc """
Returns a copy of `List1` where the first element matching `Elem` is deleted, if
there is such an element.
""".
-spec delete(Elem, List1) -> List2 when
Elem :: T,
List1 :: [T],
List2 :: [T],
T :: term().
delete(Item, [Item|Rest]) -> Rest;
delete(Item, [H|Rest]) ->
[H|delete(Item, Rest)];
delete(_, []) -> [].
%% Return [{X0, Y0}, {X1, Y1}, ..., {Xn, Yn}] for lists [X0, X1, ...,
%% Xn] and [Y0, Y1, ..., Yn].
-doc(#{equiv => zip(List1, List2, fail)}).
-spec zip(List1, List2) -> List3 when
List1 :: [A],
List2 :: [B],
List3 :: [{A, B}],
A :: term(),
B :: term().
zip(Xs, Ys) -> zip(Xs, Ys, fail).
-doc """
"Zips" two lists into one list of two-tuples, where the first element of each
tuple is taken from the first list and the second element is taken from the
corresponding element in the second list.
The `How` parameter specifies the behavior if the given lists are of different
lengths.
- **`fail`** - The call will fail if the given lists are not of equal length.
This is the default.
- **`trim`** - Surplus elements from the longer list will be ignored.
_Examples:_
```erlang
> lists:zip([a, b], [1, 2, 3], trim).
[{a,1},{b,2}]
> lists:zip([a, b, c], [1, 2], trim).
[{a,1},{b,2}]
```
- **`{pad, Defaults}`** - The shorter list will be padded to the length of the
longer list, using the respective elements from the given `Defaults` tuple.
_Examples:_
```erlang
> lists:zip([a, b], [1, 2, 3], {pad, {x, 0}}).
[{a,1},{b,2},{x,3}]
> lists:zip([a, b, c], [1, 2], {pad, {x, 0}}).
[{a,1},{b,2},{c,0}]
```
""".
-doc(#{since => <<"OTP 26.0">>}).
-spec zip(List1, List2, How) -> List3 when
List1 :: [A],
List2 :: [B],
List3 :: [{A | DefaultA, B | DefaultB}],
A :: term(),
B :: term(),
How :: 'fail' | 'trim' | {'pad', {DefaultA, DefaultB}},
DefaultA :: term(),
DefaultB :: term().
zip([X | Xs], [Y | Ys], How) ->
[{X, Y} | zip(Xs, Ys, How)];
zip([], [], fail) ->
[];
zip([], [], trim) ->
[];
zip([], [], {pad, {_, _}}) ->
[];
zip([_ | _], [], trim) ->
[];
zip([], [_ | _], trim) ->
[];
zip([], [_ | _]=Ys, {pad, {X, _}}) ->
[{X, Y} || Y <- Ys];
zip([_ | _]=Xs, [], {pad, {_, Y}}) ->
[{X, Y} || X <- Xs].
%% Return {[X0, X1, ..., Xn], [Y0, Y1, ..., Yn]}, for a list [{X0, Y0},
%% {X1, Y1}, ..., {Xn, Yn}].
-doc """
"Unzips" a list of two-tuples into two lists, where the first list contains the
first element of each tuple, and the second list contains the second element of
each tuple.
""".
-spec unzip(List1) -> {List2, List3} when
List1 :: [{A, B}],
List2 :: [A],
List3 :: [B],
A :: term(),
B :: term().
unzip(Ts) -> unzip(Ts, [], []).
unzip([{X, Y} | Ts], Xs, Ys) -> unzip(Ts, [X | Xs], [Y | Ys]);
unzip([], Xs, Ys) -> {reverse(Xs), reverse(Ys)}.
%% Return [{X0, Y0, Z0}, {X1, Y1, Z1}, ..., {Xn, Yn, Zn}] for lists [X0,
%% X1, ..., Xn], [Y0, Y1, ..., Yn] and [Z0, Z1, ..., Zn].
-doc(#{equiv => zip3(List1, List2, List3, fail)}).
-spec zip3(List1, List2, List3) -> List4 when
List1 :: [A],
List2 :: [B],
List3 :: [C],
List4 :: [{A, B, C}],
A :: term(),
B :: term(),
C :: term().
zip3(Xs, Ys, Zs) -> zip3(Xs, Ys, Zs, fail).
-doc """
"Zips" three lists into one list of three-tuples, where the first element of
each tuple is taken from the first list, the second element is taken from the
corresponding element in the second list, and the third element is taken from
the corresponding element in the third list.
For a description of the `How` parameter, see `zip/3`.
""".
-doc(#{since => <<"OTP 26.0">>}).
-spec zip3(List1, List2, List3, How) -> List4 when
List1 :: [A],
List2 :: [B],
List3 :: [C],
List4 :: [{A | DefaultA, B | DefaultB, C | DefaultC}],
A :: term(),
B :: term(),
C :: term(),
How :: 'fail' | 'trim' | {'pad', {DefaultA, DefaultB, DefaultC}},
DefaultA :: term(),
DefaultB :: term(),
DefaultC :: term().
zip3([X | Xs], [Y | Ys], [Z | Zs], How) ->
[{X, Y, Z} | zip3(Xs, Ys, Zs, How)];
zip3([], [], [], fail) ->
[];
zip3([], [], [], trim) ->
[];
zip3(Xs, Ys, Zs, trim) when is_list(Xs), is_list(Ys), is_list(Zs) ->
[];
zip3([], [], [], {pad, {_, _, _}}) ->
[];
zip3([], [], [_ |_]=Zs, {pad, {X, Y, _}}) ->
[{X, Y, Z} || Z <- Zs];
zip3([], [_ | _]=Ys, [], {pad, {X, _, Z}}) ->
[{X, Y, Z} || Y <- Ys];
zip3([_ | _]=Xs, [], [], {pad, {_, Y, Z}}) ->
[{X, Y, Z} || X <- Xs];
zip3([], [Y | Ys], [Z | Zs], {pad, {X, _, _}} = How) ->
[{X, Y, Z} | zip3([], Ys, Zs, How)];
zip3([X | Xs], [], [Z | Zs], {pad, {_, Y, _}} = How) ->
[{X, Y, Z} | zip3(Xs, [], Zs, How)];
zip3([X | Xs], [Y | Ys], [], {pad, {_, _, Z}} = How) ->
[{X, Y, Z} | zip3(Xs, Ys, [], How)].
%% Return {[X0, X1, ..., Xn], [Y0, Y1, ..., Yn], [Z0, Z1, ..., Zn]}, for
%% a list [{X0, Y0, Z0}, {X1, Y1, Z1}, ..., {Xn, Yn, Zn}].
-doc """
"Unzips" a list of three-tuples into three lists, where the first list contains
the first element of each tuple, the second list contains the second element of
each tuple, and the third list contains the third element of each tuple.
""".
-spec unzip3(List1) -> {List2, List3, List4} when
List1 :: [{A, B, C}],
List2 :: [A],
List3 :: [B],
List4 :: [C],
A :: term(),
B :: term(),
C :: term().
unzip3(Ts) -> unzip3(Ts, [], [], []).
unzip3([{X, Y, Z} | Ts], Xs, Ys, Zs) ->
unzip3(Ts, [X | Xs], [Y | Ys], [Z | Zs]);
unzip3([], Xs, Ys, Zs) ->
{reverse(Xs), reverse(Ys), reverse(Zs)}.
%% Return [F(X0, Y0), F(X1, Y1), ..., F(Xn, Yn)] for lists [X0, X1, ...,
%% Xn] and [Y0, Y1, ..., Yn].
-doc(#{equiv => zipwith(Combine, List1, List2, fail)}).
-spec zipwith(Combine, List1, List2) -> List3 when
Combine :: fun((X, Y) -> T),
List1 :: [X],
List2 :: [Y],
List3 :: [T],
X :: term(),
Y :: term(),
T :: term().
zipwith(F, Xs, Ys) -> zipwith(F, Xs, Ys, fail).
-doc """
Combines the elements of two lists into one list. For each pair `X, Y` of list
elements from the two lists, the element in the result list is `Combine(X, Y)`.
For a description of the `How` parameter, see `zip/3`.
[`zipwith(fun(X, Y) -> {X,Y} end, List1, List2)`](`zipwith/3`) is equivalent to
[`zip(List1, List2)`](`zip/2`).
_Example:_
```erlang
> lists:zipwith(fun(X, Y) -> X+Y end, [1,2,3], [4,5,6]).
[5,7,9]
```
""".
-doc(#{since => <<"OTP 26.0">>}).
-spec zipwith(Combine, List1, List2, How) -> List3 when
Combine :: fun((X | DefaultX, Y | DefaultY) -> T),
List1 :: [X],
List2 :: [Y],
List3 :: [T],
X :: term(),
Y :: term(),
How :: 'fail' | 'trim' | {'pad', {DefaultX, DefaultY}},
DefaultX :: term(),
DefaultY :: term(),
T :: term().
zipwith(F, [X | Xs], [Y | Ys], How) ->
[F(X, Y) | zipwith(F, Xs, Ys, How)];
zipwith(F, [], [], fail) when is_function(F, 2) ->
[];
zipwith(F, [], [], trim) when is_function(F, 2) ->
[];
zipwith(F, [], [], {pad, {_, _}}) when is_function(F, 2) ->
[];
zipwith(F, [_ | _], [], trim) when is_function(F, 2) ->
[];
zipwith(F, [], [_ | _], trim) when is_function(F, 2) ->
[];
zipwith(F, [], [_ | _]=Ys, {pad, {X, _}}) ->
[F(X, Y) || Y <- Ys];
zipwith(F, [_ | _]=Xs, [], {pad, {_, Y}}) ->
[F(X, Y) || X <- Xs].
%% Return [F(X0, Y0, Z0), F(X1, Y1, Z1), ..., F(Xn, Yn, Zn)] for lists
%% [X0, X1, ..., Xn], [Y0, Y1, ..., Yn] and [Z0, Z1, ..., Zn].
-doc(#{equiv => zipwith3(Combine, List1, List2, List3, fail)}).
-spec zipwith3(Combine, List1, List2, List3) -> List4 when
Combine :: fun((X, Y, Z) -> T),
List1 :: [X],
List2 :: [Y],
List3 :: [Z],
List4 :: [T],
X :: term(),
Y :: term(),
Z :: term(),
T :: term().
zipwith3(F, Xs, Ys, Zs) -> zipwith3(F, Xs, Ys, Zs, fail).
-doc """
Combines the elements of three lists into one list. For each triple `X, Y, Z` of
list elements from the three lists, the element in the result list is
`Combine(X, Y, Z)`.
For a description of the `How` parameter, see `zip/3`.
[`zipwith3(fun(X, Y, Z) -> {X,Y,Z} end, List1, List2, List3)`](`zipwith3/4`) is
equivalent to [`zip3(List1, List2, List3)`](`zip3/3`).
_Examples:_
```erlang
> lists:zipwith3(fun(X, Y, Z) -> X+Y+Z end, [1,2,3], [4,5,6], [7,8,9]).
[12,15,18]
> lists:zipwith3(fun(X, Y, Z) -> [X,Y,Z] end, [a,b,c], [x,y,z], [1,2,3]).
[[a,x,1],[b,y,2],[c,z,3]]
```
""".
-doc(#{since => <<"OTP 26.0">>}).
-spec zipwith3(Combine, List1, List2, List3, How) -> List4 when
Combine :: fun((X | DefaultX, Y | DefaultY, Z | DefaultZ) -> T),
List1 :: [X],
List2 :: [Y],
List3 :: [Z],
List4 :: [T],
X :: term(),
Y :: term(),
Z :: term(),
How :: 'fail' | 'trim' | {'pad', {DefaultX, DefaultY, DefaultZ}},
DefaultX :: term(),
DefaultY :: term(),
DefaultZ :: term(),
T :: term().
zipwith3(F, [X | Xs], [Y | Ys], [Z | Zs], How) ->
[F(X, Y, Z) | zipwith3(F, Xs, Ys, Zs, How)];
zipwith3(F, [], [], [], fail) when is_function(F, 3) ->
[];
zipwith3(F, [], [], [], trim) when is_function(F, 3) ->
[];
zipwith3(F, Xs, Ys, Zs, trim) when is_function(F, 3), is_list(Xs), is_list(Ys), is_list(Zs) ->
[];
zipwith3(F, [], [], [], {pad, {_, _, _}}) when is_function(F, 3) ->
[];
zipwith3(F, [], [], [_ | _]=Zs, {pad, {X, Y, _}}) ->
[F(X, Y, Z) || Z <- Zs];
zipwith3(F, [], [_ | _]=Ys, [], {pad, {X, _, Z}}) ->
[F(X, Y, Z) || Y <- Ys];
zipwith3(F, [_ | _]=Xs, [], [], {pad, {_, Y, Z}}) ->
[F(X, Y, Z) || X <- Xs];
zipwith3(F, [], [Y | Ys], [Z | Zs], {pad, {X, _, _}} = How) ->
[F(X, Y, Z) | zipwith3(F, [], Ys, Zs, How)];
zipwith3(F, [X | Xs], [], [Z | Zs], {pad, {_, Y, _}} = How) ->
[F(X, Y, Z) | zipwith3(F, Xs, [], Zs, How)];
zipwith3(F, [X | Xs], [Y | Ys], [], {pad, {_, _, Z}} = How) ->
[F(X, Y, Z) | zipwith3(F, Xs, Ys, [], How)].
%% sort(List) -> L
%% sorts the list L
-doc "Returns a list containing the sorted elements of `List1`.".
-spec sort(List1) -> List2 when
List1 :: [T],
List2 :: [T],
T :: term().
sort([X, Y | L] = L0) when X =< Y ->
case L of
[] ->
L0;
[Z] when Y =< Z ->
L0;
[Z] when X =< Z ->
[X, Z, Y];
[Z] ->
[Z, X, Y];
_ when X == Y ->
sort_1(Y, L, [X]);
_ ->
split_1(X, Y, L, [], [])
end;
sort([X, Y | L]) ->
case L of
[] ->
[Y, X];
[Z] when X =< Z ->
[Y, X | L];
[Z] when Y =< Z ->
[Y, Z, X];
[Z] ->
[Z, Y, X];
_ ->
split_2(X, Y, L, [], [])
end;
sort([_] = L) ->
L;
sort([] = L) ->
L.
sort_1(X, [Y | L], R) when X == Y ->
sort_1(Y, L, [X | R]);
sort_1(X, [Y | L], R) when X < Y ->
split_1(X, Y, L, R, []);
sort_1(X, [Y | L], R) ->
split_2(X, Y, L, R, []);
sort_1(X, [], R) ->
lists:reverse(R, [X]).
%% merge(List) -> L
%% merges a list of sorted lists
-doc """
Returns the sorted list formed by merging all the sublists of `ListOfLists`. All
sublists must be sorted before evaluating this function.
When two elements compare equal, the element from the sublist with the lowest
position in `ListOfLists` is picked before the other element.
""".
-spec merge(ListOfLists) -> List1 when
ListOfLists :: [List],
List :: [T],
List1 :: [T],