I am working through SICP, and the exercise I am working on asks for a procedure that returns the last element in a list. I implemented the procedure last-pair
to do this, but I'm confused why it's returning a list rather than a number:
(define (last-pair alist)
(cond ((null? (cdr alist))
(car alist)) ; still happens if this is just "car alist)"
(else
(last-pair (cdr alist)))))
When I invoke it on a list of the integers from 1 to 5, I get the output '(5):
> (last-pair (list 1 2 3 4 5))
'(5)
I was expecting 5
, like how (car (list 1 2 3 4 5))
would return 1
not '(1)
.
Why do I get '(5)
and not 5
?
I'm using DrRacket 5.3.3 and Racket Scheme.
EDIT 1: MIT-Scheme does not appear to do this. last-pair
returns 5
not '(5)
. Which is correct?!?
EDIT 2: Interestingly, in DrRacket (not in MIT-Scheme), if the second line (cond ((null? (cdr alist))
is indented two spaces, when the procedure is called, it returns '(5)
. But, when the second line is not indented, it returns 5
. Is this a glitch? I believe all that Scheme interpreters are supposed to follow is parentheses, correct?
EDIT 3: I am beginning to think this is a glitch in DrRacket. When I place the procedure definition in the definitions window (typically the top editor pane), regardless of indentation, the procedure will return 5
. But, if I define it in the interface window, the indentation affects the result as described in Edit 2. (EDIT 4) regardless of the indentation also, it will return '(5)
.
< snipped prevous part with some code about differences in indentation; the problem now is just where the procedure is defined, see Edit 4 >
EDIT 4: Ok I have simplified the problem.
- In MIT-Scheme,
(last-pair (list 1 2 3 4 5))
returns5
, wherelast-pair
is defined above. Regardless of indentation. - In DrRacket, when the
last-pair
procedure is defined in the definitions window, and then I click "Run",(last-pair (list 1 2 3 4 5))
returns5
. Regardless of indentation. - In DrRacket, when the
last-pair
procedure is defined in the interface window (the REPL),(last-pair (list 1 2 3 4 5)) returns
'(5). Regardless of indentation.
Here's a screenshot:
last-pair
defined in the Racket language: docs.racket-lang.org/reference/… It is much safer to keep all your definitions in the Definitions pane, and just treat the Interactions pane as a place to explore those definitions. – dyoolast-pair
is a standard function name, and it returns a last pair, not a last element like you want it to. Maybe DrRacket refuses to redefine it, silently, when you enter the new definition at the REPL. Try the same definition with a different name, at the REPL, and tell us what happens. :) – Will Ness