Where is the error in this Scheme program? -
i getting "error: invalid lambda: (lambda (insert-all))."
(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))))))))
it supposed return permutations of given list.
the form have provided in not valid scheme. specifically, highest-level let
form not have body. might thinking cond
clause body owing parenthesis not part of let
. honestly, fault of formatting. here 'properly' formatted scheme form:
(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)))))))
at least compiles , runs, although doesn't produce right answer (although don't know proper input it):
> (permutations '(a b c)) ((c b a)) > (permutations '((a b) (1 2))) (((1 2) (a b)))
here implementation works:
(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))
the basic structure of code fine; implementation of insert-one
, helper
lacking.
Comments
Post a Comment