【问题标题】:Cond definition in scheme方案中的条件定义
【发布时间】:2014-12-16 14:12:38
【问题描述】:

我想这将是一个简单的问题,但我需要它。我正在用方案(Dr Racket)制作一个模拟器游戏,我想改变 cond 的工作方式。但要改变 cond 的东西,我需要知道定义吗cond 的,我在 Racket 博士中找不到它。有人可以在方案中给出 cond 的定义吗?

【问题讨论】:

  • 我认为你最好编写自己的“cond-like”宏而不是重新定义 cond 本身。
  • “我想改变 cond 的工作方式” Stack Overflow 通常更适合解决特定的技术问题。你在寻找什么不同的行为?

标签: scheme lisp eval conditional-statements racket


【解决方案1】:

cond 的球拍定义在collects/racket/private/cond.rkt 中。它是使用低级语法对象操作编写的,既不使用syntax-rules 也不使用syntax-case,因此除非您非常了解语法对象,否则您将无法阅读它。

作为自定义cond 的替代起点,cond 的一个定义是SRFI 61 中给出的参考实现。它简洁,是我见过的cond 的最佳实现之一:

(define-syntax cond
  (syntax-rules (=> else)

    ((cond (else else1 else2 ...))
     ;; The (if #t (begin ...)) wrapper ensures that there may be no
     ;; internal definitions in the body of the clause.  R5RS mandates
     ;; this in text (by referring to each subform of the clauses as
     ;; <expression>) but not in its reference implementation of cond,
     ;; which just expands to (begin ...) with no (if #t ...) wrapper.
     (if #t (begin else1 else2 ...)))

    ((cond (test => receiver) more-clause ...)
     (let ((t test))
       (cond/maybe-more t
                        (receiver t)
                        more-clause ...)))

    ((cond (generator guard => receiver) more-clause ...)
     (call-with-values (lambda () generator)
       (lambda t
         (cond/maybe-more (apply guard    t)
                          (apply receiver t)
                          more-clause ...))))

    ((cond (test) more-clause ...)
     (let ((t test))
       (cond/maybe-more t t more-clause ...)))

    ((cond (test body1 body2 ...) more-clause ...)
     (cond/maybe-more test
                      (begin body1 body2 ...)
                      more-clause ...))))

(define-syntax cond/maybe-more
  (syntax-rules ()
    ((cond/maybe-more test consequent)
     (if test
         consequent))
    ((cond/maybe-more test consequent clause ...)
     (if test
         consequent
         (cond clause ...)))))

(不过,正如 molbdnilo 所说,请将您的版本命名为 cond 以外的其他名称,以避免混淆。)

【讨论】:

    【解决方案2】:

    r5rs 在此处描述 cond:http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.2.1

    您通常会将其实现为宏。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    相关资源
    最近更新 更多