Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutiple value bind in do loop in Common Lisp

Tags:

common-lisp

How do you bind multiple values returned from a function, inside a do loop? The following is obviously very wrong, but is something like this possible?

(do (((x y z) (3-val-fn) (3-val-fn)))
    ((equal y 'some-val) y)
    (values x y z))

Or maybe there is a way to do this using multiple-value-bind?

like image 730
Capstone Avatar asked Jan 13 '17 06:01

Capstone


People also ask

Do loops Lisp?

The loop for construct allows you to implement a for-loop like iteration as most common in other languages. The do construct is also used for performing iteration using LISP. It provides a structured form of iteration. The dotimes construct allows looping for some fixed number of iterations.

What are multiple values?

multiple-value-call first evaluates function to obtain a function and then evaluates all of the forms. All the values of the forms are gathered together (not just one value from each) and are all given as arguments to the function. The result of multiple-value-call is whatever is returned by the function.

How do you stop a loop in a lisp?

Use loop-finish to provide a normal exit from a nested condition inside a loop. You can use loop-finish inside nested Lisp code to provide a normal exit from a loop.


1 Answers

Multiple values in the standard iteration constructs is not really supported.

With LOOP your snippet might look like this:

(loop with x and y and z
      do (setf (values x y z) (3-val-fn))
      while (equal y 'some-val)
      finally (return y)
      do ...)

If I would need something like that often, I might define a do-mv macro which would expand into above code. Code then would look like:

(do-mv ((x y z) (3-val-fn))
       ((equal y 'some-val) y)
  ...)

The advantage to use above is that it does not create lists from multiple values during each iteration. Creating lists out of multiple values kind of defeats the purpose of multiple values, which are there to return more than one values and allowing it to be implemented in an efficient way.

like image 160
Rainer Joswig Avatar answered Sep 29 '22 07:09

Rainer Joswig