2013-07-04 80 views
3

我可能錯過了R5RS文檔中的這個內容,但是如何在(雞)方案中創建列表列表?我希望能夠列出一個列表,a,調用(list-ref a b),將結果分配給c,然後調用(list-ref c d),其中bd是索引值。如何在方案中創建列表的列表?

編輯:爲了澄清,假設我有這些列表:

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

然後我想創建一個名爲fruitcitrus和​​爲列表條目列表。

回答

2

如果你想包含這些名單列表,只需要調用list與他們參數:

(define fruit (list citrus apples)) 

(list-ref (list-ref fruit 0) 1) 
=> "lime" 
+0

代碼錯誤,給定的索引返回''limes「',而不是'」羅馬「' –

3

這裏是你如何創建一個列表的列表:

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