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

/ Erlang.HashRecipeTraverse

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

Traversing a Hash

Problem

You want to perform an action on each entry in a hash.

Solution

Use one of the built-in traversal functions:

Discussion

As with lists, see chapter ListChapter, there are a few basic ways to go over the elements of a hash table applying a procedure on each one. The dict module provides: (1) the map function, which produces a new dictionary containing all entries from the old table, with the values set by applying the function (supplied to map) on each entry; (2) the fold function, which accumulates the results into a value (whose form is dependent on the function passed as an argument); and (3) and the fetch_keys function, which retrieves a list of key values (which can then be used in turn on the result of a fetch command).

1> MyDict = dict:from_list([{foo,1},{bar,2},{baz,3}]).    
{dict,3,
      16,
      16,
      8,
      80,
      48,
      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
      {{[],
        [],
        [[bar|2]],
[...]
        [[baz|3]],
[...]
        [[foo|...]]}}}
2> Dict2 = dict:map(fun(X,V) -> V * V end, MyDict). 
{dict,3,
      16,
      16,
      8,
      80,
      48,
      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
      {{[],
        [],
        [[bar|4]],
[...]
        [[baz|9]],
[...]
        [[foo|...]]}}}
3> dict:fold(fun(Key,Val,AccIn) -> Val * Val + AccIn end, 0,
3> MyDict).                                                 
14
4> lists:foreach(fun(X) -> Y = dict:fetch(X, MyDict),       
4> io:fwrite("~B\n", [2 + Y]) end, dict:fetch_keys(MyDict)).
4
5
3
ok
Note that the internal dictionary ordering is unspecified, so should not be relied on. Also note that the functions passed to the map and fold functions expect to be passed both a key and a value argument. In many cases you can just ignore the key.

The ets module provides: (1) the foldl and foldr functions, which accumulate a result based on each value in the table; (2) the first and next functions, which allow for traversal of the table.

5> MyETS=ets:new('Cookbook',[]).
11
6> ets:insert(MyETS, {foo, 1}).
true
7> ets:insert(MyETS, {bar, 2}). 
true
8> ets:insert(MyETS, {baz, 3}). 
true
9> ets:foldl(fun(A, Accum) ->
9>     {_,X} = A,Accum + (X * X) end, 0, MyETS).
14
10> K1 = ets:first(MyETS)
foo

% traversal function implementation
traverse(Table) -> traverse(Table, ets:first(Table), 0).
traverse(Table, '$end_of_table', Accum) -> Accum;
traverse(Table, Key, Accum) ->
    {_,X} = hd(ets:lookup(Table, Key)),
    traverse(Table, ets:next(Table, Key), Accum + X).

11> traverse(MyETS). 
6

Note that the ets:first, ets:next functions will eventually return the atom '$end_of_table', so this should be the test for the end of the iteration.


Comments about this recipe

Contributors

Based on work by KarlaRamirez.

-- BrentAFulgham - 31 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: HashRecipes
TopicOrder: 060

 
 
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