dict module:
map
fold
fetch_keys
ets module:
foldl
foldr
first and next
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 |
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 |
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.
| CookbookForm | |
|---|---|
| TopicType: | Recipe |
| ParentTopic: | HashRecipes |
| TopicOrder: | 060 |