In this lecture we explore one of the most powerful features of Scheme -- the notion of a list.
(define x '(a b c d e)) '(a b c d e) (define y '(1 2 (+ 3 4) 5 6)) '(1 2 (+ 3 4) 5 6))
Another way to create lists is with the "list" function. This creates a list of
its arguments
(define u (list 'a 'e 'i 'o 'u))
'(a e i o u)
(define v (list 1 2 (+ 3 4) 5 6))
'(1 2 7 5 6)
The "list" function evaluates its arguments so in particular v above and y in the
previous example give different results.
(null? L)
is true if the list L is empty
(first L)
returns the first element of the list L
(rest L)
returns the list L, but with the first element removed
(cons X L)
creates a new list by adding X to the beginnning of list L
(length L)
returns the length of the list L
(null? ()) ;==> #t (null? '(a b c)) ;==> #f (first '(a b c)) ;==> a (rest '(a b c)) ;==> (b c) (rest '(a)) ;==> () (cons 'a '(b c)) ;==> (a b c) (cons 'a '()) ;==> (a)
(define (second x) (first (rest x))) (define (third x) (first (rest (rest x)))) OR (define (third x) (second (rest x))) (define (fourth x) (first (rest (rest (rest x))))) OR (define (fourth x) (third (rest x))) (define (get-nth N L) (if (= N 1) (first L) (get-nth (- N 1) (rest L))))Lets now trace the evolution of a call to "get-nth":
> (get-nth 4 '(a b c d e f g h)) --> (get-nth 3 '(b c d e f g h)) --> (get-nth 2 '(c d e f g h)) --> (get-nth 1 '(c d e f g h)) -->
(define (random N) (Math.ceil (* N (Math.random)))) (define (get-random L) (get-nth (random (length L)) L))
here is a link to the source code.