/
list.ex
1404 lines (1029 loc) · 37 KB
/
list.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
defmodule List do
@moduledoc """
Linked lists hold zero, one, or more elements in the chosen order.
Lists in Elixir are specified between square brackets:
iex> [1, "two", 3, :four]
[1, "two", 3, :four]
Two lists can be concatenated and subtracted using the
`++/2` and `--/2` operators:
iex> [1, 2, 3] ++ [4, 5, 6]
[1, 2, 3, 4, 5, 6]
iex> [1, true, 2, false, 3, true] -- [true, false]
[1, 2, 3, true]
An element can be prepended to a list using `|`:
iex> new = 0
iex> list = [1, 2, 3]
iex> [new | list]
[0, 1, 2, 3]
Lists in Elixir are effectively linked lists, which means
they are internally represented in pairs containing the
head and the tail of a list:
iex> [head | tail] = [1, 2, 3]
iex> head
1
iex> tail
[2, 3]
Similarly, we could write the list `[1, 2, 3]` using only
such pairs (called cons cells):
iex> [1 | [2 | [3 | []]]]
[1, 2, 3]
Some lists, called improper lists, do not have an empty list as
the second element in the last cons cell:
iex> [1 | [2 | [3 | 4]]]
[1, 2, 3 | 4]
Although improper lists are generally avoided, they are used in some
special circumstances like iodata and chardata entities (see the `IO` module).
Due to their cons cell based representation, prepending an element
to a list is always fast (constant time), while appending becomes
slower as the list grows in size (linear time):
iex> list = [1, 2, 3]
iex> [0 | list] # fast
[0, 1, 2, 3]
iex> list ++ [4] # slow
[1, 2, 3, 4]
Most of the functions in this module work in linear time. This means that,
that the time it takes to perform an operation grows at the same rate as the
length of the list. For example `length/1` and `last/1` will run in linear
time because they need to iterate through every element of the list, but
`first/1` will run in constant time because it only needs the first element.
Lists also implement the `Enumerable` protocol, so many functions to work with
lists are found in the `Enum` module. Additionally, the following functions and
operators for lists are found in `Kernel`:
* `++/2`
* `--/2`
* `hd/1`
* `tl/1`
* `in/2`
* `length/1`
## Charlists
If a list is made of non-negative integers, where each integer represents a
Unicode code point, the list can also be called a charlist. These integers
must:
* be within the range `0..0x10FFFF` (`0..1_114_111`);
* and be out of the range `0xD800..0xDFFF` (`55_296..57_343`), which is
reserved in Unicode for UTF-16 surrogate pairs.
Elixir uses the [`~c` sigil](`sigil_c/2`) to define charlists:
iex> ~c"héllo"
[104, 233, 108, 108, 111]
In particular, charlists will be printed back by default with the `~c`
sigil if they contain only printable ASCII characters:
iex> ~c"abc"
~c"abc"
Even though the representation changed, the raw data does remain a list of
integers, which can be handled as such:
iex> inspect(~c"abc", charlists: :as_list)
"[97, 98, 99]"
iex> Enum.map(~c"abc", fn num -> 1000 + num end)
[1097, 1098, 1099]
You can use the `IEx.Helpers.i/1` helper to get a condensed rundown on
charlists in IEx when you encounter them, which shows you the type, description
and also the raw representation in one single summary.
The rationale behind this behaviour is to better support
Erlang libraries which may return text as charlists
instead of Elixir strings. In Erlang, charlists are the default
way of handling strings, while in Elixir it's binaries. One
example of such functions is `Application.loaded_applications/0`:
Application.loaded_applications()
#=> [
#=> {:stdlib, ~c"ERTS CXC 138 10", ~c"2.6"},
#=> {:compiler, ~c"ERTS CXC 138 10", ~c"6.0.1"},
#=> {:elixir, ~c"elixir", ~c"1.0.0"},
#=> {:kernel, ~c"ERTS CXC 138 10", ~c"4.1"},
#=> {:logger, ~c"logger", ~c"1.0.0"}
#=> ]
A list can be checked if it is made of only printable ASCII
characters with `ascii_printable?/2`.
Improper lists are never deemed as charlists.
"""
@compile :inline_list_funcs
@doc """
Deletes the given `element` from the `list`. Returns a new list without
the element.
If the `element` occurs more than once in the `list`, just
the first occurrence is removed.
## Examples
iex> List.delete([:a, :b, :c], :a)
[:b, :c]
iex> List.delete([:a, :b, :c], :d)
[:a, :b, :c]
iex> List.delete([:a, :b, :b, :c], :b)
[:a, :b, :c]
iex> List.delete([], :b)
[]
"""
@spec delete([], any) :: []
@spec delete([...], any) :: list
def delete(list, element)
def delete([element | list], element), do: list
def delete([other | list], element), do: [other | delete(list, element)]
def delete([], _element), do: []
@doc """
Duplicates the given element `n` times in a list.
`n` is an integer greater than or equal to `0`.
If `n` is `0`, an empty list is returned.
## Examples
iex> List.duplicate("hello", 0)
[]
iex> List.duplicate("hi", 1)
["hi"]
iex> List.duplicate("bye", 2)
["bye", "bye"]
iex> List.duplicate([1, 2], 3)
[[1, 2], [1, 2], [1, 2]]
"""
@spec duplicate(any, 0) :: []
@spec duplicate(elem, pos_integer) :: [elem, ...] when elem: var
def duplicate(elem, n) do
:lists.duplicate(n, elem)
end
@doc """
Flattens the given `list` of nested lists.
Empty list elements are discarded.
## Examples
iex> List.flatten([1, [[2], 3]])
[1, 2, 3]
iex> List.flatten([[], [[], []]])
[]
"""
@spec flatten(deep_list) :: list when deep_list: [any | deep_list]
def flatten(list) do
:lists.flatten(list)
end
@doc """
Flattens the given `list` of nested lists.
The list `tail` will be added at the end of
the flattened list.
Empty list elements from `list` are discarded,
but not the ones from `tail`.
## Examples
iex> List.flatten([1, [[2], 3]], [4, 5])
[1, 2, 3, 4, 5]
iex> List.flatten([1, [], 2], [3, [], 4])
[1, 2, 3, [], 4]
"""
@spec flatten(deep_list, [elem]) :: [elem] when elem: var, deep_list: [elem | deep_list]
def flatten(list, tail) do
:lists.flatten(list, tail)
end
@doc """
Folds (reduces) the given list from the left with
a function. Requires an accumulator, which can be any value.
## Examples
iex> List.foldl([5, 5], 10, fn x, acc -> x + acc end)
20
iex> List.foldl([1, 2, 3, 4], 0, fn x, acc -> x - acc end)
2
iex> List.foldl([1, 2, 3], {0, 0}, fn x, {a1, a2} -> {a1 + x, a2 - x} end)
{6, -6}
"""
@spec foldl([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
def foldl(list, acc, fun) when is_list(list) and is_function(fun) do
:lists.foldl(fun, acc, list)
end
@doc """
Folds (reduces) the given list from the right with
a function. Requires an accumulator, which can be any value.
## Examples
iex> List.foldr([1, 2, 3, 4], 0, fn x, acc -> x - acc end)
-2
iex> List.foldr([1, 2, 3, 4], %{sum: 0, product: 1}, fn x, %{sum: a1, product: a2} -> %{sum: a1 + x, product: a2 * x} end)
%{product: 24, sum: 10}
"""
@spec foldr([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
def foldr(list, acc, fun) when is_list(list) and is_function(fun) do
:lists.foldr(fun, acc, list)
end
@doc """
Returns the first element in `list` or `default` if `list` is empty.
`first/2` has been introduced in Elixir v1.12.0, while `first/1` has been available since v1.0.0.
## Examples
iex> List.first([])
nil
iex> List.first([], 1)
1
iex> List.first([1])
1
iex> List.first([1, 2, 3])
1
"""
@spec first([], any) :: any
@spec first([elem, ...], any) :: elem when elem: var
def first(list, default \\ nil)
def first([], default), do: default
def first([head | _], _default), do: head
@doc """
Returns the last element in `list` or `default` if `list` is empty.
`last/2` has been introduced in Elixir v1.12.0, while `last/1` has been available since v1.0.0.
## Examples
iex> List.last([])
nil
iex> List.last([], 1)
1
iex> List.last([1])
1
iex> List.last([1, 2, 3])
3
"""
@spec last([], any) :: any
@spec last([elem, ...], any) :: elem when elem: var
@compile {:inline, last: 2}
def last(list, default \\ nil)
def last([], default), do: default
def last([head], _default), do: head
def last([_ | tail], default), do: last(tail, default)
@doc """
Receives a list of tuples and returns the first tuple
where the element at `position` in the tuple matches the
given `key`.
If no matching tuple is found, `default` is returned.
## Examples
iex> List.keyfind([a: 1, b: 2], :a, 0)
{:a, 1}
iex> List.keyfind([a: 1, b: 2], 2, 1)
{:b, 2}
iex> List.keyfind([a: 1, b: 2], :c, 0)
nil
This function works for any list of tuples:
iex> List.keyfind([{22, "SSH"}, {80, "HTTP"}], 22, 0)
{22, "SSH"}
"""
@spec keyfind([tuple], any, non_neg_integer, any) :: any
def keyfind(list, key, position, default \\ nil) when is_integer(position) do
:lists.keyfind(key, position + 1, list) || default
end
@doc """
Receives a list of tuples and returns the first tuple
where the element at `position` in the tuple matches the
given `key`.
If no matching tuple is found, an error is raised.
## Examples
iex> List.keyfind!([a: 1, b: 2], :a, 0)
{:a, 1}
iex> List.keyfind!([a: 1, b: 2], 2, 1)
{:b, 2}
iex> List.keyfind!([a: 1, b: 2], :c, 0)
** (KeyError) key :c at position 0 not found in: [a: 1, b: 2]
This function works for any list of tuples:
iex> List.keyfind!([{22, "SSH"}, {80, "HTTP"}], 22, 0)
{22, "SSH"}
"""
@doc since: "1.13.0"
@spec keyfind!([tuple], any, non_neg_integer) :: any
def keyfind!(list, key, position) when is_integer(position) do
:lists.keyfind(key, position + 1, list) ||
raise KeyError,
key: key,
term: list,
message:
"key #{inspect(key)} at position #{inspect(position)} not found in: #{inspect(list)}"
end
@doc """
Receives a list of tuples and returns `true` if there is
a tuple where the element at `position` in the tuple matches
the given `key`.
## Examples
iex> List.keymember?([a: 1, b: 2], :a, 0)
true
iex> List.keymember?([a: 1, b: 2], 2, 1)
true
iex> List.keymember?([a: 1, b: 2], :c, 0)
false
This function works for any list of tuples:
iex> List.keymember?([{22, "SSH"}, {80, "HTTP"}], 22, 0)
true
"""
@spec keymember?([tuple], any, non_neg_integer) :: boolean
def keymember?(list, key, position) when is_integer(position) do
:lists.keymember(key, position + 1, list)
end
@doc """
Receives a list of tuples and if the identified element by `key` at `position`
exists, it is replaced with `new_tuple`.
## Examples
iex> List.keyreplace([a: 1, b: 2], :a, 0, {:a, 3})
[a: 3, b: 2]
iex> List.keyreplace([a: 1, b: 2], :a, 1, {:a, 3})
[a: 1, b: 2]
This function works for any list of tuples:
iex> List.keyreplace([{22, "SSH"}, {80, "HTTP"}], 22, 0, {22, "Secure Shell"})
[{22, "Secure Shell"}, {80, "HTTP"}]
"""
@spec keyreplace([tuple], any, non_neg_integer, tuple) :: [tuple]
def keyreplace(list, key, position, new_tuple) when is_integer(position) do
:lists.keyreplace(key, position + 1, list, new_tuple)
end
@doc """
Receives a list of tuples and sorts the elements
at `position` of the tuples.
The sort is stable.
A `sorter` argument is available since Elixir v1.14.0. Similar to
`Enum.sort/2`, the sorter can be an anonymous function, the atoms
`:asc` or `:desc`, or module that implements a compare function.
## Examples
iex> List.keysort([a: 5, b: 1, c: 3], 1)
[b: 1, c: 3, a: 5]
iex> List.keysort([a: 5, c: 1, b: 3], 0)
[a: 5, b: 3, c: 1]
To sort in descending order:
iex> List.keysort([a: 5, c: 1, b: 3], 0, :desc)
[c: 1, b: 3, a: 5]
As in `Enum.sort/2`, avoid using the default sorting function to sort
structs, as by default it performs structural comparison instead of a
semantic one. In such cases, you shall pass a sorting function as third
element or any module that implements a `compare/2` function. For example,
if you have tuples with user names and their birthday, and you want to
sort on their birthday, in both ascending and descending order, you should
do:
iex> users = [
...> {"Ellis", ~D[1943-05-11]},
...> {"Lovelace", ~D[1815-12-10]},
...> {"Turing", ~D[1912-06-23]}
...> ]
iex> List.keysort(users, 1, Date)
[
{"Lovelace", ~D[1815-12-10]},
{"Turing", ~D[1912-06-23]},
{"Ellis", ~D[1943-05-11]}
]
iex> List.keysort(users, 1, {:desc, Date})
[
{"Ellis", ~D[1943-05-11]},
{"Turing", ~D[1912-06-23]},
{"Lovelace", ~D[1815-12-10]}
]
"""
@doc since: "1.14.0"
@spec keysort(
[tuple],
non_neg_integer,
(any, any -> boolean) | :asc | :desc | module() | {:asc | :desc, module()}
) :: [tuple]
def keysort(list, position, sorter \\ :asc)
def keysort(list, position, :asc) when is_list(list) and is_integer(position) do
:lists.keysort(position + 1, list)
end
def keysort(list, position, sorter) when is_list(list) and is_integer(position) do
:lists.sort(keysort_fun(sorter, position + 1), list)
end
defp keysort_fun(sorter, position) when is_function(sorter, 2),
do: &sorter.(:erlang.element(position, &1), :erlang.element(position, &2))
defp keysort_fun(:desc, position),
do: &(:erlang.element(position, &1) >= :erlang.element(position, &2))
defp keysort_fun(module, position) when is_atom(module),
do: &(module.compare(:erlang.element(position, &1), :erlang.element(position, &2)) != :gt)
defp keysort_fun({:asc, module}, position) when is_atom(module),
do: &(module.compare(:erlang.element(position, &1), :erlang.element(position, &2)) != :gt)
defp keysort_fun({:desc, module}, position) when is_atom(module),
do: &(module.compare(:erlang.element(position, &1), :erlang.element(position, &2)) != :lt)
@doc """
Receives a `list` of tuples and replaces the element
identified by `key` at `position` with `new_tuple`.
If the element does not exist, it is added to the end of the `list`.
## Examples
iex> List.keystore([a: 1, b: 2], :a, 0, {:a, 3})
[a: 3, b: 2]
iex> List.keystore([a: 1, b: 2], :c, 0, {:c, 3})
[a: 1, b: 2, c: 3]
This function works for any list of tuples:
iex> List.keystore([{22, "SSH"}], 80, 0, {80, "HTTP"})
[{22, "SSH"}, {80, "HTTP"}]
"""
@spec keystore([tuple], any, non_neg_integer, tuple) :: [tuple, ...]
def keystore(list, key, position, new_tuple) when is_integer(position) do
:lists.keystore(key, position + 1, list, new_tuple)
end
@doc """
Receives a `list` of tuples and deletes the first tuple
where the element at `position` matches the
given `key`. Returns the new list.
## Examples
iex> List.keydelete([a: 1, b: 2], :a, 0)
[b: 2]
iex> List.keydelete([a: 1, b: 2], 2, 1)
[a: 1]
iex> List.keydelete([a: 1, b: 2], :c, 0)
[a: 1, b: 2]
This function works for any list of tuples:
iex> List.keydelete([{22, "SSH"}, {80, "HTTP"}], 80, 0)
[{22, "SSH"}]
"""
@spec keydelete([tuple], any, non_neg_integer) :: [tuple]
def keydelete(list, key, position) when is_integer(position) do
:lists.keydelete(key, position + 1, list)
end
@doc """
Receives a `list` of tuples and returns the first tuple
where the element at `position` in the tuple matches the
given `key`, as well as the `list` without found tuple.
If such a tuple is not found, `nil` will be returned.
## Examples
iex> List.keytake([a: 1, b: 2], :a, 0)
{{:a, 1}, [b: 2]}
iex> List.keytake([a: 1, b: 2], 2, 1)
{{:b, 2}, [a: 1]}
iex> List.keytake([a: 1, b: 2], :c, 0)
nil
This function works for any list of tuples:
iex> List.keytake([{22, "SSH"}, {80, "HTTP"}], 80, 0)
{{80, "HTTP"}, [{22, "SSH"}]}
"""
@spec keytake([tuple], any, non_neg_integer) :: {tuple, [tuple]} | nil
def keytake(list, key, position) when is_integer(position) do
case :lists.keytake(key, position + 1, list) do
{:value, element, list} -> {element, list}
false -> nil
end
end
@doc """
Wraps `term` in a list if this is not list.
If `term` is already a list, it returns the list.
If `term` is `nil`, it returns an empty list.
## Examples
iex> List.wrap("hello")
["hello"]
iex> List.wrap([1, 2, 3])
[1, 2, 3]
iex> List.wrap(nil)
[]
"""
@spec wrap(term) :: maybe_improper_list()
def wrap(term)
def wrap(list) when is_list(list) do
list
end
def wrap(nil) do
[]
end
def wrap(other) do
[other]
end
@doc """
Zips corresponding elements from each list in `list_of_lists`.
The zipping finishes as soon as any list terminates.
## Examples
iex> List.zip([[1, 2], [3, 4], [5, 6]])
[{1, 3, 5}, {2, 4, 6}]
iex> List.zip([[1, 2], [3], [5, 6]])
[{1, 3, 5}]
"""
@spec zip([list]) :: [tuple]
def zip([]), do: []
def zip(list_of_lists) when is_list(list_of_lists) do
do_zip(list_of_lists, [])
end
@doc ~S"""
Checks if `list` is a charlist made only of printable ASCII characters.
Takes an optional `limit` as a second argument. `ascii_printable?/2` only
checks the printability of the list up to the `limit`.
A printable charlist in Elixir contains only the printable characters in the
standard seven-bit ASCII character encoding, which are characters ranging from
32 to 126 in decimal notation, plus the following control characters:
* `?\a` - Bell
* `?\b` - Backspace
* `?\t` - Horizontal tab
* `?\n` - Line feed
* `?\v` - Vertical tab
* `?\f` - Form feed
* `?\r` - Carriage return
* `?\e` - Escape
For more information read the [Character groups](https://en.wikipedia.org/wiki/ASCII#Character_groups)
section in the Wikipedia article of the [ASCII](https://en.wikipedia.org/wiki/ASCII) standard.
## Examples
iex> List.ascii_printable?(~c"abc")
true
iex> List.ascii_printable?(~c"abc" ++ [0])
false
iex> List.ascii_printable?(~c"abc" ++ [0], 2)
true
Improper lists are not printable, even if made only of ASCII characters:
iex> List.ascii_printable?(~c"abc" ++ ?d)
false
"""
@doc since: "1.6.0"
@spec ascii_printable?(list, 0) :: true
@spec ascii_printable?([], limit) :: true
when limit: :infinity | pos_integer
@spec ascii_printable?([...], limit) :: boolean
when limit: :infinity | pos_integer
def ascii_printable?(list, limit \\ :infinity)
when is_list(list) and (limit == :infinity or (is_integer(limit) and limit >= 0)) do
ascii_printable_guarded?(list, limit)
end
defp ascii_printable_guarded?(_, 0) do
true
end
defp ascii_printable_guarded?([char | rest], counter)
# 7..13 is the range '\a\b\t\n\v\f\r'. 32..126 are ASCII printables.
when is_integer(char) and
((char >= 7 and char <= 13) or char == ?\e or (char >= 32 and char <= 126)) do
ascii_printable_guarded?(rest, decrement(counter))
end
defp ascii_printable_guarded?([], _counter), do: true
defp ascii_printable_guarded?(_, _counter), do: false
@compile {:inline, decrement: 1}
defp decrement(:infinity), do: :infinity
defp decrement(counter), do: counter - 1
@doc """
Returns `true` if `list` is an improper list. Otherwise returns `false`.
## Examples
iex> List.improper?([1, 2 | 3])
true
iex> List.improper?([1, 2, 3])
false
"""
@doc since: "1.8.0"
@spec improper?(maybe_improper_list) :: boolean
def improper?(list) when is_list(list) and length(list) >= 0, do: false
def improper?(list) when is_list(list), do: true
@doc """
Returns a list with `value` inserted at the specified `index`.
Note that `index` is capped at the list length. Negative indices
indicate an offset from the end of the `list`.
## Examples
iex> List.insert_at([1, 2, 3, 4], 2, 0)
[1, 2, 0, 3, 4]
iex> List.insert_at([1, 2, 3], 10, 0)
[1, 2, 3, 0]
iex> List.insert_at([1, 2, 3], -1, 0)
[1, 2, 3, 0]
iex> List.insert_at([1, 2, 3], -10, 0)
[0, 1, 2, 3]
"""
@spec insert_at(list, integer, any) :: list
def insert_at(list, index, value) when is_list(list) and is_integer(index) do
case index do
-1 ->
list ++ [value]
_ when index < 0 ->
case length(list) + index + 1 do
index when index < 0 -> [value | list]
index -> do_insert_at(list, index, value)
end
_ ->
do_insert_at(list, index, value)
end
end
@doc """
Returns a list with a replaced value at the specified `index`.
Negative indices indicate an offset from the end of the `list`.
If `index` is out of bounds, the original `list` is returned.
## Examples
iex> List.replace_at([1, 2, 3], 0, 0)
[0, 2, 3]
iex> List.replace_at([1, 2, 3], 10, 0)
[1, 2, 3]
iex> List.replace_at([1, 2, 3], -1, 0)
[1, 2, 0]
iex> List.replace_at([1, 2, 3], -10, 0)
[1, 2, 3]
"""
@spec replace_at(list, integer, any) :: list
def replace_at(list, index, value) when is_list(list) and is_integer(index) do
if index < 0 do
case length(list) + index do
index when index < 0 -> list
index -> do_replace_at(list, index, value)
end
else
do_replace_at(list, index, value)
end
end
@doc """
Returns a list with an updated value at the specified `index`.
Negative indices indicate an offset from the end of the `list`.
If `index` is out of bounds, the original `list` is returned.
## Examples
iex> List.update_at([1, 2, 3], 0, &(&1 + 10))
[11, 2, 3]
iex> List.update_at([1, 2, 3], 10, &(&1 + 10))
[1, 2, 3]
iex> List.update_at([1, 2, 3], -1, &(&1 + 10))
[1, 2, 13]
iex> List.update_at([1, 2, 3], -10, &(&1 + 10))
[1, 2, 3]
"""
@spec update_at([elem], integer, (elem -> any)) :: list when elem: var
def update_at(list, index, fun) when is_list(list) and is_function(fun) and is_integer(index) do
if index < 0 do
case length(list) + index do
index when index < 0 -> list
index -> do_update_at(list, index, fun)
end
else
do_update_at(list, index, fun)
end
end
@doc """
Produces a new list by removing the value at the specified `index`.
Negative indices indicate an offset from the end of the `list`.
If `index` is out of bounds, the original `list` is returned.
## Examples
iex> List.delete_at([1, 2, 3], 0)
[2, 3]
iex> List.delete_at([1, 2, 3], 10)
[1, 2, 3]
iex> List.delete_at([1, 2, 3], -1)
[1, 2]
"""
@spec delete_at(list, integer) :: list
def delete_at(list, index) when is_integer(index) do
elem(pop_at(list, index), 1)
end
@doc """
Returns and removes the value at the specified `index` in the `list`.
Negative indices indicate an offset from the end of the `list`.
If `index` is out of bounds, the original `list` is returned.
## Examples
iex> List.pop_at([1, 2, 3], 0)
{1, [2, 3]}
iex> List.pop_at([1, 2, 3], 5)
{nil, [1, 2, 3]}
iex> List.pop_at([1, 2, 3], 5, 10)
{10, [1, 2, 3]}
iex> List.pop_at([1, 2, 3], -1)
{3, [1, 2]}
"""
@doc since: "1.4.0"
@spec pop_at(list, integer, any) :: {any, list}
def pop_at(list, index, default \\ nil) when is_integer(index) do
if index < 0 do
do_pop_at(list, length(list) + index, default, [])
else
do_pop_at(list, index, default, [])
end
end
@doc """
Returns `true` if `list` starts with the given `prefix` list; otherwise returns `false`.
If `prefix` is an empty list, it returns `true`.
### Examples
iex> List.starts_with?([1, 2, 3], [1, 2])
true
iex> List.starts_with?([1, 2], [1, 2, 3])
false
iex> List.starts_with?([:alpha], [])
true
iex> List.starts_with?([], [:alpha])
false
"""
@doc since: "1.5.0"
@spec starts_with?(nonempty_list, nonempty_list) :: boolean
@spec starts_with?(list, []) :: true
@spec starts_with?([], nonempty_list) :: false
def starts_with?(list, prefix)
def starts_with?([head | tail], [head | prefix_tail]), do: starts_with?(tail, prefix_tail)
def starts_with?(list, []) when is_list(list), do: true
def starts_with?(list, [_ | _]) when is_list(list), do: false
@doc """
Converts a charlist to an atom.
Elixir supports conversions from charlists which contains any Unicode
code point.
Inlined by the compiler.
## Examples
iex> List.to_atom(~c"Elixir")
:Elixir
iex> List.to_atom(~c"🌢 Elixir")
:"🌢 Elixir"
"""
@spec to_atom(charlist) :: atom
def to_atom(charlist) do
:erlang.list_to_atom(charlist)
end
@doc """
Converts a charlist to an existing atom.
Elixir supports conversions from charlists which contains any Unicode
code point. Raises an `ArgumentError` if the atom does not exist.
Inlined by the compiler.
> #### Atoms and modules {: .info}
>
> Since Elixir is a compiled language, the atoms defined in a module
> will only exist after said module is loaded, which typically happens
> whenever a function in the module is executed. Therefore, it is
> generally recommended to call `List.to_existing_atom/1` only to
> convert atoms defined within the module making the function call
> to `to_existing_atom/1`.
## Examples
iex> _ = :my_atom
iex> List.to_existing_atom(~c"my_atom")
:my_atom
iex> _ = :"🌢 Elixir"
iex> List.to_existing_atom(~c"🌢 Elixir")
:"🌢 Elixir"
"""
@spec to_existing_atom(charlist) :: atom
def to_existing_atom(charlist) do
:erlang.list_to_existing_atom(charlist)
end
@doc """
Returns the float whose text representation is `charlist`.
Inlined by the compiler.
## Examples
iex> List.to_float(~c"2.2017764e+0")
2.2017764
"""
@spec to_float(charlist) :: float
def to_float(charlist) do
:erlang.list_to_float(charlist)
end
@doc """
Returns an integer whose text representation is `charlist`.