1 %%%----------------------------------------------------------------------------
2 %%% Equivalent to stdlib's orddict, but with a pretty (IMO), uniform interface.
3 %%%----------------------------------------------------------------------------
6 -behavior(hope_dictionary).
24 , validate_unique_presence/2 % Assume default optional parameter(s)
25 , validate_unique_presence/3 % Specify optional parameter(s)
32 -type presence_error(A) ::
34 | {keys_duplicated , [A]}
35 | {keys_unsupported , [A]}
39 %% ============================================================================
41 %% ============================================================================
48 -spec get(t(K, V), K) ->
51 case lists:keyfind(K, 1, T)
56 -spec set(t(K, V), K, V) ->
59 lists:keystore(K, 1, T, {K, V}).
61 -spec update(t(K, V), K, fun((hope_option:t(V)) -> V)) ->
66 % TODO: Eliminate the 2nd lookup.
69 -spec pop(t(K, V), K) ->
70 {hope_option:t(V), t(K, V)}.
72 case lists:keytake(K, 1, T1)
73 of {value, {K, V}, T2} -> {{some, V}, T2}
74 ; false -> {none , T1}
77 -spec iter(t(K, V), fun((K, V) -> ok)) ->
83 -spec map(t(K, V), fun((K, V) -> V)) ->
86 F2 = fun ({K, _}=X) -> {K, apply_map(F1, X)} end,
89 -spec filter(t(K, V), fun((K, V) -> boolean())) ->
95 -spec fold(t(K, V), fun((K, V, Acc) -> Acc), Acc) ->
97 fold(T, F1, Accumulator) ->
98 F2 = fun ({K, V}, Acc) -> F1(K, V, Acc) end,
99 lists:foldl(F2, Accumulator, T).
101 -spec to_kv_list(t(K, V)) ->
106 -spec of_kv_list([{K, V}]) ->
109 % TODO: Decide if validation is to be done here. Do so if yes.
112 -spec validate_unique_presence(t(K, _V), [K]) ->
113 hope_result:t(ok, [presence_error(K)]).
114 validate_unique_presence(T, KeysRequired) ->
116 validate_unique_presence(T, KeysRequired, KeysOptional).
118 -spec validate_unique_presence(t(K, _V), [K], [K]) ->
119 hope_result:t(ok, [presence_error(K)]).
120 validate_unique_presence(T, KeysRequired, KeysOptional) ->
121 KeysSupported = KeysRequired ++ KeysOptional,
122 KeysGiven = [K || {K, _V} <- T],
123 KeysGivenUnique = lists:usort(KeysGiven),
124 KeysDups = lists:usort(KeysGiven -- KeysGivenUnique),
125 KeysMissing = KeysRequired -- KeysGivenUnique,
126 KeysUnsupported = KeysGivenUnique -- KeysSupported,
127 case {KeysDups, KeysMissing, KeysUnsupported}
130 ; {Dups, Missing, Unsupported} ->
134 ; [_|_] -> [{keys_duplicated, Dups}]
139 ; [_|_] -> [{keys_missing, Missing}]
144 ; [_|_] -> [{keys_unsupported, Unsupported}]
146 Errors = ErrorDups ++ ErrorMissing ++ ErrorUnsupported,
151 %% ============================================================================
153 %% ============================================================================
157 when F :: fun(( K, V1 ) -> V2)
158 , G :: fun(({K, V1}) -> V2)
161 fun (X) -> apply_map(F, X) end.
163 -spec apply_map(fun((K, V1) -> V2), {K, V1}) ->
165 apply_map(F, {K, V}) ->