Fundamentals of CS I (CS151 2001S) : Reference

list-ref: extract an element of a list

Procedurelist-ref
Parametersl, a list
i, an integer
PurposeExtracts the ith element of the list. Elements are numbered starting at 0.
ProducesAn element of the list.
PreconditionsTwo parameters (verified).
l is a list (verified). i >= 0 (verified). i < (length l) (verified).
PostconditionsDoes not affect l.
Examples
> (list-ref (list 1 2 3) 0)
1
> (list-ref (list 'a 'b 'c) 0)
a
> (list-ref (list 'a 'b 'c) 2)
c
> (list-ref (list 'a 'b 'c) 3)
list-ref: index 3 too large for list: (a b c)
> (define lists (list (list 'a 'b 'c) (list 1) (list 4 2 1 0)))
> lists
((a b c) (1) (4 2 1 0))
> (list-ref lists 0)
(a b c)
> (list-ref (list-ref lists 0) 1)
b
> (list-ref (list 'a 'b 'c) -1)
list-ref: expects type <non-negative exact integer> as 
  2nd argument, given: -1; other arguments were: (a b c)

Disclaimer: I usually create these pages on the fly. This means that they are rarely proofread and may contain bad grammar and incorrect details. It also means that I may update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This page was generated by Siteweaver on Thu Feb 22 05:48:05 2001.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2001S/list-ref.html.
You may validate this page's HTML.
The source was last modified Sun Jan 28 12:30:21 2001.