Erlang Central

Difference between revisions of "Adding Element to Hash"

From ErlangCentral Wiki

 
Line 87: Line 87:
 
</code>
 
</code>
  
[[Category:CookBook]]ç
+
[[Category:CookBook]][[Category:HashRecipes]]

Revision as of 02:25, 4 September 2006

Problem

You need to add an entry to a Hash.

Solution

Use the dict:append/3 or dict:store/3 functions to add to an existing Dictionary. Use the ets:insert/3 function to add an element to an existing ETS table.

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> Dict3 = dict:append(2, "bar", Dict2).
{dict,2,
      16,
      16,
      8,
      80,
      48,
      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
      {{[],[],[],[],[],[],[[2,"bar"]],[],[],
        [],[],[[1,"foo"]],[],[],[],[]}}}
4> MyETS = ets:new('Cookbook Test', []).  
15
5> ets:insert(MyETS, {1, "foo"}).
true
6> ets:insert(MyETS, {2, "bar"}).  
true

Use the dict:from_list/1 to create a Dictionary from an existing list:

7> DictList = dict:from_list([{1, "foo"}, {2,"bar"}]).
{dict,2,
      16,
      16,
      8,
      80,
      48,
      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
      {{[],
        [],
        [],
        [],
        [],
        [],
        [[2,98,97,114]],
        [],
        [],
        [],
        [],
        [[1,102,111,111]],
        [],
        [],
        [],
        []}}}

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.

You should also note that hash (dictionary) keys may be atoms of any type, so it's perfectly legal to do the following:

8> ets:insert(MyETS, {bar, "bar"}).
9> ets:insert(MyETS, {bar, "bar"}).
true
10> ets:insert(MyETS, {'%%?', "bar"}).
true