Lisp-likeness

Pascal Costanza pc at p-cos.net
Tue Mar 15 19:00:01 EST 2005


Marcin 'Qrczak' Kowalczyk wrote:
> tar at sevak.isi.edu (Thomas A. Russ) writes:
> 
> 
>>>>(defun addn (n)
>>>>	  #'(lambda (x)
>>>>	      (+ x n)))
>>>
>>>The same as 
>>>def addn(n):
>>>	def fn(x):
>>>		return n + x
>>>	return fn
>>
>>Is this really equivalent?
>>
>>What happens if you call addn more than once with different
>>parameters.  Will you get different functions that you can
>>use simultaneously?
> 
> 
> Yes.
> 
> It also behaves correctly when a variable it refers to is later
> mutated.
> 
> 
> BTW, the fact that a closure refers to a variable itself rather to its
> current value can be used to check the true attitude of languages with
> respect to functional programming, by observing how they understand
> their basic loops :-)

None of the examples you show close over values. The difference is in 
whether the loop constructs use one binding for their control variable 
or create new bindings in each iteration:

(loop for i below 10
       collect (lambda (x) (setq i x)) into setters
       collect (lambda () i) into getters
       finally
       (print (funcall (elt getters 0)))
       (funcall (elt setters 4) 42)
       (print (funcall (elt getters 9))))

=> 10
=> 42

If this difference matters to you, just be more explicit.


Pascal



More information about the Python-list mailing list