scheme - 如何在方案中创建列表列表?

标签 scheme nested-lists chicken-scheme

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

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

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

然后我想创建一个名为 fruit 的列表与 citrusapples作为列表条目。

最佳答案

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

(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/

相关文章:

set - 为什么我的集合 A 和集合 B 的 Union 过程返回集合 A 而没有别的?

html - 嵌套列表 : avoid styling of both lists 上的 CSS

scheme - 如何(eval ...)在鸡 r7rs 库中?

scheme - Racket /基础命名空间

emacs - 有这么多括号,你如何有效地输入 lisp?

recursion - 实现最后一个非零而不延续

chicken-scheme - 鸡计划 - 错误 : unbound variable: chicken-home

python - 如何按列优先顺序显示数字序列?

python - 使用相同元素展开列表

scheme - 在“鸡计划”中安装鸡蛋