Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always getting "RETURN-FROM: no block named NIL is currently visible"

(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.

like image 330
pam Avatar asked Jan 30 '26 04:01

pam


1 Answers

  1. 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))
    
  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
      ...)
    
  3. (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.

  4. 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).

  5. 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.

like image 99
coredump Avatar answered Feb 02 '26 10:02

coredump



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!