Lisp -- let and eval not working together [duplicate] - lisp

Let's say I have a special var:
(defvar x 20)
then I do the following:
(let ((x 1)) (eval '(+ x 1))
which evaluates to 2.
According to CLHS, eval "Evaluates form in the current dynamic environment and the null lexical environment". So, I would expect to get 21 instead of 2.
Am I missing something?
Now if I have no dynamic binding for symbol y, evaluating
(let ((y 1)) (eval '(+ y 1))
I get condition: "The variable Y is unbound", which makes sense, since there is no dynamic binding for y.
Note: I'm using SBCL 1.0.57
Appreciate your help in advance!

in your example x is special which means it is bound in the dynamic environment
y is not special, so it is bound in the lexical environment
so at the time of the first eval the environments could be represented like this:
dynamic environment: { x : 1 } -> { x : 20, ...other global variables... } -> nil
lexical environment: nil
the symbol x is special so eval looks up x in the current dynamic
environment and finds x = 1
assuming it was run in same lisp as the last example, the environment of your second eval looks like this:
dynamic environment: { x : 20, ...other global variables... } -> nil
lexical environment: { y : 1 } -> nil
the symbol y is not special so eval looks up y in the null
lexical environment -- not the current lexical environment -- and finds nothing.
this makes sense when you realize that lisp is usually compiled, and the lexical
environment can be optimized down to simple mov instructions in some cases.

DEFVAR declares its variables special. Globally, everywhere. You can also not remove this easily.
That's also the reason you should never use common names like x, i, list as variable names for DEFVAR. Make sure that you use *x*, *i* and *list* instead. Otherwise all variables, even local ones, with these common names are declared special.

Related

Quote-unquote idiom in Julia & concatenating Expr objects

I'd like to write a simple macro that shows the names & values of variables. In Common Lisp it would be
(defmacro dprint (&rest vars)
`(progn
,#(loop for v in vars
collect `(format t "~a: ~a~%" ',v ,v))))
In Julia I had two problems writing this:
How can I collect the generated Expr objects into a block? (In Lisp, this is done by splicing the list with ,# into progn.) The best I could come up with is to create an Expr(:block), and set its args to the list, but this is far from elegant.
I need to use both the name and the value of the variable. Interpolation inside strings and quoted expressions both use $, which complicates the issue, but even if I use string for concatenation, I can 't print the variable's name - at least :($v) does not do the same as ',v in CL...
My current macro looks like this:
macro dprint(vars...)
ex = Expr(:block)
ex.args = [:(println(string(:($v), " = ", $v))) for v in vars]
ex
end
Looking at a macroexpansion shows the problem:
julia> macroexpand(:(#dprint x y))
quote
println(string(v," = ",x))
println(string(v," = ",y))
end
I would like to get
quote
println(string(:x," = ",x))
println(string(:y," = ",y))
end
Any hints?
EDIT: Combining the answers, the solution seems to be the following:
macro dprint(vars...)
quote
$([:(println(string($(Meta.quot(v)), " = ", $v))) for v in vars]...)
end
end
... i.e., using $(Meta.quot(v)) to the effect of ',v, and $(expr...) for ,#expr. Thank you again!
the #show macro already exists for this. It is helpful to be able to implement it yourself, so later you can do other likes like make one that will show the size of an Array..
For your particular variant:
Answer is Meta.quot,
macro dprint(vars...)
ex = Expr(:block)
ex.args = [:(println($(Meta.quot(v)), " = ", $v)) for v in vars]
ex
end
See with:
julia> a=2; b=3;
julia> #dprint a
a = 2
julia> #dprint a b
a = 2
b = 3
oxinabox's answer is good, but I should mention the equivalent to ,#x is $(x...) (this is the other part of your question).
For instance, consider the macro
macro _begin(); esc(:begin); end
macro #_begin()(args...)
quote
$(args...)
end |> esc
end
and invocation
#begin x=1 y=2 x*y
which (though dubiously readable) produces the expected result 2. (The #_begin macro is not part of the example; it is required however because begin is a reserved word, so one needs a macro to access the symbol directly.)
Note
julia> macroexpand(:(#begin 1 2 3))
quote # REPL[1], line 5:
1
2
3
end
I consider this more readable, personally, than pushing to the .args array.

Writing a macro to swap the values of two symbols

I can't think of any possible use case for this, but as an exercise to try to wrap my mind further around Clojure's macros, I'm trying to write a macro that will swap the values assigned to two symbols.
Here are two things that I tried:
Method 1:
(defmacro swap [x y]
`(let [tmp# ~x]
(def x ~y)
(def y ~tmp#)))
Method 2:
(defmacro swap [x y]
`(let [tmp# ~x]
(alter-var-root #'x (fn [] ~y))
(alter-var-root #'y (fn [] ~tmp#))))
Here is the code I use to test it:
(def four 4)
(def five 5)
(swap four five)
(printf "four: %d\nfive: %d" four five)
Expected output:
four: 5
five: 4
However, using either version of the macro, I get a java.lang.RuntimeException: Unable to resolve symbol: tmp# in this context. Am I using auto gensym incorrectly?
Using method 1, I was able to get it to run by changing the last line to (def y tmp#))) (taking out the ~ before tmp#), however I get the output four: 4\nfive: 5 which is not swapped.
Ignoring the fact that mutating vars like this is a bad idea, let's assume you really want to do it anyway. Your problem is two-fold:
You have an unquote on ~tmp#, where you just want tmp#
You're missing an unquote on x and y: you want to (def ~x ~y) and (def ~y tmp#)
The version you wrote always assigns to the vars named x and y, instead of modifying the vars provided by the user.

Two simple push functions; one permanently mutates global var, other doesn't, why?

Here are two simple functions that use push on a variable passed in:
(defun push-rest (var) (push 99 (rest var)))
and
(defun just-push (something) (push 5 something))
The first one will permanently mutate the var passed. The second does not. This is quite confusing for someone who is learning the scoping behavior of this language:
CL-USER> (defparameter something (list 1 2))
SOMETHING
CL-USER> something
(1 2)
CL-USER> (just-push something)
(5 1 2)
CL-USER> something
(1 2)
CL-USER> (push-rest something)
(99 2)
CL-USER> something
(1 99 2)
In push-rest why isn't the var's scope local to the function like in just-push, when they are both using the same function, push?
According to Peter Siebel's Practical Common Lisp, Chapter 6. Variables: This might help you a lot:
As with all Common Lisp variables, function parameters hold object references. Thus, you can assign a new value to a function parameter within the body of the function, and it will not affect the bindings created for another call to the same function. But if the object passed to a function is mutable and you change it in the function, the changes will be visible to the caller since both the caller and the callee will be referencing the same object.
And a footnote:
In compiler-writer terms Common Lisp functions are "pass-by-value." However, the values that are passed are references to objects.
(Pass by value also essentially means copy; but we aren't copying the object; we are copying the reference/pointer to the object.)
As I noted in another comment:
Lisp doesn't pass objects. Lisp passes copies of object references to functions. Or you could think of them as pointers. setf assigns a new pointer created by the function to something else. The previous pointer/binding is not touched. But if the function instead operates on this pointer, rather than setting it, then it operates on the original object the pointer points too. if you are a C++ guy, this might make much more sense for you.
You can't push on a variable passed. Lisp does not pass variables.
Lisp passes objects.
You need to understand evaluation.
(just-push something)
Lisp sees that just-push is a function.
Now it evaluates something. The value of something is a list (1 2).
Then it calls just-push with the single argument (1 2).
just-push will never see the variable, it does not care. All it gets are objects.
(defun push-rest (some-list) (push 99 (rest some-list)))
Above pushes 99 onto the rest, a cons, of the list passed. Since that cons is visible outside, the change is visible outside.
(defun just-push (something) (push 5 something))
Above pushes 5 to the list pointed to by something. Since something is not visible outside and no other change has made, that change is not visible outside.
push works differently when it's passed a symbol or list as it's second argument. Pehaps you might understand it better if you do macroexpand on the two different.
(macroexpand '(push 99 (rest var)))
;;==>
(let* ((#:g5374 99))
(let* ((#:temp-5373 var))
(let* ((#:g5375 (rest #:temp-5373)))
(system::%rplacd #:temp-5373 (cons #:g5374 #:g5375)))))
Now most of this is to not evaluate the arguments more than once so we can in this case rewrite it to:
(rplacd var (cons 99 (rest var)))
Now this mutates the cdr of var such that every binding to the same value or lists that has the same object in it's structure gets altered. Now lets try the other one:
(macroexpand '(push 5 something))
; ==>
(setq something (cons 5 something))
Here is creates a new list starting with 5 and alters the local functions binding something to that value, that in the beginning pointed to the original structure. If you have the original structure in a variable lst it won't get changed since it's a completely different binding than something. You can fix your problem with a macro:
(defmacro just-push (lst)
(if (symbolp lst)
`(push 5 ,lst)
(error "macro-argument-not-symbol")))
This only accepts variables as argument and mutates it to a new list having 5 as it's first element and the original list as it's tail. (just-push x) is just an abbreviation for (push 5 x).
Just to be clear. In an Algol dialect the equivalent code would be something like:
public class Node
{
private int value;
private Node next;
public Node(int value, Node next)
{
this.value = value;
this.next = next;
}
public static void pushRest(Node var)
{
Node n = new Node(99, var.next); // a new node with 99 and chained with the rest of var
var.next = n; // argument gets mutated to have new node as next
}
public static void justPush(Node var)
{
var = new Node(5, var); // overwrite var
System.out.print("var in justPush is: ");
var.print();
}
public void print()
{
System.out.print(String.valueOf(value) + " ");
if ( next == null )
System.out.println();
else
next.print();
}
public static void main (String[] args)
{
Node n = new Node( 10, new Node(20, null));
n.print(); // displays "10 20"
pushRest(n); // mutates list
n.print(); // displays "10 99 20"
justPush(n); // displays "var in justPush is :5 10 99 20"
n.print(); // displays "10 99 20"
}
}
(push item place)
It work as follows when the form is used to instruct the place where this is referred to in the setf:
(setf place (cons item place))
Basedon your profile, it looks like you have familiarity with C-like languages. push is a macro, and is the following equivalence is roughly true (except for the fact that this would cause x to be evaluated twice, whereas push won't):
(push x y) === (setf x (list* x y))
That's almost a C macro. Consider a similar incf macro (CL actually defines an incf, but that's not important now):
(incf x) === (setf x (+ 1 x))
In C, if you do something like
void bar( int *xs ) {
xs[0] = xs[0] + 1; /* INCF( xs[0] ) */
}
void foo( int x ) {
x = x + 1; /* INCF( x ) */
}
and have calls like
bar(zs); /* where zs[0] is 10 */
printf( "%d", zs[0] ); /* 11, not 10 */
foo(z); /* where z is 10 */
printf( "%d", z ); /* 10, not 11 */
The same thing is happening in the Lisp code. In your first code example, you're modifying contents of some structure. In your second code example, you're modifying the value of lexical variable. The first you'll see across function calls, because the structure is preserved across function calls. The second you won't see, because the lexical variable only has lexical scope.
Sometimes I wonder if Lisp aficionados (myself included) promote the idea that Lisp is different so much that we confuse people into thinking that nothing's the same.

Dynamic variables in perl

I am wondering about how I can do in Perl what I commonly do in lisp:
(defvar *verbose-level* 0)
(defun my-function (... &key ((:verbose-level *verbose-level*) *verbose-level*) ...) ...)
this means that my-function is run at the current level of verbosity, but I can pass it a different level which will affect all its calls too:
(defun f1 (&key ((:verbose-level *verbose-level*) *verbose-level*))
(format t "~S: ~S=~S~%" 'f1 '*verbose-level* *verbose-level*)
(f2 :verbose-level 1)
(format t "~S: ~S=~S~%" 'f1 '*verbose-level* *verbose-level*)
(f2 :verbose-level (1+ *verbose-level*))
(format t "~S: ~S=~S~%" 'f1 '*verbose-level* *verbose-level*))
(defun f2 (&key ((:verbose-level *verbose-level*) *verbose-level*))
(format t "~S: ~S=~S~%" 'f2 '*verbose-level* *verbose-level*))
[17]> (f1)
F1: *VERBOSE-LEVEL*=0
F2: *VERBOSE-LEVEL*=1
F1: *VERBOSE-LEVEL*=0
F2: *VERBOSE-LEVEL*=1
F1: *VERBOSE-LEVEL*=0
NIL
[18]> (f1 :verbose-level 4)
F1: *VERBOSE-LEVEL*=4
F2: *VERBOSE-LEVEL*=1
F1: *VERBOSE-LEVEL*=4
F2: *VERBOSE-LEVEL*=5
F1: *VERBOSE-LEVEL*=4
(note that the variable bindings are restored on exit - even abnormal - from functions).
How can I do something like that in Perl?
E.g., in misc.pm, I have our $verbose=0;.
How do I write a function which would bind $verbose to a value of its argument and restore its value on return?
Perl's concept of global variables is quite similar to special variables in CL.
You can “shadow” the value of a global variable with local:
our $var = 1;
func("before");
{
# a block creates a new scope
local $var = 2;
func("inside");
}
func("after");
sub func { say "#_: $var" }
Output:
before: 1
inside: 2
after: 1
If you local a value, the new value is visible throughout the whole dynamic scope, i.e. in all functions that are called. The old value is restored once the lexical scope is left by any means (errors, returns, etc). Tail calls do not extend the dynamic scope, but count as scope exit.
Note that global variables have a fully qualified name. From a different package, you would do something like
local $Other::Package::var = 3;
Other::Package::func("from a package far, far away");
This is commonly used to provide configuration for packages with a functional (non-OO) interface. Important examples are
Carp
and
Data::Dumper.
If I understand you correctly, you need to locally override a global variable inside a function.
package my_package;
our $verbose = 0;
sub function {
my ($arg1, $arg2) = #_; # getting function arguments.
local $verbose = $arg1;
}
It will restore old state of $verbose on return.

Calling a Clojure function with string inside swap?

The macro, transform!, as defined below seems to work for => (transform! ["foo" 1 2 3]). The purpose is to take in a list, with the first element being a string that represents a function in the namespace. Then wrapping everything into swap!.
The problem is that transform! doesn't work for => (transform! coll), where (def coll ["foo" 1 2 3]). I am getting this mystery exception:
#<UnsupportedOperationException java.lang.UnsupportedOperationException: nth not supported on this type: Symbol>
The function:
(defmacro transform!
" Takes string input and update data with corresponding command function.
"
[[f & args]] ;; note double brackets
`(swap! *image* ~(ns-resolve *ns* (symbol f)) ~#args))
I find it strange that it works for one case and not the other.
Macros work at compile-time and operate on code, not on runtime data. In the case of (transform! coll), the macro is being passed a single, unevaluated argument: the symbol coll.
You don't actually need a macro; a regular function will suffice:
(defn transform! [[f & args]]
(apply swap! *image* (resolve (symbol f)) args)))
Resolving vars at runtime could be considered a code smell, so think about whether you really need to do it.
You're passing a symbol to the macro, namely coll. It will try to pull that symbol apart according to the destructuring statement [f & args], which won't be possible of course.
You can also use (resolve symbol) instead of (ns-resolve *ns* symbol).