431932f02abb2c183290492b9d27c98c5711495d
[hope.git] / src / hope_kv_list.erl
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 [].
36 empty() ->
37 [].
38
39 get(T, K) ->
40 case lists:keyfind(K, 1, T)
41 of false -> none
42 ; {K, V} -> {some, V}
43 end.
44
45 set(T, K, V) ->
46 lists:keystore(K, 1, T, {K, V}).
47
48 update(T, K, F) ->
49 V1Opt = get(T, K),
50 V2 = F(V1Opt),
51 % TODO: Eliminate the 2nd lookup.
52 set(T, K, V2).
53
54 iter(T, F1) ->
55 F2 = lift(F1),
56 lists:foreach(F2, T).
57
58 map(T, F1) ->
59 F2 = lift(F1),
60 F3 = fun ({K, _}=X) -> {K, F2(X)} end,
61 lists:map(F3, T).
62
63 filter(T, F1) ->
64 F2 = lift(F1),
65 lists:filter(F2, T).
66
67 fold(T, F1, Accumulator) ->
68 F2 = fun ({K, V}, Acc) -> F1(K, V, Acc) end,
69 lists:foldl(F2, T, Accumulator).
70
71 to_kv_list(T) ->
72 T.
73
74 of_kv_list(List) ->
75 % TODO: Decide if validation is to be done here. Do so if yes.
76 List.
77
78
79 %% ============================================================================
80 %% Helpers
81 %% ============================================================================
82
83 lift(F) ->
84 fun ({K, V}) -> F(K, V) end.
This page took 0.056798 seconds and 3 git commands to generate.