Python syntax in Lisp and Scheme
Daniel Silva
dsilva at ccs.neu.edu
Fri Oct 3 18:32:57 EDT 2003
On Fri, 3 Oct 2003, MetalOne wrote:
> I am just barely familiar with Lisp and Scheme. However, I always
> find comments like the above interesting. I have seen other people
> make this claim also.
> However, from an earlier post on comp.lang.python comparing a simple
> loop.
>
> Scheme
> (define vector-fill!
> (lambda (v x)
> (let ((n (vector-length v)))
> (do ((i 0 (+ i 1)))
> ((= i n))
> (vector-set! v i x)))))
>
> Python
> def vector_fill(v, x):
> for i in range(len(v)):
> v[i] = x
>
> To me the Python code is easier to read, and I can't possibly fathom
> how somebody could think the Scheme code is easier to read. It truly
> boggles my mind.
>
I'd prefer one of these two implementations myself:
(define (vector-fill! v x)
(let loop ([i (sub1 (vector-length v))])
(unless (< i 0)
(vector-set! v i x)
(loop (sub1 i)))))
(define (vector-fill-again! v x)
(for-each (lambda (i)
(vector-set! v i x))
(build-list (vector-length v) identity)))
The second one actually does almost exactly what the Python version does,
other than creating a lambda and mapping identity across range(len(v)).
If you want to use macros to make a for-each that does just what your
example asks for:
(define-syntax (for stx)
(syntax-case stx ()
[(_ idx lst exp) #`(for-each (lambda (idx)
exp)
lst)]))
And given a function range that does the same thing:
(define (range r)
(build-list r identity))
Now you have the same for loop:
(define (my-vector-fill! v x)
(for i (range (vector-length v))
(vector-set! v i x)))
- Daniel
More information about the Python-list
mailing list