Better don't use the built-in name last-pair
. I suggest using something more descriptive of what you expect, like last-elem
for example.
When renaming your function, be sure to rename it throughout; i.e. change the name of the function not only at the definition site, but also at each call site, including of course inside its body, where it gets called recursively. Renaming must be performed diligently, it is very easy to introduce new errors otherwise.
About the strange behaviour at the REPL. My guess is, when you entered
(define (last-pair alist) ;; definition
(cond ((null? (cdr alist))
(car alist))
(else
(last-pair (cdr alist))))) ;; call
at the REPL, the last-pair
at the call site still referred to the built-in definition from the "outer" environment, so this call wasn't recursive. If that is the case, REPL did redefine the built-in, it's just that the call wasn't recursive.
I'd expect making an internal definition with explicit letrec
should fix it, even when entered at the REPL:
(define (last-pair alist)
(letrec ((last-pair (lambda (alist) ;; internal definition
(cond ((null? (cdr alist))
(car alist))
(else
(last-pair (cdr alist))))))) ;; recursive call
(last-pair alist))) ;; first call
because the first call now calls into the recursive internal version explicitly, being inside the letrec
form. Or maybe it'll get screwed somehow too, but I'd be really surprised if it did. :) Translating define
s without internal definitions as simple lambda
forms is one thing; messing inside the explicit letrec
is quite another.
If this indeed works it'll mean that the Racket REPL translates simple definitions like (define (f x) ...body...)
as simple lambda
forms, (define f (lambda(x) ...body...))
, not as letrec
forms, (define f (letrec ((f (lambda(x) ...body...))) f))
. And also, that define
at the Racket REPL does not alter the old binding in the global environment, but adds a new binding into it on top of the old, shadowing the old binding.
This suggests yet another way to "fix it" at the REPL — with set!
:
> (define f #f)
> (set! f (lambda(x) ...body...)) ; alter the old binding explicitly
> (f x)