(defun take-n (lst i)
(setf newlst '())
(dotimes (n i)
(setf newlst (cons (car lst) newlst))
(print (cons (car lst) newlst))
(setf lst (cdr lst)))
(return newlst))
(print (take-n '(1 2 3) 2))
This gives me an error RETURN-FROM: no block named NIL is currently visible. I have tried moving the return statement around but I am not sure what it means.
Please indent your code in a Lisp way (this can be done automatically in many editors, like Emacs):
(defun take-n (lst i)
(setf newlst '())
(dotimes (n i)
(setf newlst (cons (car lst) newlst))
(print (cons (car lst) newlst))
(setf lst (cdr lst)))
(return newlst))
(print (take-n '(1 2 3) 2))
Do not setf
a variable that was not declared beforehand: (setf newlst '())
here refers to a hypothetical global variable newlst
, but in a function you should strive to only have local state. You introduce variables in a block using let
, as follows:
(let ((new-list ()))
...
;; here you can setf new-list if you need
...)
(setf newlst (cons (car lst) newlst))
can also be written (push (car lst) newlst)
, but please do not use overly abbreviated names; you can use list
and new-list
, for example.
return
makes a return to the enclosing block named nil
, but here you have no such block. Instead, defun
introduces an implicit block named like the function you define, i.e. you have implicitly:
(block take-n
...)
So if you wanted to return from it, you would need to do (return-from take-n newlst)
.
BUT, you do not need to return since the last form being evaluated in the function is the value associated with the function call anyway.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments