http://erdos.csie.ncnu.edu.tw/~klim/scheme/lisp-1062.html
exercise 9: enumerating tuples
•Define a procedure, (enum-tuples list-1 list-2 .... list-k) which will
generate a list of k-tuples. The tuples contains all combinations of
elements from each list.
$ scheme48
> ,load ex9-enum-tuples.scm
>
> (enum-tuples)
()
> (enum-tuples '(x y z))
((x) (y) (z))
> (enum-tuples '(a b c) '(hello world))
((a hello) (b hello) (c hello) (a world) (b world) (c world))
> (enum-tuples '(1 2) '(h i j k))
((1 h) (2 h) (1 i) (2 i) (1 j) (2 j) (1 k) (2 k))
> (enum-tuples '(hello ohio) '(101 39 11) '(good fine))
((hello 101 good) (ohio 101 good) (hello 39 good) (ohio 39 good)
(hello 11 good) (ohio 11 good) (hello 101 fine) (ohio 101 fine)
(hello 39 fine) (ohio 39 fine) (hello 11 fine) (ohio 11 fine))
> ,exit
$
解答:
;exer9 enumerating tuples
(define proc-list
(lambda (lst f)
(cond
((null? lst) '())
(else
(append (f (car lst)) (proc-list (cdr lst) f)))))
) ;proc-list END
(define combine
(lambda (list1 list2)
(proc-list list1 (lambda (x)
(map (lambda (y) (list x y)) list2))))
) ;combine END
(define enum-tuples
(lambda (x-lst . y-lst*)
(cond
((null? y-lst*) (map list x-lst)) ;case1: (enum-tuples '(x y z))
((null? (cdr y-lst*)) (combine x-lst (car y-lst*)))
(else
(proc-list x-lst (lambda (x)
(map (lambda (y) (cons x y))
(apply enum-tuples y-lst*)))))))
) ;enum-tuples END
執行結果:
沒有留言:
張貼留言