# [erlang-questions] Thinking in Erlang

Thu Apr 29 17:46:13 CEST 2010

```On Wed, Apr 28, 2010 at 10:29 AM, David N Murray <>wrote:

> I have a function:
>
> (defun make-fqueue (n)
>  (let ((queue '()))
>    (lambda (e)
>      (push e queue)
>      (if (> (length queue) n)
>        (setf queue (subseq queue 0 n)))
>      queue)))
>
> The above function returns a function that maintains a fixed-length queue,
> pushing each element it receives onto the queue and popping the head off
> when the queue reaches a certain size and always returning the queue.
> Multiple calls to make-fqueue return multiple queue "objects."
>

I didn't understand why it is a Lambda function which will receive an
element,
input it into the inner queue, and end up as a queue but queue function.
I supposed that the make-fqueue/1 returns a queue function which accepts
an element and make another queue function. And the following is an Erlang
translation of you make-fqueue/1:

---------------------------------------------
%% In module "test"
queue(N, Q_) ->
fun (E) ->
Q = push(E, Q_),
if (length(Q) > N) ->
Q1 = lists:sublist(Q, 1, N),
E1 = lists:sublist(Q, N+1, N+1);
true -> Q1 = Q,
E1 = []
end,
{queue(N, Q1), E1}
end.

push(A, Xs) ->
[A|Xs].
-------------------------------------------

Ouput:

4> Q_ = test:queue(3,[]).
#Fun<test.0.44084711>
5> {Q1,O1} = Q_(a).
{#Fun<test.0.44084711>,[]}
6> {Q2,O2} = Q1(a).
{#Fun<test.0.44084711>,[]}
7> {Q3,O3} = Q2(a).
{#Fun<test.0.44084711>,[]}
8> {Q4,O4} = Q3(a).
{#Fun<test.0.44084711>,[a]}
9> {Q5,O5} = Q4(a).
{#Fun<test.0.44084711>,[a]}
10> {Q6,O6} = Q5(b).
{#Fun<test.0.44084711>,[a]}
11> {Q7,O7} = Q6(c).
{#Fun<test.0.44084711>,[a]}
12> {Q8,O8} = Q7(d).
{#Fun<test.0.44084711>,[a]}
13> {Q9,O9} = Q8(e).
{#Fun<test.0.44084711>,[b]}
14> {Q10,O10} = Q9(f).
{#Fun<test.0.44084711>,[c]}
15>

Right?
```