[erlang-questions] Thinking in Erlang
Robert Virding
rvirding@REDACTED
Thu Apr 29 20:57:04 CEST 2010
2010/4/29 黃耀賢 (Yau-Hsien Huang) <g9414002.pccu.edu.tw@REDACTED>:
> On Wed, Apr 28, 2010 at 10:29 AM, David N Murray <dmurray@REDACTED>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 reviewed and recalled some Lisp keywords while reading your program.
> 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>,[]}
> ...
> 14> {Q10,O10} = Q9(f).
> {#Fun<test.0.44084711>,[c]}
> 15>
>
> Right?
The really big difference is that Scheme has mutable data while Erlang
has immutable data. The Scheme version can destructively update a
local variable within the lambda so you can keep calling the same
lambda while in the Erlang version, yours, you must return a new fun
each time to contain the updated data. That is one reason for using a
process in this case, a pid is "mutable" in this sense in that you can
send many messages to it.
Robert
More information about the erlang-questions
mailing list