[racket] missing solution 19.2.4 ex:para-non-empty

From: Daniel Bastos (dbastos at toledo.com)
Date: Fri Aug 29 16:37:21 EDT 2014

Perhaps I didn't understand this exercise. The hint advises me to work with
a particular case and then generalize. I did this, but it seems that even
in a particular case the most natural solution seems to be the general one.
The generalization took place only in the data definition, but it didn't
seem to affect the function definition.

;; Exercise 19.2.4. Here is a parametric data
;; definition of non-empty lists:

;; A (non-empty-listof ITEM) is either
;; 1. (cons s empty), or
;; 2. (cons s l) where l is a (non-empty-listof ITEM)
;;     and s is always an ITEM.

;; Develop the function last, which consumes
;; a (non-empty-listof ITEM) and produces the last
;; ITEM in that list.

;; Hint: Replace ITEM with a fixed class of data to
;; develop an initial draft of last. When finished,
;; replace the class with ITEM throughout the function
;; development.

;; Draft. a (non-empty-listof number) is either
;; 1. (cons s empty), or
;; 2. (cons s l) where l is a (non-empty-listof number)
;; and s is always a number.

;; last-number: non-empty-ls -> number
;; consumes a non-empty list of numbers and produces its last number
(define (last-number non-empty-ls)
  (cond
    [(empty? (rest non-empty-ls))
     (first non-empty-ls)]
    [else
     (last-number (rest non-empty-ls))]))

;; Generalizing to ITEM.

;; a (non-empty-listof ITEM) is either
;; 1. (cons s empty), or
;; 2. (cons s l) where l is a (non-empty-listof ITEM)
;; and s is always an ITEM.

;; last: non-empty-ls -> ITEM
;; consumes a non-empty list of ITEMs and produces its last ITEM
(define (last non-empty-ls)
  (cond
    [(empty? (rest non-empty-ls))
     (first non-empty-ls)]
    [else
     (last (rest non-empty-ls))]))

(check-expect (last-number (list 1 2 3 4 5)) 5)
(check-expect (last (list (list 1) (list 2) (list 3))) (list 3))
(check-expect (last '(a b c d e f)) 'f)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20140829/e3cd2c2b/attachment.html>

Posted on the users mailing list.