0

I'm looking for help in writing a function that returns a list of the first 15 cubes. Here's what I have so far, and I'm getting a stack overflow:

(defun cubes (dec lst) ;takes a number and a list as params
   (if (= dec 0) lst ;if dec is 0 return the list
       (cons (threes (- dec 1) lst))) ;;else decrement and call it again
)

I am calling it with the following code:

(cubes 15 nil) ;should print first 15 cubes

I just started on LISP today. Thanks for the help!

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
Domn Werner
  • 572
  • 2
  • 10
  • 20

2 Answers2

2

Yeah, your function has a slight issue with it: :-)

  1. You're recursing into threes instead of cubes.
  2. You're trying to call cons with one argument (it requires two).
  3. You're not changing the value of lst in the recursion, so, since the base case returns lst, you'll always get the initial lst value you passed in.

Here's a fixed version:

(defun cubes (dec lst)
  (if (zerop dec)
      lst
      (cubes (1- dec) (cons (* dec dec dec) lst))))
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
1

You can also make use of the loop facility, and you SHOULD check if the initial value of dec is positive, otherwise you may end up with infinite loop/recursion:

(defun cubes (dec lst)
       (append
          (when (plusp dec)
                (loop for i from 1 to dec collect (expt i 3)))
          lst))
tonso
  • 1,760
  • 1
  • 11
  • 19
  • You don't need `lst`, `append`, `when`. – Svante Jan 27 '15 at 15:13
  • I mean: `(defun cubes (n) (when (plusp n) (loop :for i :from 1 :to n :collect (expt i 3))))`. – Svante Jan 27 '15 at 16:36
  • That's right, but the author's function took an integer and a list, so suggested variants should as well. – tonso Jan 27 '15 at 17:50
  • `(defun cubes (n list) (declare (ignore list)) (when (plusp n) (loop :for i :from 1 :to n :collect (expt i 3))))` – Svante Jan 27 '15 at 18:35
  • 1
    The author's variant conses cubes to the list given as the second parameter, while yours just ignores it. When I wrote my variant, I took into account what the original variant actually did. – tonso Jan 27 '15 at 21:40
  • Chill out, guys. They both helped me learn a ton! Job well done, guys. – Domn Werner Jan 27 '15 at 23:26