user2976636
user2976636

Reputation: 105

A recursive function to return the nth element in lisp

I want to verify if this a recursive function? Needs to return the nth element, mine works I just want to make sure.

(defun nth2(n lst)
       (let((count 1))
           (loop
               (cond((equal count n)(return (car lst))))
               (setq count (+ count 1))
               (setq lst (cdr lst)))))

Ok. I just tried this idea. It gives me an error: Not inside a block named NIL

(defun nth2(n lst)
    (let((count 1))
      (cond((equal count n)(return (car lst)))
          (t(setq count (+ count 1))
          (nth2(count (cdr (lst))))))))

Upvotes: 1

Views: 2220

Answers (2)

uselpa
uselpa

Reputation: 18917

As I wrote in this answer, you need to avoid setq, setf and the like with recursive functions.

Instead of counting up and having to use an additional variable, you can count down. Assuming indexing starts at 0, for example:

  (nth2 2 '(a b c d e))
= (nth2 1 '(b c d e))
= (nth2 0 '(c d e))
= (car '(c d e))
= 'c

so you have to recurse down to 0 while dropping the first element, then return the first element when the index is 0:

(defun nth2 (n lst)
  (if (zerop n)
    (car lst)
    (nth2 (1- n) (cdr lst))))

Upvotes: 2

godel9
godel9

Reputation: 7390

Here's a general overview of how recursion works... Every recursive function must have:

  1. at least one base case: In base cases, the recursive function does something directly, without calling itself. A good recursive function has simple, easy-to-understand base cases. Recursive functions have base cases because the recursion has to stop somewhere.

  2. at least one recursive case: In recursive cases, the recursive function breaks a complex problem down into one or more easier problems to solve, and it does so by calling itself. The parameters used to call itself eventually need to take it closer to the base cases (e.g. using n-1 or (cdr my-list)) so that the recursion stops.

Your function doesn't have any recursive cases, so it's not a recursive function. In order to make it recursive, think about:

  1. What do I want my base case to be? What's an easy problem to solve? (Hint: It's easy to replace the value at the front of a list.)

  2. What do I want my recursive case to be? How can I make the problem look more like my base case?

Upvotes: 1

Related Questions