4

我可能在 R5RS 文档中错过了这一点,但是如何在(鸡)方案中创建列表列表?我希望能够获取一个列表,a调用(list-ref a b),将结果分配给c,然后调用(list-ref c d),其中bd是索引值。

编辑:为澄清起见,假设我有这些列表:

(define citrus (list "oranges" "limes"))
(define apples (list "macintosh" "rome" "delicious"))

然后我想创建一个名为fruit和作为列表条目citrus的列表。apples

4

2 回答 2

5

以下是创建列表列表的方法:

(list (list 1 2) (list 3 4))   

或者更简单:

'((1 2) (3 4))

现在,如果您已经将其他子列表定义为单独的列表,请将它们放在外部列表中list再次调用它们:

(define the-first  (list 1 2))
(define the-second (list 3 4))
(define list-of-lists (list the-first the-second))
list-of-lists
=> '((1 2) (3 4)) 

要访问给定两个索引的位置,请执行以下操作 - 请记住,索引是从零开始的:

(define lst '((1 2) (3 4)))
(list-ref (list-ref lst 1) 0)
=> 3

因此,问题中的第一个示例如下所示:

(define a '((1 2) (3 4)))
(define b 1)
(define c (list-ref a b))
(define d 0)
(list-ref c d)
=> 3

第二个示例(编辑后)如下所示:

(define citrus (list "oranges" "limes"))
(define apples (list "macintosh" "rome" "delicious"))
(define fruit (list citrus apples)) ; here's the list of lists

现在,要首先访问一个元素,我们必须传递最外层列表的索引(假设我们想要苹果,它们位于1最外层列表的索引处),然后是最内层列表的索引(假设我们想要一个 macintosh,它0位于苹果子列表的索引处):

(list-ref (list-ref fruit 1) 0)
=> "macintosh"
于 2013-07-04T02:53:30.497 回答
2

If you want to make a list containing those lists, just call list with them as arguments:

(define fruit (list citrus apples))

(list-ref (list-ref fruit 0) 1)
=> "lime"
于 2013-07-04T03:04:07.583 回答