Facebook
Banner
XMPP JavaScript Library READ MORE

Queue implementation in Erlang

Erlang, Sachin Puri, 2019-12-04 23:07:58


%% @author Sachin Puri

-module(cqueue).
-behaviour(gen_server).
-compile(export_all).

%% ====================================================================
%% API functions
%% ====================================================================

start()->
    gen_server:start({local, cqueue}, ?MODULE, [], []).

add(Data)->
    gen_server:call(?MODULE, {add, Data}).

remove()->
    gen_server:call(?MODULE, {remove}).

search(Data)->
    gen_server:call(?MODULE, {search, Data}).

ls()->
    gen_server:call(?MODULE, {ls}).

stop()->
    gen_server:cast(?MODULE, stop).

clear()->
    gen_server:call(?MODULE, clear).
    
%% ====================================================================
%% Internal functions
%% ====================================================================

init(_Args)->
    io:format("Queue server started~n"),
    {ok, []}.

handle_call({add, Data},_From, State)->
    NewState = add(State, Data),
    {reply, NewState, NewState};

handle_call({remove},_From, [H|T])->
    NewState = T,
    {reply, H, NewState};

handle_call({remove},_From, [])->
    {reply, [], []};

handle_call({ls},_From, State)->
    {reply, State, State};

handle_call({search, Data},_From, State)->
    Result = search(Data, State, 1),
    {reply, Result, State};

handle_call(clear,_From, _State)->
    {reply, [], []}.





handle_cast(stop, State) ->
  {stop, normal, State};

handle_cast(_Request, State) ->
  {noreply, State}.




handle_info(_Info, State) ->
  {noreply, State}.

terminate(_Reason, _State) ->
    io:format("cqueue terminating.~n"),
  ok.

code_change(_OldVsn, State, _Extra) ->
  {ok, State}.




add([H|T], Data)->
    [H|add(T, Data)];

add([], Data)->
    [Data].




search(Data, [Data|_], Index)->
    Index;

search(Data, [_H|T], Index)->
    search(Data, T, Index+1);

search(_Data, [], _Db)->
    0.

 

Add Your Comment
   
    Yes! I want to receive all comments by email

  by Bhaskar on 25-Jun-2022 10:36 pm
Thanks for the solution
  • Reply
  •  0 Like
  •  0 Dislike
  • Report
  by Ajay on 25-Jun-2022 10:35 pm
Nice
  • Reply
  •  0 Like
  •  0 Dislike
  • Report