@@ -12,7 +12,7 @@ defmodule Dict.Behaviour do
12
12
13
13
# implement required functions (see below)
14
14
15
- # override default implementations if needed
15
+ # override default implementations if optimization is needed
16
16
end
17
17
18
18
The client module must contain the following functions:
@@ -22,7 +22,6 @@ defmodule Dict.Behaviour do
22
22
* `put/3`
23
23
* `reduce/3`
24
24
* `size/1`
25
- * `update/4`
26
25
27
26
All functions, except `reduce/3`, are required by the Dict behaviour.
28
27
`reduce/3` must be implemtented as per the Enumerable protocol.
@@ -39,10 +38,14 @@ defmodule Dict.Behaviour do
39
38
* `keys/1`
40
39
* `merge/2`
41
40
* `merge/3`
41
+ * `pop/2`
42
+ * `pop/3`
42
43
* `put_new/3`
43
44
* `take/2`
44
45
* `to_list/1`
45
46
* `values/1`
47
+ * `update/4`
48
+ * `update!/3`
46
49
47
50
All of these functions are defined as overridable, so you can provide your own
48
51
implementation if needed.
@@ -144,9 +147,39 @@ defmodule Dict.Behaviour do
144
147
end ) |> elem ( 1 )
145
148
end
146
149
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
+
147
180
defoverridable merge: 2 , merge: 3 , equal?: 2 , to_list: 1 , keys: 1 ,
148
181
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
150
183
end
151
184
end
152
185
end
0 commit comments