可以将宏应用于参数列表吗? [英] Can one apply a macro to an argument list?

查看:31
本文介绍了可以将宏应用于参数列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是能够将宏应用于参数列表,就像应用原始过程将过程应用于参数列表一样.

My goal is to be able to apply a macro to an argument list in the same way the apply primitive procedure applies a procedure to an argument list.

在应用宏的时候列表已经被评估了,没有办法解决这个问题,这很好;我想知道是否有任何方法可以以编程方式将列表拼接"到宏应用程序中(与 unquote-splicing 具有相同的意义).难点在于不能将宏标识符作为参数传递.

The list will already be evaluated at the time of application of the macro, there is no way around that and that’s fine; I am wondering if there is any way to programmatically "splice" the list into the macro application (in the same sense as with unquote-splicing). The difficulty resides in that one cannot pass the macro identifier as an argument.

一个用例是

(apply and list)

相当于

(not (memq #f list))

查看列表中是否有#f.最好是符合 R7RS.

to see if there is a #f in list. Preferably this would be R7RS conformant.

一种 hacky 方式是(如建议的 在 reddit 上)

One sort of hacky way would be (as suggested on reddit)

(eval (cons 'and list))

但这不符合 R7RS,因为 eval 必须采用环境参数,而且在我看来,该标准没有指定如何在调用 eval 时有效地抢夺环境.

but this is not R7RS conformant, as eval must take an environment argument and it seems to me the standard doesn’t specify how to snatch the environment in effect at the call to eval.

另一种解决方案如下,仅当列表直接作为带括号的值序列给出时才有效:

Another half solution is the following, which only works if the list is given directly as a parenthesized sequence of values:

(syntax-rules ()
  ((_ identifier (val ...))
   (identifier val ...)))

推荐答案

我将此作为我对自己的问题找到的部分答案发布,如果没有新问题出现,我会在几天后接受它.

I'm posting this as a partial answer I found to my own question, and I'll accept it in a few days if nothing new pops up.

以下有效,但前提是要应用的宏包含在库中.

The following works, but only if the macro to apply is contained in a library.

(import (scheme base)
        (scheme eval)
        (scheme write))

(define (apply-macro mac args . libs)
  (eval (cons mac args)
        (apply environment libs)))

(define list '(#f #t #t #t))

(display (apply-macro 'and      list  '(scheme base)))    ; => #f
(display (apply-macro 'and (cdr list) '(scheme base)))    ; => #t

这篇关于可以将宏应用于参数列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