aboutsummaryrefslogtreecommitdiffstats
path: root/lib/stdlib/src/dict.erl
diff options
context:
space:
mode:
authorBjörn Gustavsson <[email protected]>2016-12-16 12:50:28 +0100
committerBjörn Gustavsson <[email protected]>2016-12-19 11:54:06 +0100
commita2d92dff3a8acc534daeeb3dea5edda406a6ab0d (patch)
treea61765af69f9cca94879083422571be3c959bd8c /lib/stdlib/src/dict.erl
parent8362491325db87bd7d561399f8ef8c849df22d33 (diff)
downloadotp-a2d92dff3a8acc534daeeb3dea5edda406a6ab0d.tar.gz
otp-a2d92dff3a8acc534daeeb3dea5edda406a6ab0d.tar.bz2
otp-a2d92dff3a8acc534daeeb3dea5edda406a6ab0d.zip
Add take/2 to all dictionary modules
Similar to maps:take/2, add take/2 to the other dictionary modules in STDLIB: orddict:take(Key, Dict) -> {Val,NewDict} | 'error'. dict:take(Key, Dict) -> {Val,NewDict} | 'error'. gb_trees:take(Key, Dict) -> {Val,NewDict}. For gb_trees also add: gb_trees:take_any(Key, Dict) -> {Val,NewDict} | 'error'. gb_trees already has delete() and delete_any(), so we will follow that design pattern. Suggested by Boris Bochkaryov in https://github.com/erlang/otp/pull/1209.
Diffstat (limited to 'lib/stdlib/src/dict.erl')
-rw-r--r--lib/stdlib/src/dict.erl23
1 files changed, 22 insertions, 1 deletions
diff --git a/lib/stdlib/src/dict.erl b/lib/stdlib/src/dict.erl
index f921e28ef6..9449ba3dc2 100644
--- a/lib/stdlib/src/dict.erl
+++ b/lib/stdlib/src/dict.erl
@@ -38,7 +38,7 @@
%% Standard interface.
-export([new/0,is_key/2,to_list/1,from_list/1,size/1,is_empty/1]).
--export([fetch/2,find/2,fetch_keys/1,erase/2]).
+-export([fetch/2,find/2,fetch_keys/1,erase/2,take/2]).
-export([store/3,append/3,append_list/3,update/3,update/4,update_counter/3]).
-export([fold/3,map/2,filter/2,merge/3]).
@@ -172,6 +172,27 @@ erase_key(Key, [E|Bkt0]) ->
{[E|Bkt1],Dc};
erase_key(_, []) -> {[],0}.
+-spec take(Key, Dict) -> {Value, Dict1} | error when
+ Dict :: dict(Key, Value),
+ Dict1 :: dict(Key, Value),
+ Key :: term(),
+ Value :: term().
+
+take(Key, D0) ->
+ Slot = get_slot(D0, Key),
+ case on_bucket(fun (B0) -> take_key(Key, B0) end, D0, Slot) of
+ {D1,{Value,Dc}} ->
+ {Value, maybe_contract(D1, Dc)};
+ {_,error} -> error
+ end.
+
+take_key(Key, [?kv(Key,Val)|Bkt]) ->
+ {Bkt,{Val,1}};
+take_key(Key, [E|Bkt0]) ->
+ {Bkt1,Res} = take_key(Key, Bkt0),
+ {[E|Bkt1],Res};
+take_key(_, []) -> {[],error}.
+
-spec store(Key, Value, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).