minor code improvements, added ninth and tenth

svn: r8364
This commit is contained in:
Eli Barzilay 2008-01-18 16:04:43 +00:00
parent a9f76e95d6
commit cd239fc23c
2 changed files with 49 additions and 53 deletions

View File

@ -1,14 +1,6 @@
#lang scheme/base
(module list scheme/base (provide first second third fourth fifth sixth seventh eighth ninth tenth
(provide first
second
third
fourth
fifth
sixth
seventh
eighth
last last
rest rest
@ -18,10 +10,9 @@
empty?) empty?)
(define (first x) (define (first x)
(unless (and (pair? x) (if (and (pair? x) (list? x))
(list? x)) (car x)
(raise-type-error 'first "non-empty list" x)) (raise-type-error 'first "non-empty list" x)))
(car x))
(define-syntax define-lgetter (define-syntax define-lgetter
(syntax-rules () (syntax-rules ()
@ -31,7 +22,8 @@
(let loop ([l l0] [pos npos]) (let loop ([l l0] [pos npos])
(if (pair? l) (if (pair? l)
(if (eq? pos 1) (car l) (loop (cdr l) (sub1 pos))) (if (eq? pos 1) (car l) (loop (cdr l) (sub1 pos)))
(raise-type-error 'name (format "list with ~a or more items" npos) l0))) (raise-type-error
'name (format "list with ~a or more items" npos) l0)))
(raise-type-error 'name "list" l0)))])) (raise-type-error 'name "list" l0)))]))
(define-lgetter second 2) (define-lgetter second 2)
(define-lgetter third 3) (define-lgetter third 3)
@ -40,22 +32,22 @@
(define-lgetter sixth 6) (define-lgetter sixth 6)
(define-lgetter seventh 7) (define-lgetter seventh 7)
(define-lgetter eighth 8) (define-lgetter eighth 8)
(define-lgetter ninth 9)
(define-lgetter tenth 10)
(define (last x) (define (last l)
(unless (and (pair? x) (if (and (pair? l) (list? l))
(list? x)) (let loop ([l l])
(raise-type-error 'last "non-empty list" x)) (if (pair? (cdr l))
(let loop ([x x]) (loop (cdr l))
(if (pair? (cdr x)) (car l)))
(loop (cdr x)) (raise-type-error 'last "non-empty list" l)))
(car x))))
(define (rest x) (define (rest l)
(unless (and (pair? x) (if (and (pair? l) (list? l))
(list? x)) (cdr l)
(raise-type-error 'rest "non-empty list" x)) (raise-type-error 'rest "non-empty list" l)))
(cdr x))
(define cons? (lambda (x) (pair? x))) (define cons? (lambda (l) (pair? l)))
(define empty? (lambda (x) (null? x))) (define empty? (lambda (l) (null? l)))
(define empty '())) (define empty '())

View File

@ -461,6 +461,10 @@ Like @scheme[assoc], but finds an element using the predicate
@defproc[(eighth [lst list?]) any]{Returns the eighth element of the list.} @defproc[(eighth [lst list?]) any]{Returns the eighth element of the list.}
@defproc[(ninth [lst list?]) any]{Returns the ninth element of the list.}
@defproc[(tenth [lst list?]) any]{Returns the tenth element of the list.}
@defproc[(last [lst list?]) any]{Returns the last element of the list.} @defproc[(last [lst list?]) any]{Returns the last element of the list.}
@; ---------------------------------------- @; ----------------------------------------