Skip to content

Commit 772c7b0

Browse files
committed
Add Keyword.intersect/2-3
1 parent 6250a17 commit 772c7b0

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

lib/elixir/lib/keyword.ex

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -960,6 +960,36 @@ defmodule Keyword do
960960
:lists.sort(left) === :lists.sort(right)
961961
end
962962

963+
@doc """
964+
Intersects two keyword lists, returning a keyword with the common keys.
965+
966+
By default, it returns the values of the intersected keys in `keyword2`.
967+
The keys are returned in the order found in `keyword1`.
968+
969+
## Examples
970+
971+
iex> Keyword.intersect([a: 1, b: 2], [b: "b", c: "c"])
972+
[b: "b"]
973+
974+
iex> Keyword.intersect([a: 1, b: 2], [b: 2, c: 3], fn _k, v1, v2 ->
975+
...> v1 + v2
976+
...> end)
977+
[b: 4]
978+
979+
"""
980+
@doc since: "1.17.0"
981+
@spec intersect(keyword, keyword, (key, value, value -> value)) :: keyword
982+
def intersect(keyword1, keyword2, fun \\ fn _key, _v1, v2 -> v2 end)
983+
984+
def intersect([{k, v1} | keyword1], keyword2, fun) do
985+
case :lists.keyfind(k, 1, keyword2) do
986+
{_, v2} -> [{k, fun.(k, v1, v2)} | intersect(keyword1, keyword2, fun)]
987+
false -> intersect(keyword1, keyword2, fun)
988+
end
989+
end
990+
991+
def intersect([], _keyword2, _fun), do: []
992+
963993
@doc """
964994
Merges two keyword lists into one.
965995

lib/elixir/test/elixir/keyword_test.exs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,7 @@ defmodule KeywordTest do
2121
end
2222

2323
test "implements (almost) all functions in Map" do
24-
assert Map.__info__(:functions) -- Keyword.__info__(:functions) == [
25-
from_struct: 1,
26-
intersect: 2,
27-
intersect: 3
28-
]
24+
assert Map.__info__(:functions) -- Keyword.__info__(:functions) == [from_struct: 1]
2925
end
3026

3127
test "get_and_update/3 raises on bad return value from the argument function" do

0 commit comments

Comments
 (0)