Skip to content

Commit 6d44180

Browse files
author
José Valim
committed
Merge pull request #2243 from meh/dict
Implement default pop/2, pop/3, update/4, update!/3 for Dict.Behaviour
2 parents b0a5197 + 235c4d6 commit 6d44180

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

lib/elixir/lib/dict/behaviour.ex

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ defmodule Dict.Behaviour do
1212
1313
# implement required functions (see below)
1414
15-
# override default implementations if needed
15+
# override default implementations if optimization is needed
1616
end
1717
1818
The client module must contain the following functions:
@@ -22,7 +22,6 @@ defmodule Dict.Behaviour do
2222
* `put/3`
2323
* `reduce/3`
2424
* `size/1`
25-
* `update/4`
2625
2726
All functions, except `reduce/3`, are required by the Dict behaviour.
2827
`reduce/3` must be implemtented as per the Enumerable protocol.
@@ -39,10 +38,14 @@ defmodule Dict.Behaviour do
3938
* `keys/1`
4039
* `merge/2`
4140
* `merge/3`
41+
* `pop/2`
42+
* `pop/3`
4243
* `put_new/3`
4344
* `take/2`
4445
* `to_list/1`
4546
* `values/1`
47+
* `update/4`
48+
* `update!/3`
4649
4750
All of these functions are defined as overridable, so you can provide your own
4851
implementation if needed.
@@ -144,9 +147,39 @@ defmodule Dict.Behaviour do
144147
end) |> elem(1)
145148
end
146149

150+
def update(dict, key, initial, fun) do
151+
case fetch(dict, key) do
152+
{ :ok, value } ->
153+
put(dict, key, fun.(value))
154+
155+
:error ->
156+
put(dict, key, initial)
157+
end
158+
end
159+
160+
def update!(dict, key, fun) do
161+
case fetch(dict, key) do
162+
{ :ok, value } ->
163+
put(dict, key, fun.(value))
164+
165+
:error ->
166+
raise KeyError, key: key, term: dict
167+
end
168+
end
169+
170+
def pop(dict, key, default \\ nil) do
171+
case fetch(dict, key) do
172+
{ :ok, value } ->
173+
{ value, delete(dict, key) }
174+
175+
:error ->
176+
{ default, dict }
177+
end
178+
end
179+
147180
defoverridable merge: 2, merge: 3, equal?: 2, to_list: 1, keys: 1,
148181
values: 1, take: 2, drop: 2, get: 2, get: 3, fetch!: 2,
149-
has_key?: 2, put_new: 3
182+
has_key?: 2, put_new: 3, pop: 2, pop: 3, update: 4, update!: 3
150183
end
151184
end
152185
end

0 commit comments

Comments
 (0)