Erlang 编程/使用 ets
外观
ETS 是 Erlang 表存储系统,它提供基于哈希的数据存储和访问功能。这些功能在恒定时间内运行。ETS 数据在进程运行期间存储在该进程中。
以下是如何在 ETS 中使用一些简单函数的示例。请注意,由于“goofy”没有姓氏,所以表格不是正方形的。
-module(test_ets). -compile(export_all). start() -> start( mouse ). start( Animal ) -> Kingdom = ets:new( 'magic', [] ), % note: table is not square populate( Kingdom, [{micky,mouse}, {mini,mouse}, {goofy}] ), Member = ets:member( Kingdom, micky ), io:format( " member ~w ~n ", [ Member ] ), %% show_next_key( Kingdom, micky ), %% Not work as expected in OTP 19.2 %% Do a minor change FirstKey = ets:first(Kingdom), show_next_key(Kingdom, FirstKey), find_animal( Kingdom, Animal ). show_next_key( _Kingdom, '$end_of_table' ) -> done; show_next_key( Kingdom, Key) -> Next = ets:next( Kingdom, Key ), io:format( " next ~w ~n ", [ Next ] ), show_next_key( Kingdom, Next ). populate( _Kingdom, [] ) -> {done,start}; populate( Kingdom, [H | T] ) -> ets:insert( Kingdom, H ), populate( Kingdom, T ). find_animal( Kingdom, Animal ) -> ets:match( Kingdom, { '$1', Animal } ).
% ============== % sample output % ============== % 53> test_ets:start(). % member true % next mini % next goofy % next '$end_of_table' % [[mini],[micky]]