打印所有 ets 表值

问题描述 投票:0回答:1

我正在学习erlang。代码摘自 Joe Armstrong 的 Programming Erlang

-module(my_bank).

-behaviour(gen_server).
-export([start/0]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
     terminate/2, code_change/3]).
-compile(nowarn_export_all).
-compile(export_all).
-define(SERVER, ?MODULE). 

start() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
stop()  -> gen_server:call(?MODULE, stop).

new_account(Who)      -> gen_server:call(?MODULE, {new, Who}).
deposit(Who, Amount)  -> gen_server:call(?MODULE, {add, Who, Amount}).
withdraw(Who, Amount) -> gen_server:call(?MODULE, {remove, Who, Amount}).

init([]) -> {ok, ets:new(?MODULE,[])}.

handle_call({new,Who}, _From, Tab) ->
    Reply = case ets:lookup(Tab, Who) of
        []  -> ets:insert(Tab, {Who,0}), 
               {welcome, Who};
        [_] -> {Who, you_already_are_a_customer}
        end,
    {reply, Reply, Tab};
    
handle_call({add,Who,X}, _From, Tab) ->
    Reply = case ets:lookup(Tab, Who) of
        []  -> not_a_customer;
        [{Who,Balance}] ->
            NewBalance = Balance + X,
            ets:insert(Tab, {Who, NewBalance}),
            {thanks, Who, your_balance_is,  NewBalance} 
        end,
    {reply, Reply, Tab};
    
handle_call({remove,Who, X}, _From, Tab) ->
    Reply = case ets:lookup(Tab, Who) of
        []  -> not_a_customer;
        [{Who,Balance}] when X =< Balance ->
            NewBalance = Balance - X,
            ets:insert(Tab, {Who, NewBalance}),
            {thanks, Who, your_balance_is,  NewBalance};    
        [{Who,Balance}] ->
            {sorry,Who,you_only_have,Balance,in_the_bank}
        end,
    {reply, Reply, Tab};


    
handle_call(stop, _From, Tab) ->
    {stop, normal, stopped, Tab}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.

简单来说,如何在上面的代码中添加一个函数来列出 ets 表中存储的所有帐户信息?

我尝试做类似的事情:

list() -> gen_server:call(?MODULE, list).

handle_call 为:

handle_call(list, _From, Tab) ->
    io:format("~p~n", [Tab]),
    {reply, ok, Tab};

但它不起作用。请问有什么帮助吗?

erlang erlang-otp gen-server ets
1个回答
0
投票

使用

ets:tab2list/1
函数,该函数从表中读取所有记录并将它们作为列表返回:

    io:format("~p~n", [ets:tab2list(Tab)]),
© www.soinside.com 2019 - 2024. All rights reserved.