Erlang Central

Difference between revisions of "Testing Hash for Key"

From ErlangCentral Wiki

 
(Discussion)
Line 40:Line 40:
 
== Discussion ==
 
== Discussion ==
  
ets tables have a similar predicate, called ets:member/2, that retursn true if the key is a member of the table, and false otherwise.
+
ets tables have a similar predicate, called ets:member/2, that returns true if the key is a member of the table, and false otherwise.
  
 
<code>
 
<code>

Revision as of 01:12, 10 March 2007

Problem

You need to know wheter a hash (Dictionary) has a particular key, regardless of whatever value may be associated with a key.

Solution

The predicate dict:is_key/2 returns true if the key is present in the dictionary, and false otherwise.

1> Dict = dict:from_list([{1,"foo"}, {2,"bar"}, {3, "baz"}]).
{dict,3,
      16,
      16,
      8,
      80,
      48,
      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
      {{[],
        [[3,98,97,122]],
        [],
        [],
        [],
        [],
        [[2,98,97,114]],
        [],
        [],
        [],
        [],
        [[1,102,111,111]],
        [],
        [],
        [],
        []}}}
2> dict:is_key(1, Dict).                                     
true
3> dict:is_key(4, Dict).
false

Discussion

ets tables have a similar predicate, called ets:member/2, that returns true if the key is a member of the table, and false otherwise.

4> MyETS = ets:new('Cookbook Test', []).
15
5> ets:insert(MyETS, {1, "foo"}).
true
6> ets:insert(MyETS, {2, "bar"}).   
true
7> ets:insert(MyETS, {3, "baz"}).   
true
8> ets:member(MyETS, 2).
true
9> ets:member(MyETS, 3).
true
10> ets:member(MyETS, 4).
false