Please explain lisp's multiple-value-bind - lisp

I've read the docs (several different versions!) but I can't quite get my head wrapped around multiple-value-bind.
Here's what I (think I) know:
The first parameter is a list of variables that are going to get bound.
The next parameter is a list of values that get bound to the variables.
Am I right that these 2 lists have to be the same length?
The last parameter (is it optional?) is a body of code that can act on the variables with their newly-bound values.
That sure seems to be how the docs read, and it fits with code I'm reading but not-quite following. I get into trouble when I try to create a multiple-value-bind statement from scratch, as a test. I end up with results like this:
? (mulitple-value-bind (x y z) (values 11 22 33) (+ x y z)) ;; 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 was sort of hoping for output along the lines of 66.) (I'm using Clozure-CL if it matters, though I don't think it should.)
Also, I'm looking at some sample code (trying to understand Project Euler Problem 24) that reads like this:
(multiple-value-bind
(q r)
(floor n m)
(cons (nth q lst) (permute-b r (remove-nth q lst)))
)
(NOTE: I may have mis-indented it, which may be affecting my lack of understanding)
What I don't get about this is it looks to me as if there are 2 variables being multiply-bound (q & r), but only one value (floor n m). Or is the other value the cons statement, and there is no body?!
As you can see, I completely don't get multiple-value-bind; please enlighten me.
Thanks!

Your first example with the "unbound variable" is due to your misspelling multiple-value-bind. Try fixing the spelling; you should see a different result.
As to your second question, floor returns two values, the floor and the remainder. Remember that values is not the only function that returns multiple values!
So, basically, the multiple-value-bind form looks like this:
(multiple-value-bind (var-1 .. var-n) expr
body)
where expr is an expression that returns multiple values, which are bound to the variable names given in var-1 .. var-n; those variables are available for use in body. It is okay for expr to return more or fewer values than are given as variables; nil is used as the default value for any absent values, and any excess values are discarded.

Related

Understanding `define-symbolic`

I'm reading the Rosette Essentials.
The guide explains the use of define-symbolic:
The define-symbolic form binds the variable to the same (unique) [symbolic] constant every time it is evaluated.
(define (static)
(define-symbolic x boolean?) ; Creates the same constant when evaluated.
x)
(define (dynamic)
(define-symbolic* y integer?) ; Creates a fresh constant when evaluated.
y)
> (eq? (static) (static))
#t
> (eq? (dynamic) (dynamic))
(= y$1 y$2)
Printed constant names, such as x or b, are just comments. Two [symbolic] constants created by evaluating two distinct define-symbolic (or, define-symbolic*) forms are distinct, even if they have the same printed name. They may still represent the same concrete value, but that is determined by the solver:
(define (yet-another-x)
(define-symbolic x boolean?)
x)
> (eq? (static) (yet-another-x))
(<=> x x)
I don't really understand the explanation of define-symbolic:
Why (eq? (static) (static)) returns #t, but (eq? (static) (yet-another-x)) returns (<=> x x)?
Since the define-symbolic binds the variable to the same (unique) constant every time it is evaluated, why (eq? (static) (yet-another-x)) does not return #t? , just like (eq? (static) (static))?
Does it mean that two symbolic variables occur in the different scope with the same name are still different, even if we use define-symbolic?
What's the difference between <=> and =? e.g. (<=> x x) vs (= y$1 y$2).
Thanks.
Here's an attempt to explain what the docs are saying:
It matters which use of define-symbolic two different symbolic constants come from. So the two uses inside static and yet-another-x are different uses and thus different symbolic constants.
It doesn't matter how many times you evaluate the same use of define-symbolic, it always produces the same symbolic constant. You can think of it as being hoisted out to the top-level of your program.
For define-symbolic*, it does matter when you evaluate things, so (eq? (dynamic) (dynamic)) produces a constraint that might or might not be true, depending on what the solver says and what other constraints you add.
= only works on numbers. <=> only works on booleans. In general eq? probably isn't what you want for these comparisons.
As you notice, there's something going on here with regard to the scope, which is left entirely out of the docs, unspecified, not mentioned at all. Very unfortunate; extremely vague. Few more remarks could probably go a long way toward clarifying the situation; but we're left out forced to guess.
My guess is that the form (define-symbolic x boolean?) knows something about where it appears, and acts accordingly each time it (the form) is evaluated. In
(define (static)
(define-symbolic x boolean?) ; Creates the same constant when evaluated.
x)
what is the scope of x? The only possible reading seems to me to be, that the call (define-symbolic x boolean?) creates a local binding inside static and sets it to the "symbolic constant" it (i.e. the call) creates. In normal Scheme these would still be different entities on each different invocation of static, of course. Rosette does its own thing here, evidently.
All we have is the docs (sans the sources of course), so we might as well just go by them.
As to what "symbolic constants" are, they seems closely related to Prolog's logical variables, but such that also know something about their own type (and probably more "constraints" or what have you).
So it looks like (static) becomes kind of a generator of a logical variable. It somehow knows about its internal binding, knows whether it is called for the very first time or not, and acts accordingly.
In short, just read it slowly and take it on faith. Nothing else to do, unless you're willing to study the sources.
Regarding (<=> x x) and (= y$1 y$2), these look like constraints. The guide calls them "symbolic expressions". The <=> most likely means "not equal" is described here as "the logical bi-implication of two boolean values", and the = means equality. x, x, y$1 and y$2 are printed representations of the four different symbolic constants.
Two different symbolic constants can be known (required) to be (eventually) equal, as with the second constraint; or to be not equal, as with the first.
While they (the constants) don't yet have any concrete value associated with them the constraint remains symbolic; but it can be actually checked as soon as the symbolic constant/logical variable gets its concrete value (or possibly gets more constraints associated with it, so those constraints could in theory be checked for consistency).

