Retrieving Element From Hash
From Erlang Community
[edit] Problem
You need to retrieve an entry from a Hash.
[edit] Solution
Use the dict:fetch/2 to retrieve an element from an existing Dictionary.
1> Dict = dict:new().
{dict,0,
16,
16,
8,
80,
48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]}}}
2> Dict2 = dict:append(1, "foo", Dict).
{dict,1,
16,
16,
8,
80,
48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[[1,"foo"]],[],[],[],[]}}}
3> dict:fetch(1, Dict2).
["foo"]
|
Use the ets:lookup/2 function to find an element in an existing ETS table.
1> ets:new('Cookbook Test',[public,named_table]).
'Cookbook Test'
2> ets:insert('Cookbook Test',{dog,1,{"Jake",white,20,12}}).
true
3> ets:insert('Cookbook Test',{dog,2,{"Dylan",black,30,8}}).
true
4> ets:insert('Cookbook Test',{dog,3,{"Macy",blue,10,1}}).
true
5> ets:insert('Cookbook Test',{cat,1,{"Kitty",white,10,4}}).
true
6> ets:lookup('Cookbook Test',dog).
[{dog,3,{"Macy",blue,10,1}}]
7> ets:lookup('Cookbook Test',cat).
[{cat,1,{"Kitty",white,10,4}}]
8>
|
[edit] Discussion
Note that ets:insert is destructive, so if you pass the same key a second time, the new element will overwrite the old one associated to the key. An exception to this rule is that if the ets table is created as a duplicate bag, duplicates of the same key/value pairs may be stored.

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati
Click here to order from amazon.com