在Scheme中手动评估函数调用

时间:2015-08-27 13:08:24

标签: scheme

(define remove-leftmost
    (lambda (item ls)
       (cond
          ((null? ls) '())
          ((equal? (car ls) item) (cdr ls))
           (pair? (car ls))
            (let ((rem-list (remove-leftmost item (car ls)))
            (cons rem-list (cond
                                   ((equal? (car ls) rem-list)
                                    (remove-leftmost item (cdr ls)))
                                     (else (cdr ls))))))
       (else (cons (car ls) (remove-leftmost item (cdr ls)))))))

现在评估(删除最左边' b(a(b c)(c(b a)))):

(cons a (remove-leftmost 'b ((b c) (c (b a)))))
(cons a (cons (c) ((c (b a)))))
(cons a ((c)(c (b a))))
(a (c)(c (b a)))

评估是否有效?如果没有,如何解决?

1 个答案:

答案 0 :(得分:2)

你真的需要识别你的代码。将代码粘贴到DrRacket并按 CTRL + i 之后,很明显代码中存在许多错误:

(define remove-leftmost
  (lambda (item ls)
    (cond
      ((null? ls) '())
      ((equal? (car ls) item) (cdr ls))
      (pair? (car ls)) 
      (let ((rem-list (remove-leftmost item (car ls)))
            (cons rem-list (cond
                             ((equal? (car ls) rem-list)
                              (remove-leftmost item (cdr ls)))
                             (else (cdr ls))))))
      (else (cons (car ls) (remove-leftmost item (cdr ls)))))))

如果未满足两个第一个术语,则将pair?作为谓词表达式。其余的术语从未尝试过,因为pair?始终为真,因此(car ls)为你的程序最可能的结果(Scheme没有函数)。

只是想猜测我认为代码应该看起来像这样:

(define remove-leftmost
  (lambda (item ls)
    (cond
      ((null? ls) '())
      ((equal? (car ls) item) (cdr ls))
      ((pair? (car ls)) 
       (let ((rem-list (remove-leftmost item (car ls))))
         (cons rem-list
               (cond
                 ((equal? (car ls) rem-list)
                  (remove-leftmost item (cdr ls)))
                 (else (cdr ls))))))
      (else
       (cons (car ls) 
             (remove-leftmost item (cdr ls)))))))

(remove-leftmost 'b '(a (b c) (c (b a))))
; ==> (a (c) (c (b a)))

我已经放了一些换行符,DrRacket根据代码设置了它。请注意额外的括号,这些括号几乎对人类不可见,但对于格式化此类代码的IDE则不会。