Coder
Coder

Reputation: 23

why does this do times lisp loop giving me issues?

Am trying to implement the function element I that return the i-th element of the list.car of the list is element 0,1 etc and I'm trying to use the dotimes loop together with the pop function and I keep getting errors

(defun element-i (y L)
;; (setq m )
  (let ((m ( cdr L));;(return car L))
    (dotimes(m (cdr L) t)
      (if (equal y 0) (return car L)
     (pop car L)
       (setq i (+ m L)))))))

Upvotes: 1

Views: 148

Answers (1)

Leo
Leo

Reputation: 1934

You have a number of issues here. First, you are using a parameter y but inside the function you call it i. Further L is a list, so (+ m L) will signal an error. On the other hand, I think you intend to use m as an integer, but you initialize it as (cdr L) which is a list. Also, the function pop modifies the list L, but it's much easier to use a variable to point at the next element of the list, without modifying the list, simply by saying (setq m (cdr m)).
You can rewrite the function in a simpler way, thinking along these lines: take a variable m and initialize it to L. Loop i times through the list, making each time m equal to (cdr m), i.e. the same list minus the first element of the previous loop. Once you exit the loop m will be the sublist whose car is the i-th element of L.

Upvotes: 4

Related Questions