<div dir="ltr">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.<div>
<br></div><div><div><div>;; Exercise 19.2.4. Here is a parametric data </div><div>;; definition of non-empty lists:</div><div><br></div><div>;; A (non-empty-listof ITEM) is either</div><div>;; 1. (cons s empty), or</div>
<div>
;; 2. (cons s l) where l is a (non-empty-listof ITEM)</div><div>;; and s is always an ITEM.</div><div><br></div><div>;; Develop the function last, which consumes </div><div>;; a (non-empty-listof ITEM) and produces the last </div>
<div>;; ITEM in that list.</div><div><br></div><div>;; Hint: Replace ITEM with a fixed class of data to</div><div>;; develop an initial draft of last. When finished, </div><div>;; replace the class with ITEM throughout the function</div>
<div>;; development.</div><div><br></div><div>;; Draft. a (non-empty-listof number) is either</div><div>;; 1. (cons s empty), or</div><div>;; 2. (cons s l) where l is a (non-empty-listof number)</div><div>;; and s is always a number.</div>
<div><br></div><div>;; last-number: non-empty-ls -> number</div><div>;; consumes a non-empty list of numbers and produces its last number</div><div>(define (last-number non-empty-ls)</div><div> (cond</div><div> [(empty? (rest non-empty-ls)) </div>
<div> (first non-empty-ls)]</div><div> [else </div><div> (last-number (rest non-empty-ls))]))</div><div><br></div><div>;; Generalizing to ITEM.</div><div><br></div><div>;; a (non-empty-listof ITEM) is either</div>
<div>;; 1. (cons s empty), or</div><div>;; 2. (cons s l) where l is a (non-empty-listof ITEM)</div><div>;; and s is always an ITEM.</div><div><br></div><div>;; last: non-empty-ls -> ITEM</div><div>;; consumes a non-empty list of ITEMs and produces its last ITEM</div>
<div>(define (last non-empty-ls)</div><div> (cond</div><div> [(empty? (rest non-empty-ls)) </div><div> (first non-empty-ls)]</div><div> [else </div><div> (last (rest non-empty-ls))]))</div></div></div><div>
<br></div><div><div>(check-expect (last-number (list 1 2 3 4 5)) 5)</div><div>(check-expect (last (list (list 1) (list 2) (list 3))) (list 3))</div><div>(check-expect (last '(a b c d e f)) 'f)</div></div></div>