Implement a Key->Value list dictionary.
[hope.git] / src / hope_kv_list.erl
CommitLineData
03ac148f
SK
1%%%----------------------------------------------------------------------------
2%%% Equivalent to stdlib's orddict, but with a pretty (IMO), uniform interface.
3%%%----------------------------------------------------------------------------
4-module(hope_kv_list).
5
6-behavior(hope_dictionary).
7
8-export_type(
9 [ t/2
10 ]).
11
12-export(
13 [ empty/0
14 , get/2
15 , set/3
16 , update/3
17 , iter/2
18 , map/2
19 , filter/2
20 , fold/3
21 , of_kv_list/1
22 , to_kv_list/1
23 ]).
24
25
26-type t(K, V) ::
27 [{K, V}].
28
29
30%% ============================================================================
31%% API
32%% ============================================================================
33
34-spec empty() ->
35 [].
36empty() ->
37 [].
38
39get(T, K) ->
40 case lists:keyfind(K, 1, T)
41 of false -> none
42 ; {K, V} -> {some, V}
43 end.
44
45set(T, K, V) ->
46 lists:keystore(K, 1, T, {K, V}).
47
48update(T, K, F) ->
49 V1Opt = get(T, K),
50 V2 = F(V1Opt),
51 set(T, K, V2).
52
53iter(T, Map1) ->
54 Map2 = lift_map_into_list(Map1),
55 lists:foreach(Map2, T).
56
57map(T, Map1) ->
58 Map2 = lift_map_into_list(Map1),
59 lists:map(Map2, T).
60
61filter(T, Map1) ->
62 Map2 = lift_map_into_list(Map1),
63 lists:filter(Map2, T).
64
65fold(T, F1, Accumulator) ->
66 F2 = fun ({K, V}, Acc) -> F1(K, V, Acc) end,
67 lists:foldl(F2, T, Accumulator).
68
69to_kv_list(T) ->
70 T.
71
72of_kv_list(List) ->
73 List.
74
75
76%% ============================================================================
77%% Helpers
78%% ============================================================================
79
80lift_map_into_list(Map) ->
81 fun ({K, V}) -> {K, Map(K, V)} end.
This page took 0.037756 seconds and 4 git commands to generate.