【问题标题】:Simulate a where in scheme with defmac使用 defmac 模拟 where in 方案
【发布时间】:2013-08-23 02:27:21
【问题描述】:

我实际上在 Scheme 中遇到了一个问题。而且我只是不知道如何解决它。这很容易理解,我想对于任何 Scheme 专家来说都很容易。我只需要在定义宏“操作”的方案中使用 defmac 函数来模拟 haskell 的 where 表达式。例如,执行如下代码

> (operation (+ x y) 
   where ([x 1]
          [y (+ x 32)]))
34

我有点熟悉用宏 (defmac) 表示简单对象的方法,但现在我真的被这个问题困住了。

非常欢迎任何帮助或想法。 提前谢谢你。

【问题讨论】:

    标签: macros scheme


    【解决方案1】:

    如果我理解正确,您想将该代码转换为类似

    (let* ((x 1)
           (y (+ x 32))
      (+ x y))
    
    (define-syntax operation
     (syntax-rules (where)
       ((operation expression where body)
        (let* body expression))))
    

    应该这样做,但仅限于“where”在表达式之后的地方

    【讨论】:

    • 老兄,你只迟到了 13 分钟。 :-D
    • Drat,我的人生故事。
    【解决方案2】:

    听起来应该可以解决问题(使用 defmac 的定义):

    (defmac (operation expr
              where (binding ...))
            #:keywords where
      (let* (binding ...)
        expr))
    

    它只是将您的operation 形式转换为等效的let*,因此您的示例将变为:

    (let* ((x 1)
           (y (+ x 32)))
      (+ x y))
    

    【讨论】:

    • 但 Haskell 的 where 也允许 (operation (+ x y) where ([y (+ x 32)] [x 1] ))。 :) 当然不清楚这是 OP 打算解决还是忽略...
    • @Will 在 Haskell 中,由于普遍存在惰性求值,这很容易实现。在 Scheme 中,这有点棘手。 :-)
    • 感谢你们的帮助,但我更需要这样的开始。问题是我的老师对我有一些要求: (defmac (val where ( ) ...) #keywords: val where (let ((val-expr ) .. .) (
    • @user2480503 defmac 不是标准的 Scheme 宏,所以我不得不四处寻找它。我找到的版本是here,我已经重新设计了宏来使用那个版本。
    • @user2480503 我找到了一个不同的版本,这可能是您正在使用的版本:users.dcc.uchile.cl/~etanter/defmac.rkt
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 2012-12-24
    • 1970-01-01
    • 2020-03-09
    • 2023-03-26
    相关资源
    最近更新 更多