简体   繁体   中英

How can I handle Account Number in erlang?

I'm making Bank Account Management system using ETS which will also hold current and savings account, I'm unable to figure it out that how can I generate and retain the series of account numbers since erlang variables are immutable.

So how can I implement a function to generate and save the account number so that the next time the account is created then it allocates the next account number to the previous one?

You can create a process which will keep current number in its state. To obtain next number you have to send message to that process and it returns next number and save it in its state. That's an example of implementation with gen_server:

-module(acc_number).
-behavior(gen_server).

-export([start_link/0, get_number/0]).
-export([init/1, handle_call/3]).

-define(SERVER, ?MODULE).

-record(state, {number}).

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

get_number() ->
    gen_server:call(?SERVER, get_number).

init([]) ->
    {ok, #state{number = 0}}.

handle_call(get_number, _From, #state{number = Number}) ->
    NextNumber = Number + 1,
    {reply, NextNumber, #state{number = NextNumber}}.

Note: In example I implemented only those callbacks which are used to solve the task. You have to implement all callback of gen_server.

So to obtain next number you can do something like this:

acc_number:start_link().
AccountNumber = acc_number:get_number().

The above answer describes a very functional approach using a process to manage the account number assignment. Another method, which is less purely functional but with better performance, would be to leverage the ets framework you say you are already using. Put the next account number into an ets table and increment/assign it with ets:update_counter/3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM