Explain lisp multiple-value-bind

I read the docs (several different versions!), But I can't get my head wrapped around multiple-value-bind .

Here is what I (I think) know:

  • The first parameter is a list of variables that you are going to receive.
  • The next parameter is a list of values ​​that are bound to variables.
    • Is it right that these 2 lists should be the same length?
  • The last parameter (optional?) Is the body of the code, which can act on variables with their new values.

Of course, it seems like the documents are reading, and this corresponds to the code that I am reading, but not quite following. I am having problems when I try to create a multiple-value-bind statement from scratch, as a test. I get the following results:

 ? (mulitple-value-bind (xyz) (values 11 22 33) (+ xyz)) ;; EDIT: contains typo > Error: Unbound variable: Y > While executing: CCL::CHEAP-EVAL-IN-ENVIRONMENT, in process Listener(7). > Type cmd-/ to continue, cmd-. to abort, cmd-\ for a list of available restarts. > If continued: Retry getting the value of Y. > Type :? for other options. 1 > 

(I kind of hoped for output along lines 66 ) (I use Clozure-CL if that matters, although I don't think it should be.)

Also, I am looking at sample code (trying to understand Project Euler Problem 24 ), which reads as follows:

 (multiple-value-bind (qr) (floor nm) (cons (nth q lst) (permute-b r (remove-nth q lst))) ) 

(NOTE: I may have been mistaken, which may affect my lack of understanding)

What I do not understand about this, it looks as if the two variables were multiply connected (q and r), but only one value (floor nm) . Or another meaning is the expression cons , and there is no body ?!

As you can see, I am not completely getting multiple-value-bind ; please enlighten me.

Thanks!

+4
source share
1 answer

Your first “unbound variable” example is due to your spelling translation of multiple-value-bind . Try spelling correction; you should see a different result.

As for your second question, floor returns two values ​​- gender and remainder. Remember that values are not the only function that returns multiple values!


So basically the form of multiple-value-bind as follows:

 (multiple-value-bind (var-1 .. var-n) expr body) 

where expr is an expression that returns several values ​​that are bound to the variable names specified in var-1 .. var-n ; these variables are available for use in the body . It is normal for expr to return more or less values ​​than specified as variables; nil used as the default value for any missing values, and any redundant values ​​are discarded.

+8
source

Source: https://habr.com/ru/post/1493836/


All Articles