/
keyword.ex
1455 lines (1094 loc) · 40.5 KB
/
keyword.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 Keyword do
@moduledoc """
A keyword list is a list that consists exclusively of two-element tuples.
The first element of these tuples is known as the *key*, and it must be an atom.
The second element, known as the *value*, can be any term.
Keywords are mostly used to work with optional values.
## Examples
For example, the following is a keyword list:
[{:exit_on_close, true}, {:active, :once}, {:packet_size, 1024}]
Elixir provides a special and more concise syntax for keyword lists:
[exit_on_close: true, active: :once, packet_size: 1024]
The two syntaxes return the exact same value.
A *key* can be any atom, consisting of Unicode letters, numbers,
an underscore or the `@` sign. If the *key* should have any other
characters, such as spaces, you can wrap it in quotes:
iex> ["exit on close": true]
["exit on close": true]
Wrapping an atom in quotes does not make it a string. Keyword list
*keys* are always atoms. Quotes should only be used when necessary
or Elixir will issue a warning.
## Duplicate keys and ordering
A keyword may have duplicate keys so it is not strictly a key-value
data type. However most of the functions in this module work on a
key-value structure and behave similar to the functions you would
find in the `Map` module. For example, `Keyword.get/3` will get the first
entry matching the given key, regardless if duplicate entries exist.
Similarly, `Keyword.put/3` and `Keyword.delete/2` ensure all duplicate
entries for a given key are removed when invoked. Note, however, that
keyword list operations need to traverse the whole list in order to find
keys, so these operations are slower than their map counterparts.
A handful of functions exist to handle duplicate keys, for example,
`get_values/2` returns all values for a given key and `delete_first/2`
deletes just the first entry of the existing ones.
Even though lists preserve the existing order, the functions in
`Keyword` do not guarantee any ordering. For example, if you invoke
`Keyword.put(opts, new_key, new_value)`, there is no guarantee for
where `new_key` will be added to (the front, the end or anywhere else).
Given ordering is not guaranteed, it is not recommended to pattern
match on keyword lists either. For example, a function such as:
def my_function([some_key: value, another_key: another_value])
will match
my_function([some_key: :foo, another_key: :bar])
but it won't match
my_function([another_key: :bar, some_key: :foo])
Most of 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 list.
## Call syntax
When keyword lists are passed as the last argument to a function,
the square brackets around the keyword list can be omitted. For
example, the keyword list syntax:
String.split("1-0", "-", [trim: true, parts: 2])
can be written without the enclosing brackets whenever it is the last
argument of a function call:
String.split("1-0", "-", trim: true, parts: 2)
Since tuples, lists and maps are treated similarly to function
arguments in Elixir syntax, this property is also available to them:
iex> {1, 2, foo: :bar}
{1, 2, [{:foo, :bar}]}
iex> [1, 2, foo: :bar]
[1, 2, {:foo, :bar}]
iex> %{1 => 2, foo: :bar}
%{1 => 2, :foo => :bar}
"""
@compile :inline_list_funcs
@type key :: atom
@type value :: any
@type t :: [{key, value}]
@type t(value) :: [{key, value}]
@doc """
Builds a keyword from the given `keys` and the fixed `value`.
## Examples
iex> Keyword.from_keys([:foo, :bar, :baz], :atom)
[foo: :atom, bar: :atom, baz: :atom]
"""
@doc since: "1.14.0"
@spec from_keys([key], value) :: t(value)
def from_keys(keys, value) when is_list(keys) do
:lists.map(&{&1, value}, keys)
end
@doc """
Returns `true` if `term` is a keyword list, otherwise `false`.
When `term` is a list it is traversed to the end.
## Examples
iex> Keyword.keyword?([])
true
iex> Keyword.keyword?(a: 1)
true
iex> Keyword.keyword?([{Foo, 1}])
true
iex> Keyword.keyword?([{}])
false
iex> Keyword.keyword?([:key])
false
iex> Keyword.keyword?(%{})
false
"""
@spec keyword?(term) :: boolean
def keyword?(term)
def keyword?([{key, _value} | rest]) when is_atom(key), do: keyword?(rest)
def keyword?([]), do: true
def keyword?(_other), do: false
@doc """
Returns an empty keyword list, i.e. an empty list.
## Examples
iex> Keyword.new()
[]
"""
@spec new :: []
def new, do: []
@doc """
Creates a keyword list from an enumerable.
Removes duplicate entries and the last one prevails.
Unlike `Enum.into(enumerable, [])`, `Keyword.new(enumerable)`
guarantees the keys are unique.
## Examples
iex> Keyword.new([{:b, 1}, {:a, 2}])
[b: 1, a: 2]
iex> Keyword.new([{:a, 1}, {:a, 2}, {:a, 3}])
[a: 3]
"""
@spec new(Enumerable.t()) :: t
def new(pairs) do
new(pairs, fn pair -> pair end)
end
@doc """
Creates a keyword list from an enumerable via the transformation function.
Removes duplicate entries and the last one prevails.
Unlike `Enum.into(enumerable, [], fun)`,
`Keyword.new(enumerable, fun)` guarantees the keys are unique.
## Examples
iex> Keyword.new([:a, :b], fn x -> {x, x} end)
[a: :a, b: :b]
"""
@spec new(Enumerable.t(), (term -> {key, value})) :: t
def new(pairs, transform) when is_function(transform, 1) do
fun = fn el, acc ->
{k, v} = transform.(el)
put_new(acc, k, v)
end
:lists.foldl(fun, [], Enum.reverse(pairs))
end
@doc """
Ensures the given `keyword` has only the keys given in `values`.
The second argument must be a list of atoms, specifying
a given key, or tuples specifying a key and a default value.
If the keyword list has only the given keys, it returns
`{:ok, keyword}` with default values applied. Otherwise it
returns `{:error, invalid_keys}` with invalid keys.
See also: `validate!/2`.
## Examples
iex> {:ok, result} = Keyword.validate([], [one: 1, two: 2])
iex> Enum.sort(result)
[one: 1, two: 2]
iex> {:ok, result} = Keyword.validate([two: 3], [one: 1, two: 2])
iex> Enum.sort(result)
[one: 1, two: 3]
If atoms are given, they are supported as keys but do not
provide a default value:
iex> {:ok, result} = Keyword.validate([], [:one, two: 2])
iex> Enum.sort(result)
[two: 2]
iex> {:ok, result} = Keyword.validate([one: 1], [:one, two: 2])
iex> Enum.sort(result)
[one: 1, two: 2]
Passing unknown keys returns an error:
iex> Keyword.validate([three: 3, four: 4], [one: 1, two: 2])
{:error, [:four, :three]}
Passing the same key multiple times also errors:
iex> Keyword.validate([one: 1, two: 2, one: 1], [:one, :two])
{:error, [:one]}
"""
@doc since: "1.13.0"
@spec validate(keyword(), values :: [atom() | {atom(), term()}]) ::
{:ok, keyword()} | {:error, [atom]}
def validate(keyword, values) when is_list(keyword) and is_list(values) do
validate(keyword, values, [], [], [])
end
defp validate([{key, _} = pair | keyword], values1, values2, acc, bad_keys) when is_atom(key) do
case find_key!(key, values1, values2) do
{values1, values2} ->
validate(keyword, values1, values2, [pair | acc], bad_keys)
:error ->
case find_key!(key, values2, values1) do
{values1, values2} ->
validate(keyword, values1, values2, [pair | acc], bad_keys)
:error ->
validate(keyword, values1, values2, acc, [key | bad_keys])
end
end
end
defp validate([], values1, values2, acc, []) do
{:ok, move_pairs!(values1, move_pairs!(values2, acc))}
end
defp validate([], _values1, _values2, _acc, bad_keys) do
{:error, bad_keys}
end
defp validate([pair | _], _values1, _values2, _acc, []) do
raise ArgumentError,
"expected a keyword list as first argument, got invalid entry: #{inspect(pair)}"
end
defp find_key!(key, [key | rest], acc), do: {rest, acc}
defp find_key!(key, [{key, _} | rest], acc), do: {rest, acc}
defp find_key!(key, [head | tail], acc), do: find_key!(key, tail, [head | acc])
defp find_key!(_key, [], _acc), do: :error
defp move_pairs!([key | rest], acc) when is_atom(key),
do: move_pairs!(rest, acc)
defp move_pairs!([{key, _} = pair | rest], acc) when is_atom(key),
do: move_pairs!(rest, [pair | acc])
defp move_pairs!([], acc),
do: acc
defp move_pairs!([other | _], _) do
raise ArgumentError,
"expected the second argument to be a list of atoms or tuples, got: #{inspect(other)}"
end
@doc """
Similar to `validate/2` but returns the keyword or raises an error.
## Examples
iex> Keyword.validate!([], [one: 1, two: 2]) |> Enum.sort()
[one: 1, two: 2]
iex> Keyword.validate!([two: 3], [one: 1, two: 2]) |> Enum.sort()
[one: 1, two: 3]
If atoms are given, they are supported as keys but do not
provide a default value:
iex> Keyword.validate!([], [:one, two: 2]) |> Enum.sort()
[two: 2]
iex> Keyword.validate!([one: 1], [:one, two: 2]) |> Enum.sort()
[one: 1, two: 2]
Passing unknown keys raises an error:
iex> Keyword.validate!([three: 3], [one: 1, two: 2])
** (ArgumentError) unknown keys [:three] in [three: 3], the allowed keys are: [:one, :two]
Passing the same key multiple times also errors:
iex> Keyword.validate!([one: 1, two: 2, one: 1], [:one, :two])
** (ArgumentError) duplicate keys [:one] in [one: 1, two: 2, one: 1]
"""
@doc since: "1.13.0"
@spec validate!(keyword(), values :: [atom() | {atom(), term()}]) :: keyword()
def validate!(keyword, values) do
case validate(keyword, values) do
{:ok, kw} ->
kw
{:error, invalid_keys} ->
keys =
for value <- values,
do: if(is_atom(value), do: value, else: elem(value, 0))
message =
case Enum.split_with(invalid_keys, &(&1 in keys)) do
{_, [_ | _] = unknown} ->
"unknown keys #{inspect(unknown)} in #{inspect(keyword)}, " <>
"the allowed keys are: #{inspect(keys)}"
{[_ | _] = known, _} ->
"duplicate keys #{inspect(known)} in #{inspect(keyword)}"
end
raise ArgumentError, message
end
end
@doc """
Gets the value under the given `key`.
Returns the default value if `key` does not exist
(`nil` if no default value is provided).
If duplicate entries exist, it returns the first one.
Use `get_values/2` to retrieve all entries.
## Examples
iex> Keyword.get([], :a)
nil
iex> Keyword.get([a: 1], :a)
1
iex> Keyword.get([a: 1], :b)
nil
iex> Keyword.get([a: 1], :b, 3)
3
With duplicate keys:
iex> Keyword.get([a: 1, a: 2], :a, 3)
1
iex> Keyword.get([a: 1, a: 2], :b, 3)
3
"""
@spec get(t, key, value) :: value
def get(keywords, key, default \\ nil) when is_list(keywords) and is_atom(key) do
case :lists.keyfind(key, 1, keywords) do
{^key, value} -> value
false -> default
end
end
@doc """
Gets the value under the given `key`.
If `key` does not exist, lazily evaluates `fun` and returns its result.
This is useful if the default value is very expensive to calculate or
generally difficult to set up and tear down again.
If duplicate entries exist, it returns the first one.
Use `get_values/2` to retrieve all entries.
## Examples
iex> keyword = [a: 1]
iex> fun = fn ->
...> # some expensive operation here
...> 13
...> end
iex> Keyword.get_lazy(keyword, :a, fun)
1
iex> Keyword.get_lazy(keyword, :b, fun)
13
"""
@spec get_lazy(t, key, (() -> value)) :: value
def get_lazy(keywords, key, fun)
when is_list(keywords) and is_atom(key) and is_function(fun, 0) do
case :lists.keyfind(key, 1, keywords) do
{^key, value} -> value
false -> fun.()
end
end
@doc """
Gets the value from `key` and updates it, all in one pass.
The `fun` argument receives the value of `key` (or `nil` if `key`
is not present) and must return a two-element tuple: the current value
(the retrieved value, which can be operated on before being returned)
and the new value to be stored under `key`. The `fun` may also
return `:pop`, implying the current value shall be removed from the
keyword list and returned.
Returns a tuple that contains the current value returned by
`fun` and a new keyword list with the updated value under `key`.
## Examples
iex> Keyword.get_and_update([a: 1], :a, fn current_value ->
...> {current_value, "new value!"}
...> end)
{1, [a: "new value!"]}
iex> Keyword.get_and_update([a: 1], :b, fn current_value ->
...> {current_value, "new value!"}
...> end)
{nil, [b: "new value!", a: 1]}
iex> Keyword.get_and_update([a: 2], :a, fn number ->
...> {2 * number, 3 * number}
...> end)
{4, [a: 6]}
iex> Keyword.get_and_update([a: 1], :a, fn _ -> :pop end)
{1, []}
iex> Keyword.get_and_update([a: 1], :b, fn _ -> :pop end)
{nil, [a: 1]}
"""
@spec get_and_update(t, key, (value | nil -> {current_value, new_value :: value} | :pop)) ::
{current_value, new_keywords :: t}
when current_value: value
def get_and_update(keywords, key, fun)
when is_list(keywords) and is_atom(key),
do: get_and_update(keywords, [], key, fun)
defp get_and_update([{key, current} | t], acc, key, fun) do
case fun.(current) do
{get, value} ->
{get, :lists.reverse(acc, [{key, value} | t])}
:pop ->
{current, :lists.reverse(acc, t)}
other ->
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
end
end
defp get_and_update([{_, _} = h | t], acc, key, fun), do: get_and_update(t, [h | acc], key, fun)
defp get_and_update([], acc, key, fun) do
case fun.(nil) do
{get, update} ->
{get, [{key, update} | :lists.reverse(acc)]}
:pop ->
{nil, :lists.reverse(acc)}
other ->
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
end
end
@doc """
Gets the value under `key` and updates it. Raises if there is no `key`.
The `fun` argument receives the value under `key` and must return a
two-element tuple: the current value (the retrieved value, which can be
operated on before being returned) and the new value to be stored under
`key`.
Returns a tuple that contains the current value returned by
`fun` and a new keyword list with the updated value under `key`.
## Examples
iex> Keyword.get_and_update!([a: 1], :a, fn current_value ->
...> {current_value, "new value!"}
...> end)
{1, [a: "new value!"]}
iex> Keyword.get_and_update!([a: 1], :b, fn current_value ->
...> {current_value, "new value!"}
...> end)
** (KeyError) key :b not found in: [a: 1]
iex> Keyword.get_and_update!([a: 1], :a, fn _ ->
...> :pop
...> end)
{1, []}
"""
@spec get_and_update!(t, key, (value | nil -> {current_value, new_value :: value} | :pop)) ::
{current_value, new_keywords :: t}
when current_value: value
def get_and_update!(keywords, key, fun) do
get_and_update!(keywords, key, fun, [])
end
defp get_and_update!([{key, value} | keywords], key, fun, acc) do
case fun.(value) do
{get, value} ->
{get, :lists.reverse(acc, [{key, value} | delete(keywords, key)])}
:pop ->
{value, :lists.reverse(acc, keywords)}
other ->
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
end
end
defp get_and_update!([{_, _} = e | keywords], key, fun, acc) do
get_and_update!(keywords, key, fun, [e | acc])
end
defp get_and_update!([], key, _fun, acc) when is_atom(key) do
raise KeyError, key: key, term: acc
end
@doc """
Fetches the value for a specific `key` and returns it in a tuple.
If the `key` does not exist, it returns `:error`.
## Examples
iex> Keyword.fetch([a: 1], :a)
{:ok, 1}
iex> Keyword.fetch([a: 1], :b)
:error
"""
@spec fetch(t, key) :: {:ok, value} | :error
def fetch(keywords, key) when is_list(keywords) and is_atom(key) do
case :lists.keyfind(key, 1, keywords) do
{^key, value} -> {:ok, value}
false -> :error
end
end
@doc """
Fetches the value for specific `key`.
If the `key` does not exist, it raises a `KeyError`.
## Examples
iex> Keyword.fetch!([a: 1], :a)
1
iex> Keyword.fetch!([a: 1], :b)
** (KeyError) key :b not found in: [a: 1]
"""
@spec fetch!(t, key) :: value
def fetch!(keywords, key) when is_list(keywords) and is_atom(key) do
case :lists.keyfind(key, 1, keywords) do
{^key, value} -> value
false -> raise KeyError, key: key, term: keywords
end
end
@doc """
Gets all values under a specific `key`.
## Examples
iex> Keyword.get_values([], :a)
[]
iex> Keyword.get_values([a: 1], :a)
[1]
iex> Keyword.get_values([a: 1, a: 2], :a)
[1, 2]
"""
@spec get_values(t, key) :: [value]
def get_values(keywords, key) when is_list(keywords) and is_atom(key) do
get_values(keywords, key, [])
end
defp get_values([{key, value} | tail], key, values), do: get_values(tail, key, [value | values])
defp get_values([{_, _} | tail], key, values), do: get_values(tail, key, values)
defp get_values([], _key, values), do: :lists.reverse(values)
@doc """
Returns all keys from the keyword list.
Keeps duplicate keys in the resulting list of keys.
## Examples
iex> Keyword.keys(a: 1, b: 2)
[:a, :b]
iex> Keyword.keys(a: 1, b: 2, a: 3)
[:a, :b, :a]
iex> Keyword.keys([{:a, 1}, {"b", 2}, {:c, 3}])
** (ArgumentError) expected a keyword list, but an entry in the list is not a two-element tuple with an atom as its first element, got: {"b", 2}
"""
@spec keys(t) :: [key]
def keys(keywords) when is_list(keywords) do
:lists.map(
fn
{key, _} when is_atom(key) -> key
element -> throw(element)
end,
keywords
)
catch
element ->
raise ArgumentError,
"expected a keyword list, but an entry in the list is not a two-element tuple " <>
"with an atom as its first element, got: #{inspect(element)}"
end
@doc """
Returns all values from the keyword list.
Keeps values from duplicate keys in the resulting list of values.
## Examples
iex> Keyword.values(a: 1, b: 2)
[1, 2]
iex> Keyword.values(a: 1, b: 2, a: 3)
[1, 2, 3]
"""
@spec values(t) :: [value]
def values(keywords) when is_list(keywords) do
:lists.map(fn {_, v} -> v end, keywords)
end
@doc false
@deprecated "Use Keyword.fetch/2 + Keyword.delete/2 instead"
def delete(keywords, key, value) when is_list(keywords) and is_atom(key) do
case :lists.keymember(key, 1, keywords) do
true -> delete_key_value(keywords, key, value)
_ -> keywords
end
end
defp delete_key_value([{key, value} | tail], key, value) do
delete_key_value(tail, key, value)
end
defp delete_key_value([{_, _} = pair | tail], key, value) do
[pair | delete_key_value(tail, key, value)]
end
defp delete_key_value([], _key, _value) do
[]
end
@doc """
Deletes the entries in the keyword list under a specific `key`.
If the `key` does not exist, it returns the keyword list unchanged.
Use `delete_first/2` to delete just the first entry in case of
duplicate keys.
## Examples
iex> Keyword.delete([a: 1, b: 2], :a)
[b: 2]
iex> Keyword.delete([a: 1, b: 2, a: 3], :a)
[b: 2]
iex> Keyword.delete([b: 2], :a)
[b: 2]
"""
@spec delete(t, key) :: t
@compile {:inline, delete: 2}
def delete(keywords, key) when is_list(keywords) and is_atom(key) do
case :lists.keymember(key, 1, keywords) do
true -> delete_key(keywords, key)
_ -> keywords
end
end
defp delete_key([{key, _} | tail], key), do: delete_key(tail, key)
defp delete_key([{_, _} = pair | tail], key), do: [pair | delete_key(tail, key)]
defp delete_key([], _key), do: []
@doc """
Deletes the first entry in the keyword list under a specific `key`.
If the `key` does not exist, it returns the keyword list unchanged.
## Examples
iex> Keyword.delete_first([a: 1, b: 2, a: 3], :a)
[b: 2, a: 3]
iex> Keyword.delete_first([b: 2], :a)
[b: 2]
"""
@spec delete_first(t, key) :: t
def delete_first(keywords, key) when is_list(keywords) and is_atom(key) do
case :lists.keymember(key, 1, keywords) do
true -> delete_first_key(keywords, key)
_ -> keywords
end
end
defp delete_first_key([{key, _} | tail], key) do
tail
end
defp delete_first_key([{_, _} = pair | tail], key) do
[pair | delete_first_key(tail, key)]
end
defp delete_first_key([], _key) do
[]
end
@doc """
Puts the given `value` under the specified `key`.
If a value under `key` already exists, it overrides the value
and removes all duplicate entries.
## Examples
iex> Keyword.put([a: 1], :b, 2)
[b: 2, a: 1]
iex> Keyword.put([a: 1, b: 2], :a, 3)
[a: 3, b: 2]
iex> Keyword.put([a: 1, b: 2, a: 4], :a, 3)
[a: 3, b: 2]
"""
@spec put(t, key, value) :: t
def put(keywords, key, value) when is_list(keywords) and is_atom(key) do
[{key, value} | delete(keywords, key)]
end
@doc """
Evaluates `fun` and puts the result under `key`
in keyword list unless `key` is already present.
This is useful if the value is very expensive to calculate or
generally difficult to set up and tear down again.
## Examples
iex> keyword = [a: 1]
iex> fun = fn ->
...> # some expensive operation here
...> 13
...> end
iex> Keyword.put_new_lazy(keyword, :a, fun)
[a: 1]
iex> Keyword.put_new_lazy(keyword, :b, fun)
[b: 13, a: 1]
"""
@spec put_new_lazy(t, key, (() -> value)) :: t
def put_new_lazy(keywords, key, fun)
when is_list(keywords) and is_atom(key) and is_function(fun, 0) do
case :lists.keyfind(key, 1, keywords) do
{^key, _} -> keywords
false -> [{key, fun.()} | keywords]
end
end
@doc """
Puts the given `value` under `key`, unless the entry `key` already exists.
## Examples
iex> Keyword.put_new([a: 1], :b, 2)
[b: 2, a: 1]
iex> Keyword.put_new([a: 1, b: 2], :a, 3)
[a: 1, b: 2]
"""
@spec put_new(t, key, value) :: t
def put_new(keywords, key, value) when is_list(keywords) and is_atom(key) do
case :lists.keyfind(key, 1, keywords) do
{^key, _} -> keywords
false -> [{key, value} | keywords]
end
end
@doc """
Puts a value under `key` only if the `key` already exists in `keywords`.
In case a key exists multiple times in the keyword list,
it removes later occurrences.
## Examples
iex> Keyword.replace([a: 1, b: 2, a: 4], :a, 3)
[a: 3, b: 2]
iex> Keyword.replace([a: 1], :b, 2)
[a: 1]
"""
@doc since: "1.11.0"
@spec replace(t, key, value) :: t
def replace(keywords, key, value) when is_list(keywords) and is_atom(key) do
do_replace(keywords, key, value)
end
defp do_replace([{key, _} | keywords], key, value) do
[{key, value} | delete(keywords, key)]
end
defp do_replace([{_, _} = e | keywords], key, value) do
[e | do_replace(keywords, key, value)]
end
defp do_replace([], _key, _value) do
[]
end
@doc """
Puts a value under `key` only if the `key` already exists in `keywords`.
If `key` is not present in `keywords`, it raises a `KeyError`.
## Examples
iex> Keyword.replace!([a: 1, b: 2, a: 3], :a, :new)
[a: :new, b: 2]
iex> Keyword.replace!([a: 1, b: 2, c: 3, b: 4], :b, :new)
[a: 1, b: :new, c: 3]
iex> Keyword.replace!([a: 1], :b, 2)
** (KeyError) key :b not found in: [a: 1]
"""
@doc since: "1.5.0"
@spec replace!(t, key, value) :: t
def replace!(keywords, key, value) when is_list(keywords) and is_atom(key) do
replace!(keywords, key, value, keywords)
end
defp replace!([{key, _} | keywords], key, value, _original) do
[{key, value} | delete(keywords, key)]
end
defp replace!([{_, _} = e | keywords], key, value, original) do
[e | replace!(keywords, key, value, original)]
end
defp replace!([], key, _value, original) do
raise KeyError, key: key, term: original
end
@doc """
Replaces the value under `key` using the given function only if
`key` already exists in `keywords`.
In comparison to `replace/3`, this can be useful when it's expensive to calculate the value.
If `key` does not exist, the original keyword list is returned unchanged.
## Examples
iex> Keyword.replace_lazy([a: 1, b: 2], :a, fn v -> v * 4 end)
[a: 4, b: 2]
iex> Keyword.replace_lazy([a: 2, b: 2, a: 1], :a, fn v -> v * 4 end)
[a: 8, b: 2]
iex> Keyword.replace_lazy([a: 1, b: 2], :c, fn v -> v * 4 end)
[a: 1, b: 2]
"""
@doc since: "1.14.0"
@spec replace_lazy(t, key, (existing_value :: value -> new_value :: value)) :: t
def replace_lazy(keywords, key, fun)
when is_list(keywords) and is_atom(key) and is_function(fun, 1) do
do_replace_lazy(keywords, key, fun)
end
defp do_replace_lazy([{key, value} | keywords], key, fun) do
[{key, fun.(value)} | delete(keywords, key)]
end
defp do_replace_lazy([{_, _} = e | keywords], key, fun) do
[e | do_replace_lazy(keywords, key, fun)]
end
defp do_replace_lazy([], _key, _value), do: []
@doc """
Checks if two keywords are equal.
Considers two keywords to be equal if they contain
the same keys and those keys contain the same values.
## Examples
iex> Keyword.equal?([a: 1, b: 2], [b: 2, a: 1])
true
iex> Keyword.equal?([a: 1, b: 2], [b: 1, a: 2])
false
iex> Keyword.equal?([a: 1, b: 2, a: 3], [b: 2, a: 3, a: 1])
true
Comparison between values is done with `===/3`,
which means integers are not equivalent to floats:
iex> Keyword.equal?([a: 1.0], [a: 1])
false
"""
@spec equal?(t, t) :: boolean
def equal?(left, right) when is_list(left) and is_list(right) do
:lists.sort(left) === :lists.sort(right)
end
@doc """
Merges two keyword lists into one.
Adds all keys, including duplicate keys, given in `keywords2`
to `keywords1`, overriding any existing ones.
There are no guarantees about the order of the keys in the returned keyword.
## Examples
iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4])
[b: 2, a: 3, d: 4]
iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4, a: 5])
[b: 2, a: 3, d: 4, a: 5]
iex> Keyword.merge([a: 1], [2, 3])
** (ArgumentError) expected a keyword list as the second argument, got: [2, 3]
"""
@spec merge(t, t) :: t
def merge(keywords1, keywords2)
def merge(keywords1, []) when is_list(keywords1), do: keywords1
def merge([], keywords2) when is_list(keywords2), do: keywords2
def merge(keywords1, keywords2) when is_list(keywords1) and is_list(keywords2) do
if keyword?(keywords2) do
fun = fn
{key, _value} when is_atom(key) ->
not has_key?(keywords2, key)
_ ->
raise ArgumentError,
"expected a keyword list as the first argument, got: #{inspect(keywords1)}"
end
:lists.filter(fun, keywords1) ++ keywords2
else
raise ArgumentError,
"expected a keyword list as the second argument, got: #{inspect(keywords2)}"
end
end
@doc """