2013-04-20 27 views
0

我得到“错误:无效的lambda:(lambda(insert-all))”。这个Scheme程序中的错误在哪里?

(define permutations 
(lambda (L) 
    (let 
    ((insert-all 
    (lambda (e Ls) 
    (let 
    ((insert-one 
     (lambda (L) 
     (letrec 
     ((helper 
     (lambda(L R) 
     (if (null? R) 
      (list (append L(list e)R)) 
      (helper (append L (list (car R))) (cdr R)) 
     )))) 
      (helper '() L))))) 
      (apply append(map insert-one Ls))))))) 

    (cond ((null? L) '()) 
    ((null?(cdr L)) (list L)) 
    (else (insert-all (car L) (permutations ((cdr L)))))))) 

它应该返回给定列表的所有排列。

+0

对于什么输入,你会得到'无效lambda'错误? '(排列((cdr L)))'是不正确的。 – GoZoner 2013-04-20 05:40:21

回答

1

您在无效方案中提供的表单。具体而言,您的最高级别let表单没有正文。您可能会认为cond条款是正文,但由于括号不同,它不是let的一部分。老实说,这是你格式化的错。这里是一个“正确的”格式化方案形式:

(define (permutations L) 
    (let ((insert-all 
     (lambda (e Ls) 
      (let ((insert-one 
        (lambda (L) 
        (let helper ((L '()) (R L)) 
         (if (null? R) 
          (list (append L (list e) R)) 
          (helper (append L (list (car R))) 
            (cdr R))))))) 
      (apply append (map insert-one Ls)))))) 

    (cond ((null? L)  '()) 
      ((null? (cdr L)) (list L)) 
      (else (insert-all (car L) 
          (permutations (cdr L))))))) 

至少它编译和运行,但它不会产生正确的答案(虽然我不知道什么是正确输入的话):

> (permutations '(a b c)) 
((c b a)) 
> (permutations '((a b) (1 2))) 
(((1 2) (a b))) 

这里是工作的落实:

(define (permutations L) 
    (define (insert-all e Ls) 
    (apply append 
      (map (lambda (e) 
        (map (lambda (x) (cons e x)) Ls)) 
       e))) 
    (cond ((null? L)  '()) 
     ((null? (cdr L)) (map list (car L))) 
     (else (insert-all (car L) 
          (permutations (cdr L)))))) 


> (permutations '((a b) (1 2) (x y))) 
((a 1 x) (a 1 y) (a 2 x) (a 2 y) (b 1 x) (b 1 y) (b 2 x) (b 2 y)) 

代码的基本结构是好的;只是执行你的insert-onehelper缺乏。

+0

谢谢。你的解释确实有帮助。 – 2013-04-20 21:04:43

相关问题