I have created a function to list the numbers from min to max. It causes
a stack overflow when called with 0 and 100000 as parameters, but I know
it shouldn't. My non-tail-recursive version works fine for much larger
input!
(defun range-tr (min max)
(labels ((help (cur acc)
(cond ((>= cur max)
(nreverse acc))
(t
(help (1+ cur) (cons cur acc))))))
(help min nil)))
Lowell
In article <············@mughi.cs.ubc.ca>, Lowell <······@cs.ubc.ca>
wrote:
> I have created a function to list the numbers from min to max. It causes
> a stack overflow when called with 0 and 100000 as parameters, but I know
> it shouldn't. My non-tail-recursive version works fine for much larger
> input!
>
> (defun range-tr (min max)
> (labels ((help (cur acc)
> (cond ((>= cur max)
> (nreverse acc))
> (t
> (help (1+ cur) (cons cur acc))))))
> (help min nil)))
>
> Lowell
>
I have just checked this with Macintosh Common Lisp and it works just
fine.
Is this part of learning tail recursion? If so then this example is ok.
If not it is most probably better to write more explicit code. For
example:
(defun range-tr (min max)
(loop for i from min to mox
collect i))
If you don't like the loop facility, try the collecting macros at http://www.tfeb.org/lisp/hax.html#COLLECTING
Pascal
+ Lowell <······@cs.ubc.ca>:
| I have created a function to list the numbers from min to max. It
| causes a stack overflow when called with 0 and 100000 as parameters,
| but I know it shouldn't.
I don't know why you think you know this, but you know wrong.
| My non-tail-recursive version works fine for
| much larger input!
|
| (defun range-tr (min max)
| (labels ((help (cur acc)
| (cond ((>= cur max)
| (nreverse acc))
| (t
| (help (1+ cur) (cons cur acc))))))
| (help min nil)))
There is no requirement in the CL spec that tail calls should be
optimized away. Some implementations do, others don't, and some may
let you turn this on or off at will. Check the documentation for your
implementation for the details.
--
* Harald Hanche-Olsen <URL:http://www.math.ntnu.no/~hanche/>
- Debating gives most of us much more psychological satisfaction
than thinking does: but it deprives us of whatever chance there is
of getting closer to the truth. -- C.P. Snow