I may have missed this in the R5RS document but how do I create a list of lists in (Chicken) Scheme? I want to be able to take a list, a
, invoke (list-ref a b)
, assign the result to c
, and then invoke (list-ref c d)
, where b
and d
are index values.
Edit: For clarification, suppose I have these lists:
(define citrus (list "oranges" "limes"))
(define apples (list "macintosh" "rome" "delicious"))
And then I want to create a list called fruit
with the citrus
and apples
as list entries.
Here's how you create a list of lists:
(list (list 1 2) (list 3 4))
Or even simpler:
'((1 2) (3 4))
Now, if you already have the other sublists defined as separate lists, put them inside an outer list calling list
again on them:
(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))
To access a position given two indexes, do this - remember, indexes are zero-based:
(define lst '((1 2) (3 4)))
(list-ref (list-ref lst 1) 0)
=> 3
So, the first example in the question would look like this:
(define a '((1 2) (3 4)))
(define b 1)
(define c (list-ref a b))
(define d 0)
(list-ref c d)
=> 3
And the second example (after the edit) would look like this:
(define citrus (list "oranges" "limes"))
(define apples (list "macintosh" "rome" "delicious"))
(define fruit (list citrus apples)) ; here's the list of lists
Now, to access an element first we have to pass the index of the outermost list (let's say we want apples, which are at index 1
in the outermost list) and then the index of the innermost list (let's say we want a macintosh, which is at index 0
in the apples sublist):
(list-ref (list-ref fruit 1) 0)
=> "macintosh"