macros - Looping over a list and generate serial statements in a lambda -
i have macro called compare-and-swap!
:
(define-macro (compare-and-swap! l x y) `(if (> (vector-ref ,l ,x) (vector-ref ,l ,y)) (vector-swap! ,l ,x ,y)))
it works, i'm testing this:
(define v (list->vector '(5 4 3 2 1))) (print v) (compare-and-swap! v 1 2) (print v)
i have function returns list of pairs can call compare-and-swap! on serially sort whole list:
(batcher 8) → ((0 1) (2 3) (0 2) (1 3) (1 2) (4 5) (6 7) (4 6) (5 7) (5 6) (0 4) (2 6) (2 4) (1 5) (3 7) (3 5) (1 2) (3 4) (5 6))
now wish create macro generates lambda sorts n element list calling batcher , doing compare-and-swap!
each pair.
for example,
(generate-sorter 8) → (lambda (l) (begin (compare-and-swap! l 0 1) (compare-and-swap! l 2 3) ...)) → (lambda (l) (begin (if (> (vector-ref l 0) (vector-ref l 1)) (vector-swap! 0 1)) (if (> (vector-ref l 2) (vector-ref l 3)) (vector-swap! 2 3))) ... )
i made function generates necessary code:
(define generate-sorter (lambda (len) (list 'lambda '( li ) 'begin (map (lambda (pair) (list 'compare-and-swap! 'li (first pair) (second pair))) (batcher len))) ))
but don't how make macro.
you don't need macro and, in particular, 'generate' part. suspect thinking macro because result of generate-sorter
can vary call call , hoped encode result through macro expansion. alternative capture result in lexical environment such:
(define-syntax compare-and-swap! (syntax-rules () ((_ l x y) (when (> (vector-ref l x) (vector-ref l y)) (vector-swap! l x y))))) (define (generate-sorter n) (let ((sorters (generate-sorter n))) (lambda (l) (for-each (lambda (sorter) (compare-and-swap! l (car sorter) (card sorter))) sorters)))) (define sorter-8 (generate-sorter 8)) (sorter-8 <l-thingy>) -> <sorted-l-thingy>
Comments
Post a Comment