Sim
Sim

Reputation: 4184

Is it possible to use return-from inside a lambda function

I got a list of lists and I want to remove a certain kind of those list. Therefore I would use a remove-if-not with a lambda expression. But I might not need to go through all elements of a list to determine if it should be erased or not, as a conclusion a return-from is needed. But how can I apply one in an anonymous lambda function?

(defvar *listlist* (list (list 1 2 3) (list 3 4 5) (list 5 6 7) (list 7 8 9)))

(remove-if-not #'(lambda (arg)
                   (dolist (x arg)
                     (when (= x 3)
                       (return-from lambda t)))
                   nil)
               *listlist*)

Another thing, bothering me is the possible use of a mapcar instead of dolist, but then my problem gets even worse, as I now would have to return-from two lambda functions.

Upvotes: 2

Views: 1164

Answers (2)

Clayton Stanley
Clayton Stanley

Reputation: 7784

You can also use Graham's alambda (instead of lambda; just add the 'a' at the front), in cases where you don't happen to have a dolist block to return from:

(remove-if-not 
  (alambda (arg)
    (dolist (x arg)
      (when (= x 3)
        (return-from self t))
      nil))
  *listlist*)

This works for the general case, where you are coding away, and writing a lambda function, and then you happen to need the lambda named so that you can return-from it. At this point, just add an 'a' to the lambda, and return-from self.

Upvotes: 1

zvrba
zvrba

Reputation: 24574

dolist establishes an implicit block, so you can use return. Read more here. Also, you can wrap dolist in explicit block so you can use return-from.

Upvotes: 3

Related Questions