笛卡尔乘积函数接受列表列表,并返回一个元组列表,其中元素来自第一个位置中的第一个列表,元素来自第二个位置,等等。如下所示:
((1 2 3)) -> ((1) (2) (3))
((1 2) (3 4)) -> ((1 3) (1 4) (2 3) (2 4))
我在看我的一些旧代码,不知道为什么它被附加在外部循环中而不是仅仅映射?有更多球拍经验的人能给我解释一下吗?
(define cartesian-product
(lambda (s)
(if (null? s)
'(())
(append-map (lambda (el1)
(map (lambda (el2)
(cons el1 el2))
(cartesian-product (cdr s))))
(car s)))))
发布于 2016-08-29 15:42:25
因为您需要扁平化递归调用cartesian-product
返回的列表,否则您将得到大量不想要的子列表,看看如果我们不使用append-map
会发生什么
(define cartesian-product
(lambda (s)
(if (null? s)
'(())
(map (lambda (el1)
(map (lambda (el2)
(cons el1 el2))
(cartesian-product (cdr s))))
(car s)))))
(cartesian-product '((1 2 3) (4 5 6)))
=> '(((1 (4)) (1 (5)) (1 (6))) ((2 (4)) (2 (5)) (2 (6))) ((3 (4)) (3 (5)) (3 (6))))
将其与简化列表的结果进行比较:
(define cartesian-product
(lambda (s)
(if (null? s)
'(())
(append-map (lambda (el1)
(map (lambda (el2)
(cons el1 el2))
(cartesian-product (cdr s))))
(car s)))))
(cartesian-product '((1 2 3) (4 5 6)))
=> '((1 4) (1 5) (1 6) (2 4) (2 5) (2 6) (3 4) (3 5) (3 6))
https://stackoverflow.com/questions/39209020
复制相似问题