这里有一个syntax-rules
基于我在其他答案和评论中收到的反馈的解决方案:
(define ($ alist name)
(cdr (assoc name alist)))
(define-syntax with-alist
(syntax-rules ()
[(_ alist names expr)
(let ([alist-local alist])
(apply map (lambda names expr)
(map (lambda (name) ($ alist-local name)) (quote names))))]))
以下是一些用法示例:
> (define alist-example
'((x 1 2 3) (y 4 5 6) (z 7 8 9)))
> (with-alist alist-example (x) (+ x 2))
(3 4 5)
> (with-alist alist-example (x y) (+ x y))
(5 7 9)
> (with-alist alist-example (x y z) (+ x y z))
(12 15 18)
这个答案不足以解决更复杂的例子,(with-alist alist-example (/ y (apply max y)))
,在我的问题中,但我认为这对于我的目的来说是一个合理的方法:
> (with-alist alist-example (y) (/ y (apply max ($ alist-example 'y))))
(2/3 5/6 1)
编辑:经过一些额外的修改,我得出了一个稍微不同的解决方案,我认为它将提供更大的灵活性。
我的新宏,npl
,将速记表达式扩展为名称和过程的列表。
(define-syntax npl
(syntax-rules ()
[(_ (names expr) ...)
(list
(list (quote names) ...)
(list (lambda names expr) ...))]))
该宏的输出被传递给常规过程,with-list-map
,其中包含了大部分核心功能with-alist
上面的宏。
(define (with-alist-map alist names-proc-list)
(let ([names-list (car names-proc-list)]
[proc-list (cadr names-proc-list)])
(map (lambda (names proc)
(apply map proc
(map (lambda (name) ($ alist name)) names)))
names-list proc-list)))
3个例子with-alist
上面的用法可以在一次调用中捕获with-alist-map
.
> (with-alist-map alist-example
(npl ((x) (+ x 2))
((x y) (+ x y))
((x y z) (+ x y z))))
((3 4 5) (5 7 9) (12 15 18))