我可能在 R5RS 文档中错过了这一点,但是如何在(鸡)方案中创建列表列表?我希望能够拿一个 list ,a
, 调用 (list-ref a b)
, 将结果赋值给 c
,然后调用 (list-ref c d)
, 其中 b
和 d
是指标值。
编辑:为澄清起见,假设我有这些列表:
(define citrus (list "oranges" "limes"))
(define apples (list "macintosh" "rome" "delicious"))
然后我想创建一个名为
fruit
的列表与 citrus
和 apples
作为列表条目。
最佳答案
以下是创建列表列表的方法:
(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,在 apples 子列表中的索引 0
处):(list-ref (list-ref fruit 1) 0)
=> "macintosh"
关于scheme - 如何在方案中创建列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17461094/