Data structures Erlang中的双向哈希表
我正在尝试提出一种类似于字典的数据结构,可以在Erlang中使用。目标是确保所有值以及键都是唯一的。每次修改后,我都可以通过显式一致性检查来完成,但我希望有一种晦涩难懂的类型可以帮我做到这一点。有吗?如果不是,有没有比在每个修改数据(或返回稍微不同的副本)的函数中包装检查更好的方法 我希望至少有120个元素,但不超过几千个,以防万一 有吗Data structures Erlang中的双向哈希表,data-structures,erlang,Data Structures,Erlang,我正在尝试提出一种类似于字典的数据结构,可以在Erlang中使用。目标是确保所有值以及键都是唯一的。每次修改后,我都可以通过显式一致性检查来完成,但我希望有一种晦涩难懂的类型可以帮我做到这一点。有吗?如果不是,有没有比在每个修改数据(或返回稍微不同的副本)的函数中包装检查更好的方法 我希望至少有120个元素,但不超过几千个,以防万一 有吗 我相信不是在标准图书馆。我会使用一对由一个dict()和一个set()组成的值。这样的东西怎么样: -module(unidict). -export([
我相信不是在标准图书馆。我会使用一对由一个
dict()
和一个set()
组成的值。这样的东西怎么样:
-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.
示例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}
您可以对几百个元素使用一个简单的{key,value}列表:
put(L, K, V) ->
case lists:keyfind(K, 1, L) of
{K, _} -> erlang:error(badarg);
false ->
case lists:keyfind(V, 2, L) of
{_, V} -> erlang:error(badarg);
false -> [{K,V} | L]
end
end.
get(L, K) ->
case lists:keyfind(K, 1, L) of
{K, V} -> {'value', V};
false -> 'undefined'
end.
我喜欢这一点,但是你为什么用
dict:find
而不是dict:is\u key
?你说得对,dict:is\u key在这里可以稍微好一点。我先考虑dict:update,然后再试试dict:find