用空列表填充元组列表 [英] Transpose list of tuples filling with empty lists
问题描述
我是Scheme的新手,我正在尝试编写一个将 n 列表组合成 n -tuple列表的过程.如果列表的大小不同,则当相应列表用完元素时,元组应包含空列表()
.
I'm new to Scheme and I'm trying to write a procedure which combines n list into a list of n-tuples. If the lists are of different size, the tuples should contain the empty list ()
when the corresponding list ran out of elements.
我当前的实现如下:
(define (comb list1 list2)
(cond [(empty? list1) empty]
[(empty? list2) empty]
[else (cons (list (first list1) (first list2))
(comb (rest list1) (rest list2)))]))
但是,当列表中没有更多项目可合并时,此程序不会生成另一个元组.例如,(comb '(1 2 3 ) '(3 4))
仅产生((1 3) (2 4))
However, this program doesn't produce another tuple when there are no more items in the list to combine. For instance, (comb '(1 2 3 ) '(3 4))
produces only ((1 3) (2 4))
我该如何解决?
推荐答案
这有点棘手,我认为这对于只学习该语言基础知识的人来说并不适合.无论如何,这是我针对高阶程序提出的解决方案:
This is a bit tricky, and I believe it's not an appropriate exercise for someone who is just learning the basics of the language. Anyway, here's my proposed solution, in terms of higher-order procedures:
; helper procedure for filling a list with arbitrary values at the end
(define (fill lst val num)
(append lst
(build-list num (const val))))
; helper procedure for transposing a list of lists
(define (transpose lsts)
(apply map list lsts))
; main procedure
(define (list-tuples lsts)
(let* ((lengths (map length lsts)) ; obtain the length of each sublist
(max-length (apply max lengths))) ; find out the maximum length
(transpose ; build new sublists element-wise
(map (lambda (lst len) ; build sublists of the right length
(fill lst '() (- max-length len))) ; fill sublists with '()
lsts
lengths))))
诀窍是找到列表的最大长度,然后以该长度构建新列表,最后以'()
填充它们.之后,只需从每个子列表中选取一个元素即可构建答案.它可以按预期工作:
The trick was to find the maximum length of the lists and then build new lists with that length, filling them with '()
at the end. After that, it's a simple matter of building the answer by taking one element from each sublist. It works as expected:
(list-tuples '((m n o) (1) (x y)))
=> '((m 1 x) (n () y) (o () ()))
这篇关于用空列表填充元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!