[erlang-questions] How to use ets with a foreach way?

Vance Shipley vances@REDACTED
Tue May 28 10:50:44 CEST 2013


On Tue, May 28, 2013 at 02:18:34PM +0800, 饕餮 wrote:
}  foldl with update_element?
}  Is there any more efficient way?

Sorry, I missed the point that you want to increment each element.
You can use ets:update_counter/3 to efficiently increment values:

   -module(ets_increment_all).
   
   -export([new/1, increment_all/1]).
   
   new(N) ->
   	Tab = ets:new(count, []),
   	ets:insert(Tab, [{K, 0} || K <- lists:seq(1, N)]),
   	Tab.
   
   increment_all(Tab) ->
   	Key = ets:first(Tab), 
   	increment_all(Tab, Key).
   
   increment_all(_Tab, '$end_of_table') ->
   	ok;
   increment_all(Tab, Key) ->
   	ets:update_counter(Tab, Key, {2, 1}),
   	NextKey = ets:next(Tab, Key),
   	increment_all(Tab, NextKey).


   1> Tab = ets_increment_all:new(10).
   16400

   2> ets:i(Tab).
   <1   > {10,0}
   <2   > {9,0}
   <3   > {6,0}
   <4   > {7,0}
   <5   > {5,0}
   <6   > {3,0}
   <7   > {1,0}
   <8   > {4,0}
   <9   > {2,0}
   <10  > {8,0}
   EOT  (q)uit (p)Digits (k)ill /Regexp -->q
   ok

   3> ets_increment_all:increment_all(Tab).
   ok

   4> ets:i(Tab).                          
   <1   > {10,1}
   <2   > {9,1}
   <3   > {6,1}
   <4   > {7,1}
   <5   > {5,1}
   <6   > {3,1}
   <7   > {1,1}
   <8   > {4,1}
   <9   > {2,1}
   <10  > {8,1}
   EOT  (q)uit (p)Digits (k)ill /Regexp -->q
   ok



On Tue, May 28, 2013 at 10:27:03AM +0800, 饕餮 wrote:
}  Like [A+1|A<-List]
}  How to use ets like this in efficient way?

-- 
	-Vance



More information about the erlang-questions mailing list