Eugene
Eugene

Reputation: 27

Syntax Error in Lisp Loop for defining variables in a loop

I am a beginner student who is learning Lisp. I want to turn the loop to the i value using k using the loop statement, but the following error appears. I think I wrote the parentheses correctly, but I don't know why this error occurs.

 LOOP: illegal syntax near (SETQ K (1+ K)) in
      (LOOP WHILE (< K I) (SETQ K (1+ K)))

Below is my code.

(DEFUN promising (i)
    (setq k 1)
    (loop while (< k i) (setq k (1+ k)))
    (return-from promising 1)
 )

promising(2)

Upvotes: 0

Views: 57

Answers (1)

Robert
Robert

Reputation: 2812

I see several small things:

  1. The loop syntax is not 100% correct, you missed a do keyword
(loop while (< k i) do (setq k (1+ k)))
                    ^^
                    do keyword is missing!
  1. The syntax for the function call promising(2) is also incorrect
(promising 2)
  1. The return-from thing is unusual

The first reason is that the return value is always 1, in your case, you probably want to return k.

(DEFUN promising (i)
    (setq k 1)
    (loop while (< k i) (setq k (1+ k)))
    (return-from promising 1))
                           ^
                           Always return 1

The second reason is you don't need a return-from, the last value of a defun form will be given to the function caller.

(DEFUN promising (i)
    (setq k 1)
    (loop while (< k i) do (setq k (1+ k)))
    k)
    ^
    The last value will be returned to the function caller
  1. The k variable should be defined locally and not use a global definition

The final code could be something like this:

(defun promising (i)
  (let ((k 1))
    (loop while (< k i) do (setq k (1+ k)))
    ;; return value
    k))

(promising 2)

This should return:

2

Upvotes: 1

Related Questions