Need help understanding bindings in Scheme code - variables

For the code below, I am unable to comprehend how the bindings (x, y, z) occur. Please check out the code, I'll explain my problem in greater detail below:
(define (w x)
(lambda (y z)
(begin
(set! x (+ (* y x) z)) x)))
(define f1 (w 3))
(f1 4 2)
(f1 2 1)
The output is 14, 29. These are values for x.
This means initially, x=3, y=4, z=2. In the 2nd call, i.e. (f1 2 1), x=14, y=2,z=1.
My doubts:
How does the binding occur at first, why is x=3, y=4, and z=2? If it has got to do with lambda expression in the function, please elaborate on how it works..I have a feeling this is where my understanding breaks down..
Next, why is the initial answer of x=14 retained in the second call, i.e. (f1 2 1)?
Thank you for looking into this :)

When w is run, it creates a closure out of the inner lambda. Because x came from outside of that inner lambda, x is stored inside that closure (in this case, f1).
So, f1 has a variable inside that represents x, and it starts out as 3. When you run f1, it evaluates the math and then sets its own x to be 14.
The moral is, a lambda is more than just code; it's code combined with the variables it closes over, such as this x.

Related

Are variables bounded to free variables still free variables?

I am looking at some questions in my textbook about whether or not the variables are free or bound. I am not sure about these two in particular.
First off, I want to make sure I understand the concept of free vs. bound. I am fairly sure this x is a free variable in the following:
variable x is free in expression "x"
I believe this is true but I just want to make sure.
These two questions I am not really sure about, however.
(/ (+ 1 x) (let x 2 (+ x x))),
(let x y (/ (+ 1 x) (let x 2 (+ x x))))
For the top expression, the x in the first subexpression is unbound(right?) but x in the second subexpression is bound to 2, so would that mean the x in regards to the expression as a whole is unbound?
For the bottom expression, x is bound to y, but y is a free variable(?). So would x be free because y is free or is it bound because x is still bounded to y?
For (/ (+ 1 x) (let x 2 (+ x x))), the x in the first subexpression is unbound but x in the second subexpression is bound to 2, so would that mean the x in regards to the expression as a whole is unbound?
Yes. Although I would use the terminology "is bound" or "is free" only with respect to a concrete variable expression, not to a name. As you can see, it's ambiguous what "x" refers to.
I'd say "the whole expression has a free variable x", which is what you usually care about when trying to evaluate the expression.
For (let x y (/ (+ 1 x) (let x 2 (+ x x)))), x is bound to y, but y is a free variable. So would x be free because y is free or is it bound because x is still bounded to y?
The x is bound (and can be substituted). y is free.

How to rewrite recursive procedure (repeated f n) as an iterative process using Racket?

