e r l a n g : c o o k b o o k

/ Erlang.HashRecipePresenceOfKeys

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Testing for the Presence of a Key in a Hash

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 retursn 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


Comments about this recipe

Contributors

-- BrentAFulgham - 31 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: HashRecipes
TopicOrder: 030

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest