如何通过组合较长列表(例如 4 个元素)中的任意两个元素来生成序列列表?
例如,我想获取 '(1 2)
, '(1 3)
, '(1 4)
, '(2 3)
、'(2 4)
和基于'(1 2 3 4)的
.'(3 4)
最佳答案
该问题要求提供给定列表的 2 个大小的组合列表。它可以通过生成 n 大小组合的更通用过程来实现:
(define (combinations size elements)
(cond [(zero? size)
'(())]
[(empty? elements)
empty]
[else
(append (map (curry cons (first elements))
(combinations (sub1 size) (rest elements)))
(combinations size (rest elements)))]))
当我们指定 size=2
时,它会按预期工作:
(combinations 2 '(1 2 3 4))
=> '((1 2) (1 3) (1 4) (2 3) (2 4) (3 4))
关于list - 使用较长列表中的任意两个元素创建列表 DrRacket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18065250/