How to read space separated integers in racket

I looked at the documentation https://docs.racket-lang.org/reference/input-and-output.html but I find it to be very confusing and I feel like it contains a lot of extra information I don't need for such a simple task.
I would like to read two space separated integers and store them in variables.
example input:
1 2
I would like to define and x and y whose values are 1 and 2 respectively.
There are a lot of ways to do this. I’ll give you three.
Option 1: Use the built-in read
The read function reads s-expressions. Conveniently, integers are valid s-expressions, and it skips whitespace, too. This means you can just call read twice on an input port to produce two datums:
> (let ([in (open-input-string "1 2")])
(values (read in) (read in)))
1
2
This has a drawback, though: there are a lot of things that are valid s-expressions that aren’t numbers, so you might get a lot of garbage back if you’re not careful. For example:
> (let ([in (open-input-string "#f (hello world)")])
(values (read in) (read in)))
#f
'(hello world)
You’d probably need to do some post-processing to ensure what you get back is what you expect. This also won’t necessarily consume all the input, so if it’s important there’s nothing else after the numbers, you’d need to check that separately, too.
Option 2: Use a regular expression
Regular expressions are a pretty easy way to handle simple cases like this. In this example, the regexp literal #px"^(\\d+) (\\d+)$" is a simple way to express the pattern you mention in your question. You can use this to extract the numeric parts of the string:
> (regexp-match #px"^(\\d+) (\\d+)$" "1 2")
'("1 2" "1" "2")
You can combine this with string->number to get numbers out:
> (let ([matches (regexp-match #px"^(\\d+) (\\d+)$" "1 2")])
(values (string->number (second matches))
(string->number (third matches))))
1
2
This has the advantage of ensuring the input matches precisely, and it’s safe, fast, and simple. However, one downside is that it will not provide good error messages if the parsing fails, regexp-match will simply produce #f.
Option 3: Use a parser combinator library
Racket has a number of libraries designed for parsing. These can scale to parsing far more complicated things that two numbers, but they also work fine for simple situations. I will show an example using megaparsack, since it’s my library, and I like it.
You can use megaparsack to write a parser that parses two integers separated by a space:
(require data/applicative
data/monad
megaparsack
megaparsack/text)
(define 2-integers/p
(do [x <- integer/p]
(char/p #\space)
[y <- integer/p]
(pure (cons x y))))
This parser is obviously more complicated than the regexp, but it also does more, and it’s much more extensible and composable. You can use this parser to get the numbers you want:
> (parse-result! (parse-string 2-integers/p "1 2"))
'(1 . 2)
However, unlike the regular expression, it will automatically provide good error messages when a parse fails:
> (parse-result! (parse-string 2-integers/p "1 "))
string:1:1: parse error
unexpected: end of input
expected: integer

values function in Common Lisp

Is the values function in Common Lisp just syntactic sugar for packaging multiple values into a list that gets destructured by the caller?. I am asking because I thought Common Lisp supports "true" multiple value return rather than returning a tuple or a list as in other languages, such as python. Someone just told me that it's just syntactic sugar, so I would like someone to kindly explain it. To try to understand the type that is returned by the values function, I typed (type-of (values 1 2 3)), and the output was BIT. I searched in the Common Lisp reference for that and I couldn't find it mentioned in the datatypes section. Also, can anyone share some resources that suggest how the values function is implemented in Common Lisp?. Thank you.
Multiple Values in CL
The language Common lisp
is described in the ANSI standard INCITS 226-1994 (R2004) and has many
implementations.
Each can implement multiple values
as it sees fit, and they are allowed, of course, to cons up a list for them
(in fact, the Emacs Lisp compatibility layer for CL does just
that -
but it is, emphatically and intentionally, not a Common Lisp implementation).
Purpose
However, the intent of this facility is to enable passing (at least
some) multiple values without consing (i.e., without allocating
heap memory) and all CL
implementations I know of do that.
In this sense the multiple values facility is an optimization.
Of course, the implementation of this feature can be very different for
different platforms and scenarios. E.g., the first few (say, 20 -
required by the standard) are
stored in a static of thread-local vector, the next several (1000?) are
allocated on the stack, and the rest (if needed) are allocated on the
heap as a vector or list.
Usage
E.g., the function floor returns two values.
If you write
(setq a (floor 10 3))
you capture only the first one and discard the second one, you need to
write
(setf (values q r) (floor 10 3))
to capture both values. This is similar to what other
languages might express as
q,r = floor(10,3)
using tuples, except that CL does
not allocate memory to pass (just a few) multiple values, and the
other languages often do.
IOW, one can think of multiple values as an ephemeral struct.
Note that CL can convert multiple values to lists:
(destructuring-bind (q r) (multiple-value-list (floor 10 3))
; use q & r here
...)
instead of the more efficient and concise
(multiple-value-bind (q r) (floor 10 3)
; use q & r here
...)
MV & type
CL does not have a special type for the "multiple value object"
exactly because it does not allocate a separate object to pass
around multiple values. In this sense one can, indeed, claim that
values is syntactic sugar.
However, in CL one can declare a
function type returning
multiple values:
(declaim (ftype (real &optional real) (values real real)) floor)
This means that floor returns two values, both
reals (as opposed to returning
a value of type (values real real)), i.e., in this case one might
claim abuse of notation.
Your case
In your specific case, type-of
is an ordinary function (i.e., not a macro or special operator).
You pass it a single object, 1, because, unless you are using
multiple-value-bind and
friends, only the first value is used, so
(type-of (values 1 2 3))
is identical to
(type-of 1)
and type of 1 is bit.
PS: Control return values
One use of values is to
control the return values of a function.
Normally a CL function's return values are those of the last form.
Sometimes it is not desirable, e.g., the last form return multiple
values and you want your function to return one value (or none,
like void in C):
(defun 2values (x y)
(floor y x))
(defun 1value (x y)
(values (floor y x)))
(defun no-values (x)
(print x)
(values))
The values function isn't just syntactic sugar for making a list for the caller to destructure.
For one, if the caller expects only a single value, it will get only one value (the first), not a list, from a form that returns multiple values. Since type-of takes only one value as an argument, it is giving you the type of the first value, 1. 1 is of type BIT.
Each Common Lisp implementation is free to pursue its own strategy for implementing multiple values. I learned a lot from what Frode Fjeld wrote about how his implementation, Movitz, handles it in The Movitz development platform, section 2.5.
If you make a CL implementation you could implement it with lists as long as it coheres to the spec. You need to handle one value specific and you need some way to tag zero, 2..n values and the other functions need to understand that format and print can be made to display it the same way as in other makes.
Most likely values and its sister functions is an optimization where the implementations use the stack instead of consing the values to a list structure just to get it destructured in the next level. In the olden times where RAM and CPU was not to be wasted it was very important, but I doubt you'll notice real trouble should you use destructuring-bind instead of multiple-value-bind today.
Common Lisp differs from Scheme a great deal in the positive direction that you can make a function, eg. floor where in it's calculations end up with the remainder in addition to the quotient answer, return all values at the same time but you are allowed to use it as if it only returned the very first value. I really miss that sometimes when writing Scheme since it demands you have a call-with-values that is similar to multiple-value-call or syntactic sugar like let-values to handle all the returned values that again makes you end up with making three versions in case you only need just one of the values.

Evaluating arguments of Clojure tagged literals

I have been trying to use Clojure tagged literals, and noticed that the reader does not evaluate the arguments, very much like a macro. This makes sense, but what is the appropriate solution for doing this? Explicit eval?
Example: given this function
(defn my-data
([[arg]]
(prn (symbol? arg))
:ok))
and this definition data_readers.clj
{myns/my-data my.ns/my-data}
The following behave differently:
> (let [x 1] (my.ns/my-data [x]))
false
:ok
So the x passed in is evaluated before being passed into my-data. On the other hand:
> (let [x 1] #myns/my-data [x])
true
:ok
So if I want to use the value of x inside my-data, the my-data function needs to do something about it, namely check that x is a symbol, and if so, use (eval x). That seems ugly. Is there a better approach?
Summary
There is no way to get at the value of the local x in your example, primarily because locals only get assigned values at runtime, whereas tagged literals are handled at read time. (There's also compile time in between; it is impossible to get at locals' values at compile time; therefore macros cannot get at locals' values either.)1
The better approach is to use a regular function at runtime, since after all you want to construct a value based on the runtime values of some parameters. Tagged literals really are literals and should be used as such.
Extended discussion
To illustrate the issue described above:
(binding [*data-readers* {'bar (fn [_] (java.util.Date.))}]
(eval (read-string "(defn foo [] #bar x)")))
foo will always return the same value, because the reader has only one opportunity to return a value for #bar x which is then baked into foo's bytecode.
Notice also that instead of passing it to eval directly, we could store the data structure returned by the call to read-string and compile it at an arbitrary point in the future; the value returned by foo would remain the same. Clearly there's no way for such a literal value to depend on the future values of any locals; in fact, during the reader's operation, it is not even clear which symbols will come to name locals -- that's for the compiler to determine and the result of that determination may be non-obvious in cases where macros are involved.
Of course the reader is free to return a form which looks like a function call, the name of a local etc. To show one example:
(binding [*data-readers* {'bar (fn [sym] (list sym 1 2 3 4 5))}]
(eval (read-string "#bar *")))
;= 120
;; substituting + for * in the string yields a value of 15
Here #bar f becomes equivalent to (f 1 2 3 4 5). Needless to say, this is an abuse of notation and doesn't really do what you asked for.
1 It's worth pointing out that eval has no access to locals (it always operates in the global scope), but the issue with locals not having values assigned before runtime is more fundamental.

Apply-recur macro in Clojure

I'm not very familiar with Clojure/Lisp macros. I would like to write apply-recur macro which would have same meaning as (apply recur ...)
I guess there is no real need for such macro but I think it's a good exercise. So I'm asking for your solution.
Well, there really is no need for that, if only because recur cannot take varargs (a recur to the top of the function takes a single final seqable argument grouping all arguments pass the last required argument). This doesn't affect the validity of the exercise, of course.
However, there is a problem in that a "proper" apply-recur should presumably handle argument seqs returned by arbitrary expressions and not only literals:
;; this should work...
(apply-recur [1 2 3])
;; ...and this should have the same effect...
(apply-recur (vector 1 2 3))
;; ...as should this, if (foo) returns [1 2 3]
(apply-recur (foo))
However, the value of an arbitrary expression such as (foo) is simply not available, in general, at macro expansion time. (Perhaps (vector 1 2 3) might be assumed to always yield the same value, but foo might mean different things at different times (one reason eval wouldn't work), be a let-bound local rather than a Var (another reason eval wouldn't work) etc.)
Thus to write a fully general apply-recur, we would need to be able to determine how many arguments a regular recur form would expect and have (apply-recur some-expression) expand to something like
(let [seval# some-expression]
(recur (nth seval# 0)
(nth seval# 1)
...
(nth seval# n-1))) ; n-1 being the number of the final parameter
(The final nth might need to be nthnext if we're dealing with varargs, which presents a problem similar to what is described in the next paragraph. Also, it would be a good idea to add an assertion to check the length of the seqable returned by some-expression.)
I am not aware of any method to determine the proper arity of a recur at a particular spot in the code at macro-expansion time. That does not mean one isn't available -- that's something the compiler needs to know anyway, so perhaps there is a way to extract that information from its internals. Even so, any method for doing that would almost certainly need to rely on implementation details which might change in the future.
Thus the conclusion is this: even if it is at all possible to write such a macro (which might not even be the case), it is likely that any implementation would be very fragile.
As a final remark, writing an apply-recur which would only be capable of dealing with literals (actually the general structure of the arg seq would need to be given as a literal; the arguments themselves -- not necessarily, so this could work: (apply-recur [foo bar baz]) => (recur foo bar baz)) would be fairly simple. I'm not spoiling the exercise by giving away the solution, but, as a hint, consider using ~#.
apply is a function that takes another function as an argument. recur is a special form, not a function, so it cannot be passed to apply.