Subject: Re: Last Value in List
From: rpw3@rigden.engr.sgi.com (Rob Warnock)
Date: 2000/03/27
Newsgroups: comp.lang.scheme
Message-ID: <8bmnjq$ou93c$1@fido.engr.sgi.com>
Brian Tuman  <brian@netkick.com> wrote:
+---------------
| Can someone please help me figure out how to return the list that
| contains only the last entry of a given non-empty list?  I have the
| following code, but it is always outputting the empty list () instead of
| a list containing the last entry.  Help would be much appreciated.
| 
| (define (last-pair n)
|   (cond ((not (pair? n)) n)
|         (else (last-pair (cdr n)))))
+---------------

The trick to recursive definitions is correctly choosing the "base case".
Your English text says that you want "the list that contains only the
last entry of a given non-empty list", but your *code* "(not (pair? n))"
does not match this. A "not-pair" is not a non-empty list.

What would be a question [asked as a Scheme predicate] for which the
answer would be true for "the last entry of a given non-empty list"?
Well, since you named the routine "last-pair", for starters I'd suspect
that you want the desired thing to *be* a pair, yes? That is, given the
input "(a b c d)", you want the answer to be "(d)", not "d", yes?

Next, given some pair, what question can you ask of it to see if it's
the *last* pair of a list?  Well, how about about asking if there are
any *more* pairs left in the list?

That is, the question you should be asking is: "Is this a pair *and*
is it also true that there are no pairs past this one?"


-Rob

p.s. Even if the problem statement doesn't call for it, defensive code
is usually a good idea. What if the caller hands you an empty list? Or
an improper list? What will your code do? Should you maybe add tests for
those situations, too?

-----
Rob Warnock, 41L-955		rpw3@sgi.com
Applied Networking		http://reality.sgi.com/rpw3/
Silicon Graphics, Inc.		Phone: 650-933-1673
1600 Amphitheatre Pkwy.		PP-ASEL-IA
Mountain View, CA  94043