Erlang中queue的实现方式

 

Erlang中queue的实现很有意思,queue中数据的组织方式与我们常见的queue不同,如Erlang queue的reverse的时间复杂度为O(1),严格的说这种queue实现方式对所有的FP都适用。

 

 

%% Efficient implementation of double ended fifo queues
%%
%% Queue representation
%%
%% {RearList,FrontList}
%%
%% The first element in the queue is at the head of the FrontList
%% The last element in the queue is at the head of the RearList,
%% that is; the RearList is reversed.
%%

 

 像一般的queue操作代码就不贴了,关键看一下reverse函数:

%% Return reversed queue
%%
%% O(1)
-spec reverse(Q1 :: queue()) -> Q2 :: queue().
reverse({R,F}) when is_list(R), is_list(F) ->
    {F,R};
reverse(Q) ->
    erlang:error(badarg, [Q]).
 

Have fun!

 

 

你可能感兴趣的:(erlang,Queue)