Вопрос

I have a function like this.

(defun foo ()
  (if (condition)
     (do-something)))

But I want to write like this to avoid unnecessary indent.

(defun foo ()
  (if not (condition) (return))
  (do-something))

Obviously return isn't caught because there is no block here.

How can I get out of the function? Or is this a bad way with lisp?

Это было полезно?

Решение

Defun creates a block named for the function name, which can be used by calling return-from.

(return-from foo (do-something))

It's not good style to use this to avoid a little indentation. Your editor should be able to do indentation automatically, and functions are usually easier to read without early returns.

Другие советы

@m-n already answered your question fully. I just want to provide an example of what 'good style' would be in this case:

(defun foo ()
  (when (condition)
    (do-something)))

In my opinion, it even does look better than

(defun foo ()
  (if (condition)
      (do-something)))

and in particular than

(defun foo ()
  (if (not (condition)) (return-from foo))
  (do-something))

(This is the indentation as my emacs with slime etc. produces it)

N.B.: Instead of (when (not (condition)) ...) use (unless (condition) ...).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top