I am hoping someone can explain why tests 1-5 work but test 6 does not. I thought that quoting a lambda with ' and using #' in front of a lambda both returned pointers to the function with the only difference being that the #' will compile it first.
(defun test-1 (y)
(mapcar (lambda (x) (expt x 2))
'(1 2 3)))
(defun test-2 (y)
(mapcar (lambda (x) (expt x y))
'(1 2 3)))
(defun test-3 (y)
(mapcar #'(lambda (x) (expt x 2))
'(1 2 3)))
(defun test-4 (y)
(mapcar #'(lambda (x) (expt x y))
'(1 2 3)))
(defun test-5 (y)
(mapcar '(lambda (x) (expt x 2))
'(1 2 3)))
(defun test-6 (y)
(mapcar '(lambda (x) (expt x y))
'(1 2 3)))
I am using the free version of Franz Industries Allegro Common Lisp. The following are the outputs:
(test-1 2) ; --> (1 4 9)
(test-2 2) ; --> (1 4 9)
(test-3 2) ; --> (1 4 9)
(test-4 2) ; --> (1 4 9)
(test-5 2) ; --> (1 4 9)
(test-6 2) ; --> Error: Attempt to take the value of the unbound variable `Y'. [condition type: UNBOUND-VARIABLE]
For a start, you should be aware that your tests 1-4 are conforming Common Lisp, while your tests 5 and 6 are not. I believe Allegro is perfectly well allowed to do what it does for 5 and 6, but what it is doing is outside the standard. The bit of the standard that talks about this is the definition of functions like mapcar, which take function designators as argument, and the definition of a function designator:
function designator n. a designator for a function; that is, an object that denotes a function and that is one of: a symbol (denoting the function named by that symbol in the global environment), or a function (denoting itself). The consequences are undefined if a symbol is used as a function designator but it does not have a global definition as a function, or it has a global definition as a macro or a special form. [...]
From this it is clear that a list like (lambda (...) ...) is not a function designator: it's just a list whose car happens to be lambda. What Allegro is doing is noticing that this list is in fact something that can be turned into a function and doing that.
Well, let's just write a version of mapcar which does what Allegro's does:
(defun mapcar/coercing (maybe-f &rest lists)
(apply #'mapcar (coerce maybe-f 'function) lists))
This just uses coerce which is a function which knows how to turn lists like this into functions, among other things. If its argument is already a function, coerce just returns it.
Now we can write the two tests using this function:
(defun test-5/coercing (y)
(mapcar/coercing '(lambda (x) (expt x 2))
'(1 2 3)))
(defun test-6/coercing (y)
(mapcar/coercing '(lambda (x) (expt x y))
'(1 2 3)))
So, after that preamble, why can't test-6/explicit work? Well the answer is that Common Lisp is (except for for special variables) lexically scoped. Lexical scope is just a fancy way of saying that the bindings (variables) that are available are exactly and only the bindings you can see by looking at the source of the program. (Except, in the case of CL for special bindings, which I'll ignore, since there are none here.)
So, given this, think about test-6/coercing, and in particular the call to mapcar/coercing: in that call, coerce has to turn the list (lambda (x) (expt z y)) into a function. So it does that. But the function it returns doesn't bind y and there is no binding for y visible in it: the function uses y 'free'.
The only way that this could work is if the function that coerce constructs for us were to dynamically look for a binding for y. Well, that's what dynamically-scoped languages do, but CL is not dynamically-scoped.
Perhaps a way of making this even clearer is to realise that we can lift the function creation right out of the function:
(defun test-7 (y f)
(mapcar f '(1 2 3)))
> (test-7 1 (coerce '(lambda (x) (expt x y)) 'function))
It's clear that this can't work in a lexically-scoped language.
So, then, how do tests 1-4 work?
Well, firstly there are only actually two tests here. In CL, lambda is a macro and (lambda (...) ...) is entirely equivalent to (function (lambda (...) ...)). And of course #'(lambda (...) ...) is also the same as (function (lambda (...) ...)): it's just a read-macro for it.
And (function ...) is a magic thing (a special form) which says 'this is a function'. The important thing about function is that it's not a function: it's a deeply magic thing which tells the evaluator (or the compiler) that its argument is the description of a function in the current lexical context, so, for instance in
(let ((x 1))
(function (lambda (y) (+ x y))))
The x referred to by the function this creates is the x bound by let. So in your tests 2 and 4 (which are the same):
(defun test-4 (y)
(mapcar (function (lambda (x) (expt x y)))
'(1 2 3)))
The binding of y which the function created refers to is the binding of y which is lexically visible, which is the argument of test-4 itself.
Let's add a y parameter to avoid closing over variables and see what kind of values we are manipulating:
USER> (type-of #'(lambda (x y) (expt x y)))
FUNCTION
USER> (type-of (lambda (x y) (expt x y)))
FUNCTION
USER> (type-of '(lambda (x y) (expt x y)))
CONS
As you can see, the two first lambda-like forms are evaluated as functions, while the third is evaluated as a cons-cell. As far as Lisp is concerned, the third argument is just a tree of symbols with no meaning.
Reader macros
I thought that quoting a lambda with ' and using #' in front of a lambda both returned pointers to the function with the only difference being that the #' will compile it first.
Let's go back to the definitions, ' and #' are reader macros, respectively Single-Quote and Sharpsign Single-Quote. They are found in front of other forms, for example 'f is read as (quote f) and #'f is read as (function f). At read-time, f and the resulting forms are just unevaluated data.
We will see below how both special operators are interpreted, but what matters really is the lexical scope, so let's open a parenthesis.
Lexical environment
Lexical environments are the set of bindings in effect at some point of your code. When you evaluate a let or an flet it enriches the current environment with new bindings. When you call EVAL on an expression, you start evaluating from a null lexical environment, even if the call to eval itself is in a non-null environment.
Here x is just unbound during eval:
(let ((x 3)) (eval '(list x))) ;; ERROR
Here we build a let to be evaluated by eval:
(eval '(let ((x 3)) (list x)))
=> (3)
That's all for the crash course on lexical environments.
Special operators
FUNCTION
Special operator FUNCTION takes an argument that is either the name of a function (symbol or setf), or a lambda expression; in particular:
The value of function is the functional value of name in the current lexical environment.
Here the lambda expression is evaluated in the current lexical environment, which means it can refer to variable outside the lambda expression. That's the definition of closures, they capture the surrounding bindings.
NB. you do not need to prefix lambda with #', because there is a macro named (lambda ...) that expands into (function (lambda ...)). It looks like this could expand recursively forever, but this is not the case: at first the macro is expanded so that (lambda ...) becomes (function (lambda ...)), then the special operator function knows how to evaluate the lambda expression itself.
This means that (lambda ...) and #'(lambda ...) are equivalent. Note in particular that there is nothing about whether one form is compiled or not at this point, the compiler will see the same expression after macroexpansion.
QUOTE
Special operator QUOTE evaluates (quote f) as f, where f itself is unevaluated. In test-5 and test-6, there is no function, just an unevaluated structured expression that can be interpreted as code.
Type coercion
Now, certain functions like MAPCAR are used to apply functions. Notice how the specification says that the function parameter is a function designator:
function --- a designator for a function that must take as many arguments as there are lists.
A designator for a type is not necessarily a value of that type, but can be a value that can be coerced to that type. Sometimes a user wants to specify a pathname, and enters a string, but a string is not a value of type pathname: the system has to converts the string into a pathname.
Common Lisp defines a COERCE function with rules regarding how values can be converted to other values. In you case, mapcar first does (coerce (lambda ...) 'function). This is defined as follows:
If the result-type is function, and object is a lambda expression, then the result is a closure of object in the null lexical environment.
The value is thus evaluated in a null lexical environment, so it does not have access to the surrounding bindings; y is a free variable in your lambda expression, and since it is evaluated in a null environment, it is unbound. That's why test-5 pass but test-6 fails.
Name resolution, compilers and late binding
There is a difference whether you write #'f or 'f when referring to a function f where f is a symbol: in the first case, the expression evaluated to an object of type function, and in the second case, you only evaluate a symbol.
Name resolution for this function can change depending and how the compiler works. With a symbol as a function designator, the function does not even need to be defined, the name is resolved when the symbols has to be coerced as a function.
When you write #'f, some compilers may remove one level of indirection and directly make your code jump to the code associated with the function, without having to resolve the name at runtime.
However, this also means that with such compilers (e.g. SBCL), you need to recompile some call sites on function redefinition, as-if the function was declared inline, otherwise some old code will still reference the previous definition of #'f. This is something that is not necessarily important to consider at the beginning, but it can be a source of confusion to keep in mind when you are live coding.
Related
I read a relevant post on binding, however still have questions.
Here are the following examples I found. Can someone tell me if the conclusions are correct?
Dynamic Binding of x in (i):
(defun j ()
(let ((x 1))
(i)))
(defun i ()
(+ x x))
> (j)
2
Lexical Binding of x in i2:
(defun i2 (x)
(+ x x))
(defun k ()
(let ((x 1))
(i2 2)))
> (k)
4
No Global Lexical Variables in ANSI CL so Dynamic Binding is performed:
(setq x 3)
(defun z () x)
> (let ((x 4)) (z))
4
Dynamic Binding, which appears to bind to a lexically scoped variable:
(defvar x 1)
(defun f (x) (g 2))
(defun g (y) (+ x y))
> (f 5)
7
Based on the above tests, CL first tries lexical binding. If there is no lexical match in the environment, then CL tries dynamic binding. It appears that any previously lexically scoped variables become available to dynamic binding. Is this correct? If not, what is the behavior?
(defun j ()
(let ((x 1))
(i)))
(defun i ()
(+ x x))
> (j)
2
This is actually undefined behavior in Common Lisp. The exact consequences of using undefined variables (here in function i) is not defined in the standard.
CL-USER 75 > (defun j ()
(let ((x 1))
(i)))
J
CL-USER 76 > (defun i ()
(+ x x))
I
CL-USER 77 > (j)
Error: The variable X is unbound.
1 (continue) Try evaluating X again.
2 Return the value of :X instead.
3 Specify a value to use this time instead of evaluating X.
4 Specify a value to set X to.
5 (abort) Return to top loop level 0.
Type :b for backtrace or :c <option number> to proceed.
Type :bug-form "<subject>" for a bug report template or :? for other options.
CL-USER 78 : 1 >
As you see, the Lisp interpreter (!) complains at runtime.
Now:
(setq x 3)
SETQ sets an undefined variable. That's also not fully defined in the standard. Most compilers will complain:
LispWorks
;;;*** Warning in (TOP-LEVEL-FORM 1): X assumed special in SETQ
; (TOP-LEVEL-FORM 1)
;; Processing Cross Reference Information
;;; Compilation finished with 1 warning, 0 errors, 0 notes.
or SBCL
; in: SETQ X
; (SETQ X 1)
;
; caught WARNING:
; undefined variable: COMMON-LISP-USER::X
;
; compilation unit finished
; Undefined variable:
; X
; caught 1 WARNING condition
(defvar x 1)
(defun f (x) (g 2))
(defun g (y) (+ x y))
> (f 5)
7
Dynamic Binding, which appears to bind to a lexically scoped variable
No, x is globally defined to be special by DEFVAR. Thus f creates a dynamic binding for x and the value of x in the function g is looked up in the dynamic environment.
Basic rules for the developer
never use undefined variables
when using special variables always put * around them, so that it is always visible when using them, that dynamic binding&lookup is being used. This also makes sure that one does NOT declare variables by accident globally as special. One (defvar x 42) and x will from then on always be a special variable using dynamic binding. This is usually not what is wanted and it may lead to hard to debug errors.
In summary: no, CL never 'tries one kind of binding then another': rather it establishes what kind of binding is in effect, at compile time, and refers to that. Further, variable bindings and references are always lexical unless there is a special declaration in effect, in which case they are dynamic. The only time when it is not lexically apparent whether there is a special declaration in effect is for global special declarations, usually performed via defvar / defparameter, which may not be visible (for instance they could be in other source files).
There are two good reasons it decides about binding like this:
firstly it means that a human reading the code can (except possibly in the case of a global special declaration which is not visible) know what sort of binding is in use – getting a surprise about whether a variable reference is to a dynamic or lexical binding of that variable is seldom a pleasant experience;
secondly it means that good compilation is possible – unless the compiler can know what a variable's binding type is, it can never compile good code for references to that variable, and this is particularly the case for lexical bindings with definite extent where variable references can often be compiled entirely away.
An important aside: always use a visually-distinct way of writing variables which have global special declarations. So never say anything like (defvar x ...): the language does not forbid this but it's just catastrophically misleading when reading code, as this is the exact case where a special declaration is often not visible to the person reading the code. Further, use *...* for global specials like the global specials defined by the language and like everyone else does. I often use %...% for nonglobal specials but there is no best practice for this that I know of. It's fine (and there are plenty of examples defined by the language) to use unadorned names for constants since these may not be bound.
The detailed examples and answers below assume:
Common Lisp (not any other Lisp);
that the code quoted is all the code, so there are no additional declarations or anything like that.
Here is an example where there is a global special declaration in effect:
;;; Declare *X* globally special, but establish no top-level binding
;;; for it
;;;
(defvar *x*)
(defun foo ()
;; FOO refers to the dynamic binding of *X*
*x*)
;;; Call FOO with no binding for *X*: this will signal an
;;; UNBOUND-VARIABLE error, which we catch and report
;;;
(handler-case
(foo)
(unbound-variable (u)
(format *error-output* "~&~S unbound in FOO~%"
(cell-error-name u))))
(defun bar (x)
;; X is lexical in BAR
(let ((*x* x))
;; *X* is special, so calling FOO will now be OK
(foo)))
;;; This call will therefore return 3
;;;
(bar 3)
Here is an example where there are nonglobal special declarations.
(defun foo (x)
;; X is lexical
(let ((%y% x))
(declare (special %y%))
;; The binding of %Y% here is special. This means that the
;; compiler can't know if it is referenced so there will be no
;; compiler message even though it is unreferenced in FOO.
(bar)))
(defun bar ()
(let ((%y% 1))
;; There is no special declaration in effect here for %Y%, so this
;; binding of %Y% is lexical. Therefore it is also unused, and
;; tere will likely be a compiler message about this.
(fog)))
(defun fog ()
;; FOG refers to the dynamic binding of %Y%. Therefore there is no
;; compiler message even though there is no apparent binding of it
;; at compile time nor gobal special declaration.
(declare (special %y%))
%y%)
;;; This returns 3
;;;
(foo 3)
Note that in this example it is always lexically apparent what binding should be in effect for %y%: just looking at the functions on their own tells you what you need to know.
Now here are come comments on your sample code fragments.
(defun j ()
(let ((x 1))
(i)))
(defun i ()
(+ x x))
> (j)
<error>
This is illegal in CL: x is not bound in i and so a call to i should signal an error (specifically an unbound-variable error).
(defun i2 (x)
(+ x x))
(defun k ()
(let ((x 1))
(i2 2)))
> (k)
4
This is fine: i2 binds x lexically, so the binding established by k is never used. You will likely get a compiler warning about unused variables in k but this is implementation-dependent of course.
(setq x 3)
(defun z () x)
> (let ((x 4)) (z))
<undefined>
This is undefined behaviour in CL: setq's portable behaviour is to mutate an existing binding but not to create a new bindings. You are trying to use it to do the latter, which is undefined behaviour. Many implementations allow setq to be used like this at top-level and they may either create what is essentially a global lexical, a global special, or do some other thing. While this is often done in practice when interacting with a given implementation's top level, that does not make it defined behaviour in the language: programs should never do this. My own implementation squirts white-hot jets of lead from hidden nozzles in the general direction of the programmer when you do this.
(defvar x 1)
(defun f (x) (g 2))
(defun g (y) (+ x y))
> (f 5)
7
This is legal. Here:
defvar declares x globally special, so all bindings of x will be dynamic, and establishes a top-level binding of x to 1;
in f the binding of its argument, x will therefore be dynamic, not lexical (without the preceding defvar it would be lexical);
in g the free reference to x will be to its dynamic binding (without the preceding defvar it would be a compile-time warning (implementation-dependent) and a run-time error (not implementation-dependent).
In this post, I ask tangentially why when I declare in SBCL
(defun a (&rest x)
x)
and then check what the function cell holds
(describe 'a)
COMMON-LISP-USER::A
[symbol]
A names a compiled function:
Lambda-list: (&REST X)
Derived type: (FUNCTION * (VALUES LIST &OPTIONAL))
Source form:
(LAMBDA (&REST X) (BLOCK A X))
I see this particular breakdown of the original function. Could someone explain what this output means? I'm especially confused by the last line
Source form:
(LAMBDA (&REST X) (BLOCK A X))
This is mysterious because for some reason not clear to me Lisp has transformed the original function into a lambda expression. It would also be nice to know the details of how a function broken down like this is then called. This example is SBCL. In Elisp
(symbol-function 'a)
gives
(lambda (&rest x) x)
again, bizarre. As I said in the other post, this is easier to understand in Scheme -- but that created confusion in the answers. So once more I ask, Why has Lisp taken a normal function declaration and seemingly stored it as a lambda expression?
I'm still a bit unclear what you are confused about, but here is an attempt to explain it. I will stick to CL (and mostly to ANSI CL), because elisp has a lot of historical oddities which just make things hard to understand (there is an appendix on elisp). Pre-ANSI CL was also a lot less clear on various things.
I'll try to explain things by writing a macro which is a simple version of defun: I'll call this defun/simple, and an example of its use will be
(defun/simple foo (x)
(+ x x))
So what I need to do is to work out what the expansion of this macro should be, so that it does something broadly equivalent (but simpler than) defun.
The function namespace & fdefinition
First of all I assume you are comfortable with the idea that, in CL (and elisp) the namespace of functions is different than the namespace of variable bindings: both languages are lisp-2s. So in a form like (f x), f is looked up in the namespace of function bindings, while x is looked up in the namespace of variable bindings. This means that forms like
(let ((sin 0.0))
(sin sin))
are fine in CL or elisp, while in Scheme they would be an error, as 0.0 is not a function, because Scheme is a lisp-1.
So we need some way of accessing that namespace, and in CL the most general way of doing that is fdefinition: (fdefinition <function name>) gets the function definition of <function name>, where <function name> is something which names a function, which for our purposes will be a symbol.
fdefinition is what CL calls an accessor: this means that the setf macro knows what to do with it, so that we can mutate the function binding of a symbol by (setf (fdefinition ...) ...). (This is not true: what we can access and mutate with fdefinition is the top-level function binding of a symbol, we can't access or mutate lexical function bindings, and CL provides no way to do this, but this does not matter here.)
So this tells us what our macro expansion needs to look like: we want to set the (top-level) definition of the name to some function object. The expansion of the macro should be like this:
(defun/simple foo (x)
x)
should expand to something involving
(setf (fdefinition 'foo) <form which makes a function>)
So we can write this bit of the macro now:
(defmacro defun/simple (name arglist &body forms)
`(progn
(setf (fdefinition ',name)
,(make-function-form name arglist forms))
',name))
This is the complete definition of this macro. It uses progn in its expansion so that the result of expanding it is the name of the function being defined, which is the same as defun: the expansion does all its real work by side-effect.
But defun/simple relies on a helper function, called make-function-form, which I haven't defined yet, so you can't actually use it yet.
Function forms
So now we need to write make-function-form. This function is called at macroexpansion time: it's job is not to make a function: it's to return a bit of source code which will make a function, which I'm calling a 'function form'.
So, what do function forms look like in CL? Well, there's really only one such form in portable CL (this might be wrong, but I think it is true), which is a form constructed using the special operator function. So we're going to need to return some form which looks like (function ...). Well, what can ... be? There are two cases for function.
(function <name>) denotes the function named by <name> in the current lexical environment. So (function car) is the function we call when we say (car x).
(function (lambda ...)) denotes a function specified by (lambda ...): a lambda expression.
The second of these is the only (caveats as above) way we can construct a form which denotes a new function. So make-function-form is going to need to return this second variety of function form.
So we can write an initial version of make-function-form:
(defun make-function-form (name arglist forms)
(declare (ignore name))
`(function (lambda ,arglist ,#forms)))
And this is enough for defun/simple to work:
> (defun/simple plus/2 (a b)
(+ a b))
plus/2
> (plus/2 1 2)
3
But it's not quite right yet: one of the things that functions defined by defun can do is return from themselves: they know their own name and can use return-from to return from it:
> (defun silly (x)
(return-from silly 3)
(explode-the-world x))
silly
> (silly 'yes)
3
defun/simple can't do this, yet. To do this, make-function-form needs to insert a suitable block around the body of the function:
(defun make-function-form (name arglist forms)
`(function (lambda ,arglist
(block ,name
,#forms))))
And now:
> (defun/simple silly (x)
(return-from silly 3)
(explode-the-world x))
silly
> (silly 'yes)
3
And all is well.
This is the final definition of defun/simple and its auxiliary function.
Looking at the expansion of defun/simple
We can do this with macroexpand in the usual way:
> (macroexpand '(defun/simple foo (x) x))
(progn
(setf (fdefinition 'foo)
#'(lambda (x)
(block foo
x)))
'foo)
t
The only thing that's confusing here is that, because (function ...) is common in source code, there's syntactic sugar for it which is #'...: this is the same reason that quote has special syntax.
It's worth looking at the macroexpansion of real defun forms: they usually have a bunch of implementation-specific stuff in them, but you can find the same thing there. Here's an example from LW:
> (macroexpand '(defun foo (x) x))
(compiler-let ((dspec::*location* '(:inside (defun foo) :listener)))
(compiler::top-level-form-name (defun foo)
(dspec:install-defun 'foo
(dspec:location)
#'(lambda (x)
(declare (system::source-level
#<eq Hash Table{0} 42101FCD5B>))
(declare (lambda-name foo))
x))))
t
Well, there's a lot of extra stuff in here, and LW obviously has some trick around this (declare (lambda-name ...)) form which lets return-from work without an explicit block. But you can see that basically the same thing is going on.
Conclusion: how you make functions
In conclusion: a macro like defun, or any other function-defining form, needs to expand to a form which, when evaluated, will construct a function. CL offers exactly one such form: (function (lambda ...)): that's how you make functions in CL. So something like defun necessarily has to expand to something like this. (To be precise: any portable version of defun: implementations are somewhat free to do implementation-magic & may do so. However they are not free to add a new special operator.)
What you are seeing when you call describe is that, after SBCL has compiled your function, it's remembered what the source form was, and the source form was exactly the one you would have got from the defun/simple macro given here.
Notes
lambda as a macro
In ANSI CL, lambda is defined as a macro whose expansion is a suitable (function (lambda ...)) form:
> (macroexpand '(lambda (x) x))
#'(lambda (x) x)
t
> (car (macroexpand '(lambda (x) x)))
function
This means that you don't have to write (function (lambda ...)) yourself: you can rely on the macro definition of lambda doing it for you. Historically, lambda wasn't always a macro in CL: I can't find my copy of CLtL1, but I'm pretty certain it was not defined as one there. I'm reasonably sure that the macro definition of lambda arrived so that it was possible to write ISLisp-compatible programs on top of CL. It has to be in the language because lambda is in the CL package and so users can't portably define macros for it (although quite often they did define such a macro, or at least I did). I have not relied on this macro definition above.
defun/simple does not purport to be a proper clone of defun: its only purpose is to show how such a macro can be written. In particular it doesn't deal with declarations properly, I think: they need to be lifted out of the block & are not.
Elisp
Elisp is much more horrible than CL. In particular, in CL there is a well-defined function type, which is disjoint from lists:
> (typep '(lambda ()) 'function)
nil
> (typep '(lambda ()) 'list)
t
> (typep (function (lambda ())) 'function)
t
> (typep (function (lambda ())) 'list)
nil
(Note in particular that (function (lambda ())) is a function, not a list: function is doing its job of making a function.)
In elisp, however, an interpreted function is just a list whose car is lambda (caveat: if lexical binding is on this is not the case: it's then a list whose car is closure). So in elisp (without lexical binding):
ELISP> (function (lambda (x) x))
(lambda (x)
x)
And
ELISP> (defun foo (x) x)
foo
ELISP> (symbol-function 'foo)
(lambda (x)
x)
The elisp intepreter then just interprets this list, in just the way you could yourself. function in elisp is almost the same thing as quote.
But function isn't quite the same as quote in elisp: the byte-compiler knows that, when it comes across a form like (function (lambda ...)) that this is a function form, and it should byte-compile the body. So, we can look at the expansion of defun in elisp:
ELISP> (macroexpand '(defun foo (x) x))
(defalias 'foo
#'(lambda (x)
x))
(It turns out that defalias is the primitive thing now.)
But if I put this definition in a file, which I byte compile and load, then:
ELISP> (symbol-function 'foo)
#[(x)
"\207"
[x]
1]
And you can explore this a bit further: if you put this in a file:
(fset 'foo '(lambda (x) x))
and then byte compile and load that, then
ELISP> (symbol-function 'foo)
(lambda (x)
x)
So the byte compiler didn't do anything with foo because it didn't get the hint that it should. But foo is still a fine function:
ELISP> (foo 1)
1 (#o1, #x1, ?\C-a)
It just isn't compiled. This is also why, if writing elisp code with anonymous functions in it, you should use function (or equivalently #'). (And finally, of course, (function ...) does the right thing if lexical scoping is on.)
Other ways of making functions in CL
Finally, I've said above that function & specifically (function (lambda ...)) is the only primitive way to make new functions in CL. I'm not completely sure that's true, especially given CLOS (almost any CLOS will have some kind of class instances of which are functions but which can be subclassed). But it does not matter: it is a way and that's sufficient.
DEFUN is a defining macro. Macros transform code.
In Common Lisp:
(defun foo (a)
(+ a 42))
Above is a definition form, but it will be transformed by DEFUN into some other code.
The effect is similar to
(setf (symbol-function 'foo)
(lambda (a)
(block foo
(+ a 42))))
Above sets the function cell of the symbol FOO to a function. The BLOCK construct is added by SBCL, since in Common Lisp named functions defined by DEFUN create a BLOCK with the same name as the function name. This block name can then be used by RETURN-FROM to enable a non-local return from a specific function.
Additionally DEFUN does implementation specific things. Implementations also record development information: the source code, the location of the definition, etc.
Scheme has DEFINE:
(define (foo a)
(+ a 10))
This will set FOO to a function object.
This question already has answers here:
What is the difference between Lisp-1 and Lisp-2?
(2 answers)
Closed 6 years ago.
I am attempting to understand the lambda notion found within Emacs Lisp.
In ielm, executing:
((lambda (x) (* x x)) 5)
gives us 25, and
(let ((x 4)) (* x x))
gives us 16. However when I do:
(let ((f (lambda (x) (* x x)))) (f 7))
it does not give me 49, but instead informs me:
*** Eval error *** Symbol's function definition is void: f
Don't know why, I am sure the syntax is right and f is defined in the let?
Using cl-flet to define let-ed function
We can actually do this without using funcall. The cl module includes standard functions from Common Lisp. We first import it:
(require 'cl)
Thereafter we can use cl-flet to define our function:
(cl-flet ((f (x) (* x x)))
(f 7))
I'd be surprised if this isn't a duplicate, but I can't find it readily here on Stack Overflow. In "Lisp-2" languages (e.g., Emacs Lisp and Common Lisp), there are separate namespaces for functions and variables. A function call looks like:
((lambda ...) ...) ; call the lambda function
or
(f ...) ; call the function binding of f
If you want to call the function that is the value of a variable, then you need to use funcall or apply:
(apply f ...)
(funcall f ...)
The difference between apply and funcall is well documented in other places, but the quick difference is that apply expects an argument list (in some Lisps, a "spreadable argument list"), whereas funcall takes the arguments directly. E.g.,
(let ((f (lambda (a b) (+ a b))))
(funcall f 1 2) ; arguments directly
(apply f '(1 2))) ; arguments in a list
In a "Lisp-1", (like Scheme), you don't need funcall, since there's only one space for bindings. In Scheme you can do:
(let ((f (lambda (a b) (+ a b))))
(f 1 2))
The difference between Lisp-1 and Lisp-2 languages is described more in What is the difference between Lisp-1 and Lisp-2?. The big difference is when the system sees a function call, how it figures out what function to call. In a Lisp-1, variables have values, and that's all. So when the system sees something like:
(f ...)
f is a variable, and the only possible thing to call is the value of f. In a Lisp-2, the systems tries to call the function value of f, which doesn't have to have anything do with the value of the variable f. That can be a bit confusing at first, but it's actually pretty handy in many cases, because it makes it harder to accidentally obscure functions with common names. E.g., in a Lisp-1, you'll see lots of people use lst as an argument name instead of list, because if they named the argument list, then they couldn't use the (standard) function list within the function.
Are symbols and names different? On Lisp by Paul Graham, which focuses on common lisp, has some discussions that seem to imply so, e.g.
Since lambda-expressions are also names of functions, they can also appear first in function calls:
((lambda (x) (* x 2) 3)
6
This makes it sound like symbols are names but names aren't symbols. But I don't understand what sort of Lisp "object" symbols are / could be.
This is also deriving from my question here on the sharp-quote (#') operator v. symbol-function. I'm suspecting the only reason these are different is because not all names are symbols but I don't have enough background to understand those answers yet (hence this question).
I'm also asking for clarification in elisp v. common lisp. I'm assuming this pertains to lexical form, which wasn't introduced in elisp until version 24 (24.1 I think).
Lambda Expressions are not names of functions. It's just that ((lambda (...) ...) ...) is allowed in Common Lisp, since it is defined in the standard as legal syntax.
The only allowed function names in Common Lisp are symbols and lists like (setf symbol).
For example one can write
(defun (setf foo) (...) ...)
Here (setf foo) is the function name.
Other function names don't exist in Common Lisp, only symbols and (setf symbol) names.
Common Lisp Hyperspec Glossary: Function Name.
function name n. 1. (in an environment) A symbol or a list (setf
symbol) that is the name of a function in that environment. 2. A
symbol or a list (setf symbol).
Note: the Common Lisp version of 1984 (as published in CLtL1) did only have symbols as function names. Thus the idea of a function name was not defined. The function to retrieve a function from a symbol was called SYMBOL-FUNCTION. In 1989 the ANSI CL standardization group decided to add setf lists as function names. It also introduced the function FDEFINITION, which is like SYMBOL-FUNCTION but also accepts other function names, besides symbols. See here: Issue FUNCTION-NAME.
I think Rainer's answer gets this right, but since the question appeared in a comment on my answer to another question, I'll include (an update to) my response from that comment.
A symbol is an actual object. You can inspect it, you can create them with make-symbol, etc. Importantly, symbols are one of the primary components of source code in Common Lisp. Function names, especially in the context that this question arose in (arguments to the function special operator) are either symbols or lists of the form (setf symbol) according to the glossary entry:
function name n. 1. (in an environment) A symbol or a list (setf symbol) that is the name of a function in that environment. 2. A
symbol or a list (setf symbol).
Function is a special operator that doesn't evaluate its arguments, so passing a symbol or setf list means something like:
(function car)
(function (setf car))
and not:
(function 'car)
(function '(setf car))
Now, lexical variables, e.g., x in (let ((x 42)) x), while represented by symbols in the source code, don't actually have any connection with the symbol at runtime. The compiled version of (let ((x 42)) x) doesn't need to know anything about the symbol x. Intuitively, this makes sense, because we'd expect the code (let ((y 42)) y) to compile to the same thing. However, when a variable is special, there is a connection with the symbol. The difference is clearest with:
(let ((x 42))
(symbol-value x))
;=> NIL
(let ((x 42))
(declare (special x)) ; or (defparameter x ...) or (defvar x ...) earlier
(symbol-value x))
;=> 42
We'd expect the same thing to be true of lexically scoped functions, e.g., the following code causes an error because there's no connection between the symbol x at runtime and the local function:
(flet ((x () 42))
(symbol-function 'x)) ; ERROR, no function value for symbol x
But even so, we can still do:
(flet ((x () 42))
(function x))
This is because function is special operator and can access the environment where is occurs. That means that (because it's special, and the implementation makes it work) it can know that x is defined as function here. It may be interesting to note, now, that since flet and labels are defined to take a function name, you can do:
(flet (((setf kar) (value kons)
...))
...)
I'm confused about how defun macro works, because
(defun x () "hello")
will create function x, but symbol x still will be unbound.
If I'll bind some lambda to x then x will have a value, but it will not be treated by interpreter as function in form like this:
(x)
I think that it is related to the fact that defun should define function in global environment, but I'm not sure what does it exactly mean. Why can't I shadow it in the current environment?
Is there any way to force interpreter treat symbol as function if some lambda was bound to it? For example:
(setq y (lambda () "I want to be a named function"))
(y)
P.S.: I'm using SBCL.
Common Lisp has different namespaces for functions and values.
You define functions in the function namespace with DEFUN, FLET, LABELS and some others.
If you want to get a function object as a value, you use FUNCTION.
(defun foo (x) (1+ x))
(function foo) -> #<the function foo>
or shorter:
#'foo -> #<the function foo>
If you want to call a function, then you write (foo 100).
If you want to call the function as a value then you need to use FUNCALL or APPLY:
(funcall #'foo 1)
You can pass functions around and call them:
(defun bar (f arg)
(funcall f arg arg))
(bar #'+ 2) -> 4
In the case of DEFUN:
It is not (setf (symbol-value 'FOO) (lambda ...)).
It is more like (setf (symbol-function 'foo) (lambda ...)).
Note that the two namespaces enable you to write:
(defun foo (list)
(list list))
(foo '(1 2 3)) -> ((1 2 3))
There is no conflict between the built-in function LIST and the variable LIST. Since we have two different namespaces we can use the same name for two different purposes.
Note also that in the case of local functions there is no symbol involved. The namespaces are not necessarily tied to symbols. Thus for local variables a function lookup via a symbol name is not possible.
Common Lisp has multiple slots for each symbol, including a value-slot, and a function-slot. When you use the syntax (x), common lisp looks for the function-slot-binding of x. If you want to call the value-binding, use funcall or apply.
See http://cl-cookbook.sourceforge.net/functions.html