From 70cf8e86a06d8721fcc8b658bb2be1f7b401326f Mon Sep 17 00:00:00 2001 From: Siraaj Khandkar Date: Thu, 14 Aug 2014 13:55:40 -0400 Subject: [PATCH] Add dictionary method: pop. --- src/hope_dictionary.erl | 3 +++ src/hope_kv_list.erl | 7 +++++++ test/hope_kv_list_SUITE.erl | 8 ++++++++ 3 files changed, 18 insertions(+) diff --git a/src/hope_dictionary.erl b/src/hope_dictionary.erl index 5494f39..7930c1d 100644 --- a/src/hope_dictionary.erl +++ b/src/hope_dictionary.erl @@ -21,6 +21,9 @@ -callback update(t(K, V), K, fun((hope_option:t(V)) -> V)) -> t(K, V). +-callback pop(t(K, V), K) -> + {hope_option:t(V), t(K, V)}. + -callback map(t(K, V), fun((K, V) -> V)) -> t(K, V). diff --git a/src/hope_kv_list.erl b/src/hope_kv_list.erl index 3ca9d07..ebc4176 100644 --- a/src/hope_kv_list.erl +++ b/src/hope_kv_list.erl @@ -14,6 +14,7 @@ , get/2 , set/3 , update/3 + , pop/2 , iter/2 , map/2 , filter/2 @@ -51,6 +52,12 @@ update(T, K, F) -> % TODO: Eliminate the 2nd lookup. set(T, K, V2). +pop(T1, K) -> + case lists:keytake(K, 1, T1) + of {value, {K, V}, T2} -> {{some, V}, T2} + ; false -> {none , T1} + end. + iter(T, F1) -> F2 = lift_map(F1), lists:foreach(F2, T). diff --git a/test/hope_kv_list_SUITE.erl b/test/hope_kv_list_SUITE.erl index e0f0747..8abb888 100644 --- a/test/hope_kv_list_SUITE.erl +++ b/test/hope_kv_list_SUITE.erl @@ -10,6 +10,7 @@ -export( [ t_set_new/1 , t_set_existing/1 + , t_pop/1 ]). @@ -30,6 +31,7 @@ groups() -> Tests = [ t_set_new , t_set_existing + , t_pop ], Properties = [], [{?GROUP_KV_LIST, Properties, Tests}]. @@ -55,3 +57,9 @@ t_set_existing(_Config) -> ListResulting = hope_kv_list:set(ListInitial, Key, ValExpected), {some, ValResulting} = hope_kv_list:get(ListResulting, Key), ValResulting = ValExpected. + +t_pop(_Config) -> + KVList = [{a, 1}, {b, 2}, {c, 3}], + Dict1 = hope_kv_list:of_kv_list(KVList), + {{some, 1}, Dict2} = hope_kv_list:pop(Dict1, a), + {none , _Dict3} = hope_kv_list:pop(Dict2, a). -- 2.20.1