nmi*_*els 6 erlang data-structures
我试图想出一个类似字典的数据结构,我可以在Erlang中使用它.目标是保证所有值以及密钥都是唯一的.我可以在每次修改后使用显式一致性检查来完成它,但我希望有一个模糊的类型可以为我做这个.有吗?如果没有,有没有比将支票包装到修改数据的每个函数(或返回稍微不同的副本)更好的方法?
我希望至少有120个元素,不超过几千个,如果重要的话.
这样的事情怎么样:
-module(unidict).
-export([
new/0,
find/2,
store/3
]).
new() ->
dict:new().
find(Key, Dict) ->
dict:find({key, Key}, Dict).
store(K, V, Dict) ->
Key = {key, K},
case dict:is_key(Key, Dict) of
true ->
erlang:error(badarg);
false ->
Value = {value, V},
case dict:is_key(Value, Dict) of
true ->
erlang:error(badarg);
false ->
dict:store(Value, K, dict:store(Key, V, Dict))
end
end.
Run Code Online (Sandbox Code Playgroud)
示例shell会话:
1> c(unidict).
{ok,unidict}
2> D = unidict:new().
{dict,0,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]}}}
3> D1 = unidict:store(key, value, D).
{dict,2,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[],[],[],
[[{key,key}|value],[{value,...}|{...}]],
[]}}}
4> D2 = unidict:store(key, value, D1).
** exception error: bad argument
in function unidict:store/3
5> D2 = unidict:store(key2, value, D1).
** exception error: bad argument
in function unidict:store/3
6> D2 = unidict:store(key, value2, D1).
** exception error: bad argument
in function unidict:store/3
7> D2 = unidict:store(key2, value2, D1).
{dict,4,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],
[[{key,key2}|value2]],
[],[],[],[],[],[],[],[],[],[],[],
[[{value,value2}|{key,key2}]],
[[{key,key}|value],[{value,...}|{...}]],
[]}}}
8> unidict:find(key, D2).
{ok,value}
9> unidict:find(key2, D2).
{ok,value2}
Run Code Online (Sandbox Code Playgroud)