Lisp-likeness

Fernando frr at easyjob.net
Wed Mar 16 10:53:39 CET 2005


On Wed, 16 Mar 2005 00:36:40 +0100, Marcin 'Qrczak' Kowalczyk
<qrczak at knm.org.pl> wrote:


>
>
>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 :-)
>
>Python loses:
>
>>>> closures = []
>>>> for i in range(10):
>...    def add(x):
>...       return x + i
>...    closures.append(add)
>...
>>>> closures[5](1000)
>1009
>
[snip]
>Scheme wins:
>
>> (let ((closures (make-vector 10)))
>    (do ((i 0 (+ i 1)))
>        ((= i 10))
>        (vector-set! closures i (lambda (x) (+ x i))))
>    ((vector-ref closures 5) 1000))
>1005
>
>and what is perhaps surprising, Perl wins:
>
>$ perl -e '
>   foreach my $i (0..9) {
>      push @closures, sub {$_[0] + $i}
>   }
>   print $closures[5](1000), "\n"'
>1005

Smalltalk 'loses' too:

closures := Array new: 10.
1 to: 10 do: [:i |
	closures at: i put: [:x| x + i]].

(closures at: 5) value: 1000
returns 1011



>If you think it's unlikely that one would want to keep a closure
>referring to a loop control variable longer than the loop iteration
>which has created it, think about the loop body spawning a thread.

I'm still not convinced this is really useful, but Scheme's behavior
seems more intuitive.



More information about the Python-list mailing list