【问题标题】:Recurring with anonymous functions Common Lisp vs. Scheme使用匿名函数重复出现 Common Lisp 与 Scheme
【发布时间】:2017-04-11 23:30:57
【问题描述】:

我正在研究 Little Schemer,我正在尝试将所有答案转换为 Common Lisp。 第 8 章讨论了匿名函数以及返回匿名函数。 例如:

(define insertL-f
    (lambda (test?)
        (lambda (new old l)
            (cond
                ((null? l) (quote ()))
                ((test? (car l) old) (cons new l)))
                (else (cons (car l) ((insertL-f test?) new old (cdr l))))))))

我的代码:

(defun insertL-f (test)
    (lambda (new old l)
        (cond
            ((null l) '())
            ((funcall test (car l) old) (cons new l))
            (t (cons (car l) (insertL-f test) new old (cdr l))))))

问题出在第二个代码块的最后一行。我收到错误“cons 的参数太多”,但我不能像 Scheme 代码那样添加一对额外的括号。这种递归风格在 Common Lisp 中是不可能的吗?

【问题讨论】:

    标签: scheme common-lisp


    【解决方案1】:
    (defun insertL-f (test)
      (lambda (new old l)
        (cond
         ((null l) '())
         ((funcall test (car l) old) (cons new l))
         (t (cons (car l)
                  (funcall (insertL-f test)
                           new
                           old
                           (cdr l)))))))
    

    【讨论】:

      【解决方案2】:

      insertL-f 返回一个函数,在您的 Scheme 版本中,您应用它,而在 CL 中,如果使用 funcall 应用它,则将列表展平,但是看起来要返回的函数等于它获取的函数所以你可以通过在本地使用 labels 定义它来缓存它:

      (defun insert-l-f (test)
        (labels ((func (new old l)
                   (cond
                     ((null l) '())
                     ((funcall test (car l) old) (cons new l))
                     (t (cons (car l) (func new old (cdr l)))))))
          #'func))
      

      在使用本地define 的Scheme 中也是如此(实际上是aletrec,语法更扁平):

      (define (insert-l-f test?)
        (define (func new old l)
          (cond
            ((null? l) (quote ()))
            ((test? (car l) old) (cons new l)))
            (else (cons (car l) (func new old (cdr l)))))
        func)
      

      【讨论】:

        猜你喜欢
        • 2010-11-04
        • 1970-01-01
        • 2020-08-16
        • 2011-10-17
        • 1970-01-01
        • 1970-01-01
        • 2013-08-29
        • 1970-01-01
        • 2017-10-19
        相关资源
        最近更新 更多