This is what I have for recursive procedure (repeated f n) that applies the function f n times to an argument:
(define (repeated f count)
(if (= count 1)
f
(lambda (x)
(f ((repeated f (- count 1)) x)))))
E.g. ((repeated sqr 3) 2) returns 256, i.e. (sqr(sqr(sqr 2))).
But I have no idea how to implement repeated as an iterative process using Racket. Any advice is much obliged.
A typical solution for converting a recursive process to an iterative process is to enlist the aid of an accumulator.
Any way you slice it, repeated will have to return a procedure. One solution would use a named let inside the returned procedure that iterates n times, keeping track of the results in an accumulator. Here is a version of repeated that returns a unary procedure; note that there is no input validation here, so calls like ((repeated f 0) 'arg) will lead to trouble.
(define (repeated f n)
(lambda (x)
(let iter ((n n)
(acc x))
(if (= n 1) (f acc)
(iter (- n 1)
(f acc))))))
Named let expressions are very handy for things like this, but you could also define a helper procedure to do the same thing. I will leave that solution as an exercise for OP.
scratch.rkt> ((repeated sqr 3) 2)
256
scratch.rkt> ((repeated add1 8) 6)
14
I think using for/fold makes a cleaner solution
(define ((repeated f n) x)
(for/fold ([acc x]) ([i (in-range n)]) (f acc)))
Using it:
> ((repeated sqr 3) 2)
256
> ((repeated add1 8) 6)
14

Unique variable names in Z3

I need to rely on the fact that two Z3 variables
can not have the same name.
To be sure of that,
I've used tuple_example1() from test_capi.c in z3/examples/c and changed the original code from:
// some code before that ...
x = mk_real_var(ctx, "x");
y = mk_real_var(ctx, "y"); // originally y is called "y"
// some code after that ...
to:
// some code before that ...
x = mk_real_var(ctx, "x");
y = mk_real_var(ctx, "x"); // but now both x and y are called "x"
// some code after that ...
And (as expected) the output changed from:
tuple_example1
tuple_sort: (real, real)
prove: get_x(mk_pair(x, y)) = 1 implies x = 1
valid
disprove: get_x(mk_pair(x, y)) = 1 implies y = 1
invalid
counterexample:
y -> 0.0
x -> 1.0
to:
tuple_example1
tuple_sort: (real, real)
prove: get_x(mk_pair(x, y)) = 1 implies x = 1
valid
disprove: get_x(mk_pair(x, y)) = 1 implies y = 1
valid
BUG: unexpected result.
However, when I looked closer, I found out that Z3 did not really fail or anything, it is just a naive (driver) print out to console.
So I went ahead and wrote the exact same test with y being an int sort called "x".
To my surprise, Z3 could handle two variables with the same name when they have different sorts:
tuple_example1
tuple_sort: (real, real)
prove: get_x(mk_pair(x, y)) = 1 implies x = 1
valid
disprove: get_x(mk_pair(x, y)) = 1 implies y = 1
invalid
counterexample:
x -> 1.0
x -> 0
Is that really what's going on? or is it just a coincidence??
Any help is very much appreciated, thanks!
In general, SMT-Lib does allow repeated variable names, so long as they have different sorts. See page 27 of the standard. In particular, it says:
Concretely, a variable can be any symbol, while a function symbol
can be any identifier (i.e., a symbol or an indexed symbol). As a
consequence, contextual information is needed during parsing to know
whether an identifier is to be treated as a variable or a function
symbol. For variables, this information is provided by the three
binders which are the only mechanism to introduce variables. Function
symbols, in contrast, are predefined, as explained later. Recall that
every function symbol f is separately associated with one or more
ranks, each specifying the sorts of f’s arguments and result. To
simplify sort checking, a function symbol in a term can be annotated
with one of its result sorts σ. Such an annotated function symbol is a
qualified identifier of the form (as f σ).
Also on page 31 of the same document, it further clarifies "ambiguity" thusly:
Except for patterns in match expressions, every occurrence of an
ambiguous function symbol f in a term must occur as a qualified
identifier of the form (as f σ) where σ is the intended output sort of
that occurrence
So, in SMT-Lib lingo, you'd write like this:
(declare-fun x () Int)
(declare-fun x () Real)
(assert (= (as x Real) 2.5))
(assert (= (as x Int) 2))
(check-sat)
(get-model)
This produces:
sat
(model
(define-fun x () Int
2)
(define-fun x () Real
(/ 5.0 2.0))
)
What you are observing in the C-interface is essentially a rendering of the same. Of course, how much "checking" is enforced by the interface is totally solver specific as SMT-Lib says nothing about C API's or API's for other languages. That actually explains the BUG line you see in the output there. At this point, the behavior is entirely solver specific.
But long story short, SMT-Lib does indeed allow two variables have the same name used so long as they have different sorts.

While loops working mechanism of a program in Scheme

DrRacket user.
I'm struggling to understand how this program works.I wrote it myself and it does what it must but I can't understand how.
I define while loops as:
(define (while test body)
(if (test)
(begin
(body)
(while test body))
(void)))
Now I need to write a program that applies the given procedure to each element of a mutable list.
Here what I wrote:
(define (mlist-map-while f x)
(while (lambda() (not (null? x)))
(lambda ()
(set-mcar! x (f (mcar x)))
(set! x (mcdr x))))
(void))
So, defining
list1 (mlist 1 2 3)
and applying
(mlist-map-while (lambda (x) (+ x 1)) list1)
we get '(2 3 4).
The thing that I don't understand is how the first element of the list stays in it, because if it's done how I wrote here
(set! x (mcdr x))
the first procedure that sets -mcar! must be useless and be overlapped with the second. Like in this example:
(define list1 (mlist 1 2 3))
(set-mcar! list1 9)
(set-mcdr! list1 (mcdr list!))
and we lack the first element, but this program somehow leaves it in and gives the desired output. I would like to know how it works and whether there is another way of traversing the given list.
There is a big difference between set-cdr! abd set!. The first alters the pair's cdr pointer, while the latter alters the binding, thus what the name should point to.
In your mlist-map-while the variable x alters the car, then changes what x represents, to be the cdr of x. It never changes the cdr so your binding list1 always points to the first pair while x points to the first, then second, etc...
Thus it's more like this:
(define list1 (mlist 1 2 3))
(define list1-ref list1) ; variable pointing to the same value as list1
(set-mcar! list1-ref 9) ; set-car! changes the pair
(set! list1-ref (mcdr list)) ; set! updates what list1-ref points to
list1 ; ==> (9 2 3)
list-ref ; ==> (2 3)
You can iterate over a list in the same fashion without using set!, with recursion:
(define (fold function init lst)
(if (null? lst)
init
(fold function
(function (car lst) init)
(cdr lst))))
(fold + 0 '(1 2 3)
; ==> 6
(fold cons '() '(1 2 3))
; ==> (3 2 1)
Notice that here we recurse and change what lst is, to be the cdr. Every recursion has its own lst, which is not to be confused with the caller's own. It ends up doing the same as set! in your example, without mutation.

Dynamic function call in Racket; or get a procedure from a string

I apologize in advance for this likely silly question :)
Suppose, I have a list of strings like
(define func-names '("add" "sub" "mul"))
And there are also functions defined like so
(define (add x y)
(+ x y))
(define (sub x y)
(- x y))
(define (mul x y)
(* x y))
As you can see, values of the strings in the list correspond to the names of the functions.
I need a way to iterate through the list and call the function that corresponds to a string value. Something like
(define (all-ops x y)
(map (lambda (name) (string->proc name x y)) func-names))
where string->proc is what I'm looking for. Something like Ruby's send/public_send method, if you're familiar with Ruby.
I'm mostly interested in answers applicable to Racket.
Thank you.
EDIT;
And I've forgotten to mention that there may be a million of function names, so cond, match would be tedious to use here.
Consider making a hash table that maps strings to function values.
That said, you can do as follows:
#lang racket
(define (add x y)
(+ x y))
(define ns (variable-reference->namespace (#%variable-reference)))
(define (string->procedure s)
(define sym (string->symbol s))
(eval sym ns))
(string->procedure "add")
((string->procedure "add") 1 2)
See also http://blog.racket-lang.org/2011/10/on-eval-in-dynamic-languages-generally.html