[erlang-questions] Thinking in Erlang

黃耀賢 (Yau-Hsien Huang) g9414002.pccu.edu.tw@REDACTED
Fri Apr 30 07:35:59 CEST 2010


On Fri, Apr 30, 2010 at 12:10 AM, David N Murray <dmurray@REDACTED>wrote:

> On Apr 29, é»^Cè^@^@è³¢ (Yau-Hsien Huang) scribed:
>
> > On Wed, Apr 28, 2010 at 10:29 AM, David N Murray <dmurray@REDACTED
> >wrote:
> >
> > {#Fun<test.0.44084711>,[c]}
> > 15>
> >
> > Right?
> >
>
> No, the lisp returns the queue (list).
>
> * (defparameter q (make-fqueue 3))
> Q
> * (funcall q 1)
> (1)
> * (funcall q 2)
> (2 1)
> * (funcall q 3)
> (3 2 1)
> * (funcall q 4)
> (4 3 2)
> *
>
> Dave
>

 Interesting, mutable variables.

Two important features of Erlang are process-communication modelling and
immutable objects. Thus, one of same implementations can be:

----------------------------------------------------------------
%% In module "test"

% A client queue functions.
enq(Fq, E) ->
    Fq ! {self(), E},
    receive
{Q,O} ->
    {Q,O};
Q -> Q
    end.

fqueue(N) ->
    spawn(test, q, [N, []]).

% Function for maintaining a queue while manipulating a queue function.
q(N, Q) ->
    receive
{Pid, break} ->
    Pid ! Q;
{Pid, E} ->
    Q1 = [E|Q],
    if length(Q1) > N ->
    Pid ! {lists:sublist(Q1, 1, N),
   lists:sublist(Q1, N+1, N+1)},
    q(N, lists:sublist(Q1, 1, N));
       true ->
    Pid ! {Q1, []},
    q(N, Q1)
    end
    end.
--------------------------------------------------

Output:

8> Q_ = test:fqueue(2).
<0.77.0>
9> test:enq(Q_,a).
{[a],[]}
10> test:enq(Q_,b).
{[b,a],[]}
11> test:enq(Q_,c).
{[c,b],[a]}
12>


More information about the erlang-questions mailing list