Variable bindings in elisp - emacs

the elisp program
(defun test (ee) (symbol-value ee))
(setq e 1.1)
(test 'e)
its result is
1.1
then change the 'ee' in test to 'e',
(defun test (e) (symbol-value e))
(setq e 1.1)
(test 'e)
its result is
e
Why are there different results?

The formal parameter e is bound to the symbol e, which is passed as argument. With lexical binding turned off, when (symbol-value e) is evaluated, the value of formal parameter e is the symbol e, which is returned. IOW, there is confusion (variable capture) between the symbol passed as argument and the variable bound by the function.
If you use a different symbol, such as ee, as argument, then there is no variable capture.
This is a prime example of why dynamic binding can be confusing.

Related

What is the difference between #\ , ' and #'?

In Common Lisp, given that "a" is simply a character, what is the difference between #\a, 'a #'a?
My question comes from the tutorialspoint.com tutorial on Lisp. At one point the tutorial introduces:
; a character array with all initial elements set to a
; is a string actually
(write(make-array 10 :element-type 'character :initial-element #\a))
(terpri)
; a two dimensional array with initial values a
(setq myarray (make-array '(2 2) :initial-element 'a :adjustable t))
(write myarray)
(terpri)
With the output:
"aaaaaaaaaa"
#2A((A A) (A A))
#' is not included in this example but I'm including it in the question because it can be confusing as well. 🙂
Thank you very much! 😊
To start, a is not "simply a character." The Lisp reader parses #\a as the character literal a, which is an object in Common Lisp. Note that #\a and #\A are different character objects.
When the Lisp reader encounters a single quote, the expression following the single quote is not evaluated. Specifically, 'a is treated as (quote a), where quote returns its argument unevaluated. Now, a is a symbol, so 'a evaluates to that symbol. But the Lisp reader upcases most characters it reads by default, so 'a really evaluates to the symbol A. The good news is that whether you type a or A, the Lisp reader will read A (unless you mess with the readtable), and both 'a and 'A evaluate to the symbol A.
When the Lisp reader encounters #'a, the entire expression is treated as (function a), which when evaluated returns the function associated with the name a. But, note that it is an error to use function, and by extension #', on an identifier that does not denote a function.
To clarify this last part a bit, consider the following REPL interaction:
CL-USER> (defvar a 1)
A
CL-USER> a
1
CL-USER> #'a
The function COMMON-LISP-USER::A is undefined.
[Condition of type UNDEFINED-FUNCTION]
Here the variable a is defined and given the value 1, but when we try to access the function denoted by a we get an error message because there is no such function. Continuing:
; Evaluation aborted on #<UNDEFINED-FUNCTION A {1002DDC303}>.
CL-USER> (defun a (x) x)
A
CL-USER> (a 'b)
B
CL-USER> a
1
CL-USER> #'a
#<FUNCTION A>
Now we have defined a function named a that simply returns its argument. You can see that when we call a with an argument 'b we get the expected result: (a 'b) --> b. But, then when we evaluate a alone we still get 1. Symbols in Common Lisp are objects that have, among other cells, value cells and function cells. After the above interaction, the symbol a now has 1 in its value cell, and it has the function we have defined in its function cell. When the symbol a is evaluated the value cell is accessed, but when (function a) or #'a is evaluated, the function cell is accessed. You can see above that when #'a is evaluated, the function we defined is returned, and the REPL prints #<FUNCTION A> to show this.
As an aside, I wouldn't recommend using Tutorialspoint to learn Common Lisp. Glancing over the site, right away I see this:
LISP expressions are case-insensitive, cos 45 or COS 45 are same.
This is just wrong. And, Lisp is not written in all-caps. None of this inspires faith. Instead, find a good book. There are some recommendations on the common-lisp tag-info page.
#\
This is to introduce a character.
CL-USER> #\a
#\a
CL-USER> (character 'a)
#\A
CL-USER> (character "a")
#\a
'
This is quote, to quote and not evaluate things and construct object literals.
CL-USER> a
=> error: the variable a is unbound.
CL-USER> 'a
A
CL-USER> (inspect 'a)
The object is a SYMBOL.
0. Name: "A"
1. Package: #<PACKAGE "COMMON-LISP-USER">
2. Value: "unbound"
3. Function: "unbound"
4. Plist: NIL
> q
CL-USER> (equal (list 1 2) (quote (1 2))) ;; aka '(1 2)
T ;; but watch out with object literals constructed with quote, prefer constructor functions.
and #'
This is sharpsign-quote to reference a function.
CL-USER> #'a
=> error: The function COMMON-LISP-USER::A is undefined.
CL-USER> (defun a () (print "hello A"))
A
CL-USER> (a)
"hello A"
"hello A"
CL-USER> #'a
#<FUNCTION A>
CL-USER> (function a)
#<FUNCTION A>
One can ask Lisp to describe the data objects you've mentioned.
If we look at the expressions:
CL-USER 13 > (dolist (object (list '#\a ''a '#'a))
(terpri)
(describe object)
(terpri))
#\a is a CHARACTER
Name "Latin-Small-Letter-A"
Code 97
(QUOTE A) is a LIST
0 QUOTE
1 A
(FUNCTION A) is a LIST
0 FUNCTION
1 A
NIL
If we look at the evaluated expressions:
CL-USER 5 > (dolist (object (list #\a 'a #'a))
(terpri)
(describe object)
(terpri))
#\a is a CHARACTER
Name "Latin-Small-Letter-A"
Code 97
A is a SYMBOL
NAME "A"
VALUE #<unbound value>
FUNCTION #<interpreted function A 422005BD54>
PLIST NIL
PACKAGE #<The COMMON-LISP-USER package, 73/256 internal, 0/4 external>
#<interpreted function A 422005BD54> is a TYPE::INTERPRETED-FUNCTION
CODE (LAMBDA (B)
A)

Unexpected eval result in CLISP

I run following code of CLISP, but the result looks strange to me.
(setq a 'b)
(setq b 'c)
(setq c 'd)
(setq d 8)
(eval a)
(eval c)
(eval (eval a))
The output of last three line is:
C
8
D
How do I understand the output?
How could last two line have different output?
Please help explain this, thank you so much!
Evaluate (eval c)
get value of variable c -> symbol D
call EVAL with symbol D -> number 8
Evaluate (eval (eval a))
get value of variable a -> symbol B
call EVAL with symbol B -> symbol C
call EVAL with symbol C -> symbol D
Some basic evaluation rules for Lisp
a symbol evaluates to its value
a number evaluates to itself
a list (foo-function arg) evaluates first the argument and then calls the function foo-function with that evaluated argument
a list (quote something) returns something (whatever it is) as it is

How are arguments passed into functions in Elisp?

Coming from a C++ background, I'm trying to figure out how arguments are passed into methods in Elisp. While I acknowledge that maybe the wording could be different, I'm wondering if it is closer to the C++ idea of passing by reference or passing by value? If I alter the parameter in the method itself, will it alter the parameter that was passed in in the function call?
All Lisps (Emacs Lisp, Common Lisp) pass parameters by value, always:
(defparameter x 42) ; defconst in Emacs Lisp
(defun test (x)
(setq x 10))
(test x)
==> 10
x
==> 42
Note, however, that some values are actually pointers (or, rather, objects with components), so a function can modify their content by side effects:
(defparameter x (list 1 2))
(defun test (x)
(setf (first x) 42
(second x) 24
x 17))
(test x)
==> 17
x
==> (42 24)
PS1. Cf. When to use ' (or quote) in Lisp? -- "quoted arguments" are evaluated too: the evaluation strips the quote.
PS2. Cf. add-to-list - it accepts a symbol (variable name) and modifies its value. This only works for global dynamic variables, not for lexical variables. Not a very good idea.
Actually, in Emacs Lisp, there is no such thing like passing a argument by value or by reference, not to mention pointer. But all arguments passed to function will be evaluated in advance except those have a ' prefix. Always remember When you set a variable, you always just create symbol with a value.[1]
So if you want to modify a variable's value in a function, all you need to do is modifying the value of that variable's symbol in that function.
Check my code bellow.
(defvar my-val 1)
(defun my-func-value (val)
(setq val 2))
(defun my-func-symbol (sym)
;; NOTE! using set instead of setq,
;; casue we want symbol "my-val" be evaluated from "sym" here
(set sym 2))
(my-func-value my-val) ; evaluate my-val before passed into function
(message "my-val: %s" my-val) ; my-val: 1
(my-func-symbol 'my-val) ; pass my-val symbol directly into function
(message "my-val: %s" my-val) ; my-val: 2
Note! If the variable is a lexically-bound variable[2], it's still true that you can modified the symbol's value but not the value in the lexical environment.
Here is the code:
(let ((my-lexical-var 1))
(my-func-symbol 'my-lexical-var)
;; evaluate from lexical environment
(message "my-lexical-var: %s" my-lexical-var) ; my-lexical-var: 1
;; evaluate from the symbol
(message "symbol my-lexical-var: %s" (symbol-value 'my-lexical-var))
; symbol my-lexical-var: 2

in clojure language what <'a> really is

actually i am trying to perfectly understand clojure and particularly symbols
(def a 1)
(type a)
;;=>java.lang.Long
(type 'a)
;;=>clojure.lang.Symbol
I know that type is a function so its arguments get evaluated first so i perfectly understand why the code above work this way .In the flowing code i decided to delay the evaluation using macro
(defmacro m-type [x] (type x))
(m-type a)
;;==>clojure.lang.Symbol
and i am fine with that but what i fail to uderstand is this:
(m-type 'a)
;;=>clojure.lang.Cons
why the type of 'a is a cons
the character ' is interpreted by the clojure reader as a reader-macro which expands to a list containing the symbol quote followed by whatever follows the ', so in your call to (m-type 'a) the 'a is expanding to:
user> (macroexpand-1 ''a)
(quote a)
then calling type on the list (quote a) which is a Cons.
This may be a bit more clear if we make the m-type macro print the arguments as it sees them while it is evaluating:
user> (defmacro m-type [x] (println "x is " x) (type x))
#'user/m-type
user> (m-type 'a)
x is (quote a)
clojure.lang.Cons

Howto recursively call a function with a function as a parameter

From the Question How do I pass a function as a parameter to in elisp? I know how to pass a function as a parameter to a function. But we need to go deeper...
Lame movie quotes aside, I want to have a function, which takes a function as a parameter and is able to call itself [again passing the function which it took as parameter]. Consider this snippet:
(defun dummy ()
(message "Dummy"))
(defun func1 (func)
(funcall func))
(defun func2 (func arg)
(message "arg = %s" arg)
(funcall func)
(func2 'func (- arg 1)))
Calling (func1 'dummy) yields the expected output:
Dummy
"Dummy"
Calling (func2 'dummy 4) results in an error message:
arg = 4
Dummy
arg = 3
funcall: Symbol's function definition is void: func
I had expected four calls to dummy, yet the second iteration of func2 seems to have lost its knowledge of the function passed to the first iteration (and passed on from there). Any help is much appreciated!
There probably is a better way to do this with lexical scoping. This is more or less a translation from Rosetta Code:
(defun closure (y)
`(lambda (&rest args) (apply (funcall ',y ',y) args)))
(defun Y (f)
((lambda (x) (funcall x x))
`(lambda (y) (funcall ',f (closure y)))))
(defun factorial (f)
`(lambda (n)
(if (zerop n) 1
(* n (funcall ,f (1- n))))))
(funcall (Y 'factorial) 5) ;; 120
Here's a link to Rosetta code: http://rosettacode.org/wiki/Y_combinator with a bunch of other languages immplementing the same thing. Y-combinator is a construct, from the family of fixed-point combinators. Roughly, the idea is to eliminate the need for implementing recursive functions (recursive functions require more sophistications when you think about how to make them compile / implement in the VM). Y-combinator solves this by allowing one to mechanically translate all functions into non-recursive form, while still allowing for recursion in general.
To be fair, the code above isn't very good, because it will create new functions on each recursive step. This is because until recently, Emacs Lisp didn't have lexical bindings (you couldn't have a function capture its lexical environment), in other words, when the Emacs Lisp function is used outside the scope it was declared, the values of the bound variables will be taken from the function's current scope. In the case above such bound variables are f in the Y function and y in the closure function. Luckily, those are just symbols designating an existing function, so it is possible to mimic that behaviour using macros.
Now, what Y-combinator does:
Captures the original function into variable f.
Returns a wrapper function of one argument, which will call f, when called in its turn, used by Y-combinator to
Return a wrapper function of unbounded number of arguments which will
call the original function passing it all the arguments it was called with.
This structure also dictates you the structure of the function to be used with Y-combinator: it has to take single argument, which must be a function (which is this same function again) and return a function (of any number of arguments) which calls the function inherited from outer scope.
Well, it is known to be a little mind-boggling :)
That's because you're trying to call the function func not the function dummy.
(Hence the error "Symbol's function definition is void: func".)
You want:
(func2 func (- arg 1)))
not:
(func2 'func (- arg 1)))
You do not need to quote func in the func2 call
You are missing a recursion termination condition in func2
Here is what works for me:
(defun func2 (func arg)
(message "arg = %s" arg)
(funcall func)
(when (plusp arg)
(func2 func (- arg 1))))