Reputation: 27
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
Reputation: 2812
I see several small things:
loop
syntax is not 100% correct, you missed a do
keyword(loop while (< k i) do (setq k (1+ k)))
^^
do keyword is missing!
promising(2)
is also incorrect(promising 2)
return-from
thing is unusualThe 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
k
variable should be defined locally and not use a global definitionThe 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