回复: How to use ets with a foreach way?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

回复: How to use ets with a foreach way?

饕餮
foldl with update_element?
Is there any more efficient way?




------------------ ???? ------------------
???: "Vance Shipley"<vances>;
????: 2013?5?28?(???) ??12:55
???: "??"<249505968>;
??: "erlang-questions"<erlang-questions>;
??: Re: [erlang-questions] How to use ets with a foreach way?



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?

        ets:foldl/3 http://www.erlang.org/doc/man/ets.html#foldl-3

--
        -Vance
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130528/46b85dd0/attachment.html>

Reply | Threaded
Open this post in threaded view
|

How to use ets with a foreach way?

Vance Shipley-2
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