Fred_2
Fred_2

Reputation: 249

LISP break a function execution

How can I break a function execution in LISP if I get a certain value?

For example, I have a main function like this:

(defun recognize-a (arg input)
    (if (equal (recognize-b arg input) '())
        T
      NIL
      ))

I want to break the function recognize-b in case the input is an empty list, without passing any values to the main function:

(defun recognize-b (fa input)
  (if (equal input '())
      <<<WANTED BREAK>>>
     (<Else branch>)))

Upvotes: 1

Views: 2260

Answers (1)

jkiiski
jkiiski

Reputation: 8411

You can use ERROR to signal an error from RECOGNIZE-B when INPUT is empty.

(defun recognize-b (arg input)
  (when (emptyp input)
    (error "INPUT is empty!"))
  ;; Do whatever the function normally does...
  :return-value-from-b)

I'll just return :RETURN-VALUE-FROM-B since I don't know what the function is supposed to do. You could define an error type to signal, but by default ERROR will signal a SIMPLE-ERROR.

To handle the error in RECOGNIZE-A, you can use HANDLER-CASE.

(defun recognize-a (arg input)
  (handler-case (recognize-b arg input)
    (simple-error () t)))

This simply returns the value from RECOGNIZE-B if there was no error, or T if there was.

(recognize-a 10 '(1 2)) ;=> :RETURN-VALUE-FROM-B
(recognize-a 10 '()) ;=> T

There is a good introduction to the condition system in the book Practical Common Lisp, Chapter 19. Beyond Exception Handling: Conditions and Restarts.

Upvotes: 6

Related Questions