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

 From: Matthias Felleisen (matthias at ccs.neu.edu) Date: Fri Aug 29 22:00:28 EDT 2014 Previous message: [racket] missing solution 19.2.4 ex:para-non-empty Next message: [racket] performance of iteration through a vector Messages sorted by: [date] [thread] [subject] [author]

```On Aug 29, 2014, at 4:37 PM, Daniel Bastos wrote:

> 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.

Correct. The most appropriate solution is going to be:

;; Exercise 19.2.4.

;; 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

(check-expect (last-number (list 1 2 3 4 5)) 5)
(check-expect (last (list (list 1) (list 2) (list 3))) (list 3))

(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-listof ITEM) -> ITEM
;; consumes a non-empty list of ITEMs and produces its last ITEM

(check-expect (last '(a b c d e f)) 'f)

(define (last non-empty-ls)
(cond
[(empty? (rest non-empty-ls)) (first non-empty-ls)]
[else (last (rest non-empty-ls))]))

;; INSIGHT: in this case, the data-specific function and the
;; data-parametric one are identical because the former does
;; not exploit the knowledge about the nature of the list items.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20140829/6943f74d/attachment.html>
```

 Posted on the users mailing list. Previous message: [racket] missing solution 19.2.4 ex:para-non-empty Next message: [racket] performance of iteration through a vector Messages sorted by: [date] [thread] [subject] [author]