How to call particular function depending on variable that's passed in? - common-lisp

I'm fairly new to lisp but I've been playing around with it. I have several problems which I need clarifying. Below is my little macro that I defined.
(defmacro transform (query)
'(lambda (row)
(eq (nth 1 query) (nth 0 (nth 0 row)))
)
)
I'm just wondering how I can specify the function to use in the body dynamically? Say if I want to use the "+" or "-" function instead of "eq", or even another function that I defined? Like I thought it'd be possible to pass in the name of the function as a parameter but that obviously doesn't work. I also get variable unbound errors when I modify the list (query) that's passed in.

In the body of the macro, you can use all of Lisp's run-time library to generate the actual expansion. So, for example:
(defmacro transform (query &key (test 'eq))
(let ((row-var (gensym)))
`(lambda (,row-var)
(,test (nth 1 ,query) (nth 0 (nth 0 ,row-var))))))
This version uses the "backtick" instead of a plain apostrophe, which allows for "unquoting" of forms within the body, thus allowing the inclusion of generated forms into the result.
You can use this macro like your original version:
(transform (...))
or (passing an explicit test function):
(transform (...) :test equal)
Note, that you should not use plain symbols as variable names in macro expansions (as your row argument to the generated lambda expression) as that might accidentally interfer with the use of that symbol at the site of the use of your macro. You simply don't know when writing your macro, whether there will be a variable called row somewhere when your macro is used, and whether it is not already used within the query form/expression. Your original definition would "capture" the variable, possibly altering the meaning of whatever query does.

funcall is the answer! Decided to just pass it in and use funcall to evaluate the function.

Related

Is it valid to use "setf" to create special variables?

It appears that I can use setf to create special variables. For example, if I start the REPL and enter (setf x 123), a special variable x will be created. There is no error in CLISP and ECL. SBCL gives a warning (undefined variable: COMMON-LISP-USER::X), but creates the special variable anyway. Is setf a valid way to create special variables?
It is not valid to use setf to create new variables. The HyperSpec is pretty clear that setf is only intended to update existing variables:
setf changes the value of place to be newvalue.
(setf place newvalue) expands into an update form that stores the result of evaluating newvalue into the location referred to by place.
setf is intended for updating a place. There is no behavior specified for attempting to use setf to update the value of a place that does not already exist.
In the section which discusses assignment, CLTL2 says a bit more:
Such alteration is different from establishing a new binding. Constructs for establishing new bindings of variables are described in section 7.5.
While this may seem to work, you can't rely on it. It often works in REPLs, and it is fine if you want to use setf this way when playing around in a REPL, but you should not do this in any program.
Actually it is a bit tricky.
This is one of the things in Common Lisp which are underspecified. Unfortunately.
LispWorks:
CL-USER 61 > (setf foo 1)
1
CL-USER 62 > (defun bar () foo)
BAR
CL-USER 63 > (bar)
1
CL-USER 64 > (let ((foo 2))
(bar))
1
The last foo in the let is using lexical binding and thus there it is not assumed to be special.
In the forms (setf foo 1) and (defun bar () foo) the variable foo is assumed by the particular Lisp implementation to be special and it even could be declared to be special by setf (-> which most implementations don't).
Whether above let form returns 1 or 2 is unspecified in the Common Lisp language standard. Most implementations will return 1, though.
Next:
CL-USER 65 > (let ((foo 2))
(declare (special foo))
(bar))
2
Above we see that the use of foo inside bar is actually using the dynamic binding of foo in the let.
Basically the exact effects of setting an undefined variable is unspecified. The variable could be assumed to be special or not. Most implementations prefer to NOT declare it special, such that further use of the variable must be special.
But whether the variable is special or not, and the exact effects using it, is actually undefined in the Common Lisp language standard.
Most implementations agree
that setf setting an undefined variable only changes the symbol value of the symbol
that setting and retrieving the variable is assuming a special variable
that rebinding the variable by let(or similar) does not create a special variable
that a compiler (if used) will warn about an undefined variable and/or about assuming a special variable.
One implementation where the default disagrees is CMUCL -> there the setf also declares the variable to be special, similar to what defparameter would do.
For a general style rule see the last paragraph of ad absurdum's answer.

Usefulness/point of function "symbol-name"?

On first look it seems somewhat silly to have a function which returns the name of a symbol, which must be called using the name of that same symbol. i.e. it should already be obvious in the calling context what the function will return. On the other hand there is identity which is sometimes useful (I forget where just now) but I supposed (perhaps wrongly) that symbol-function is there for a reason other than simply to act as a kind of identity.
However, the hyperspec offers a possible hint:
(symbol-name 'temp) => "TEMP"
(symbol-name :start) => "START"
(symbol-name (gensym)) => "G1234" ;for example
I note that :start means get the name of the symbol start from the keyword package, where the keyword package is denoted simply by :.
(:keyword being its longer form, unnecessary to use). Thus, in this case symbol-name plays the role of simply removing the package prefix.
The other thing it might do is, given an implementation is case insensitive, it would get the actual name by removing case in the symbol name supplied.
Is that roughly it or is there any importance to this function I am missing?
One thing I was confused by about symbols (cleared up now) is that symbol-plist does not tell you everything about the symbol (say, whether it holds the value of a special variable or function). Rather, plist is a mainly legacy feature now largely replaced by hashtables. So, a call to symbol-plist is going to return NIL even if one has set a special variable on the symbol.
One final question on that, Paul Graham says in Chapter 8 (p133), that "You can use symbols as data objects and as names for things without understanding how the two are related". Would it be correct say that if we rarely now use plists, that, today, we generally don't use symbols "as data objects" at all, instead, just as names for things (allbeit with the duality in CL of course, i.e. symbol-function and symbol-value simultaneously).
Symbols are objects. You can create them and pass them around programmatically. One of the properties of these objects is their name, which is a string. Symbol-name is the reader (not accessor) for that. That's all.
Symbols are also used in the representation of code. In this case, they are created by the reader and used by the compiler. This is not their only use, however, and the spec makes no such assumptions either. I hope that this addresses the core of your question.
Here is a function that, given a symbol, returns a symbol interned in the same package but with a reversed name:
(defun reverse-symbol (symbol)
(intern (make-symbol (reverse (symbol-name symbol)))
(symbol-package symbol)))
Here is a function that, given a string designator, returns the designated string:
(defun designated-string (string-designator)
(ctypecase string-designator
(string string-designator)
(symbol (symbol-name string-designator))))
You can also do all kinds of shenanigans in macros and compiler macros by inspecting the names of the symbols in the given form and applying some conventions (not that you should…).
Let's assume you want to write some protocol for transmitting bits of structure between two different systems over some serial channel
(defgeneric transmit-object (o stream))
What is the method for symbols going to look like?
(defmethod transmit-object ((o symbol) stream)
... (symbol-name o) ...)
In particular you certainly do not know the name of the symbol at the point where you need to reason about it, and you could not write such a protocol without using symbol-name (or some absolutely appalling hack like printing the symbol to a string and using that).
Regarding symbol-plist, the implementation is completely at liberty to keep all sorts of information on the property list of a symbol. I am not even sure that the implementation is not allowed to do (a cleverer version of):
(defun symbol-value (s)
(let* ((d (load-time-value (cons nil nil)))
(v (get s secret-value-indicator d)))
(when (eq v d)
(error ...))
v))
It may be that this is not allowed, but I am not sure. Certainly it was once fairly common for function definitions to be kept in this way.
It's not so silly when you process symbol names. When you for example build preprocessor - you read some data, convert it to list structures and then some code is processing those list and trigger some additional logic when symbol-name is lets say defun-my-ubermacro. It's exactly what's in Graham quote - you treat symbols as data.
And (in my opinion) it's not correct to say, that when you don't use plists, you generally don't use symbols as data. Plists are only on of many places where it's useful feature. A lot of what macros do is processing symbols as data / names.
On first look it seems somewhat silly to have a function which returns the name of a symbol, which must be called using the name of that same symbol.
That's wrong. symbol-name is called with a symbol and not a name. It returns the name as a string.
I note that :start means get the name of the symbol start from the keyword package, where the keyword package is denoted simply by :. (:keyword being its longer form, unnecessary to use). Thus, in this case symbol-name plays the role of simply removing the package prefix.
No, symbol-name returns the name of the symbol as a string. The keyword symbol is an object of type symbol.
A symbol is a data type and has several cells:
the name, a string
possibly a function
possibly a value
a property list
optionally the home package it is interned in
don't use symbols "as data objects" at all, instead, just as names for things
No, symbols as data objects have many purposes. For example Lisp source code uses many symbols. But it can also appear in all sorts of data.
CL-USER 6 > 'foo
FOO
CL-USER 7 > (type-of 'foo)
SYMBOL
CL-USER 8 > (symbol-name 'foo)
"FOO"
CL-USER 9 > (type-of (symbol-name 'foo))
SIMPLE-BASE-STRING
CL-USER 10 > (mapcar #'symbol-name '(a b c defun foo bar))
("A" "B" "C" "DEFUN" "FOO" "BAR")
CL-USER 11 > (mapcar #'type-of *)
(SIMPLE-BASE-STRING SIMPLE-BASE-STRING SIMPLE-BASE-STRING SIMPLE-BASE-STRING SIMPLE-BASE-STRING SIMPLE-BASE-STRING)
Since you haven't accepted an answer, here is my take.
For most day-to-day programming symbols, and therefore SYMBOL-NAME,
aren't very useful. Mostly they are used for their
unique-ness. However they shine when you are modifying the compiler
with macros.
Here are 3 examples where SYMBOL-NAME is used:
Firstly, LOOP is the CL generic looping construct, it works via
placeholder symbols in a way that some claim is un-lispy, but it
remains very handy, especially if you are stepping things in parallel.
The following 3 forms are equivalent (at run-time):
(loop for i in list collect i)
(loop :for i :in list :collect i)
(loop #:for i #:in list #:collect i)
I, personally, prefer the third form because it makes it really
obvious where the LOOP magic is happening, and also avoids interning
symbols in any package (which is usually harmless, but not
always). That the third works at all requires the existence of
SYMBOL-NAME
Secondly, I don't make much use of CLOS but classes are undeniably
useful. DEFCLASS tends to be too verbose for what I want to do though,
so I often employ a macro that uses implied symbols. So:
(defbean peer ()
(id)
(next
beats))
Becomes:
(defclass peer nil
((id :initarg :id :reader peer-id)
(next :initarg :next :accessor peer-next)
(beats :initarg :beats :accessor peer-beats)))
Saving much typing. Notice how the slot name is converted to a keyword
for the initargs, and how reader and accessor names are created.
Some don't like this sort of macro, and I can see how it might be
problematic if you have a large team with everyone doing this all over
the shop (though M-. and C-c ret are always available), but for
small teams I think this is one of the best reasons to use lisp,
customising it to how you actually want to use it.
Thirdly, my sqlite helper library uses SYMBOL-NAME to generate SQL
statements (along with some more implied symbols) for even more
code-saving:
(defsqlite-table artists
(id :auto-key)
(artist-name :t)
(sort-artist-name :t :n))
Becomes something pretty huge:
(progn
(defparameter +create-artists-sql+
"CREATE TABLE artists (
id INTEGER PRIMARY KEY NOT NULL,
artist_name TEXT NOT NULL,
sort_artist_name TEXT
)")
(defun create-artists-table (pjs-sqlite::db pjs-sqlite::recursive log)
###)
(eval-when (:load-toplevel)
###)
(defun insert-artists
(pjs-sqlite::db artist-name sort-artist-name &key (id nil id-p))
###)
(defun update-artists
(pjs-sqlite::db id
&key (artist-name nil artist-name-p)
(sort-artist-name nil sort-artist-name-p))
###)
(defun delete-artists (pjs-sqlite::db id)
(with-sqlite-statements (pjs-sqlite::db
(pjs-sqlite::stmt
"DELETE FROM artists WHERE id = ?"))
###)))
(I stripped out a lot of code that would be distracting, but it should
be clear how I mapped symbols to sql identifiers)
I hope this gives you some ideas on what sort of things SYMBOL-NAME
can be used for.

How to pass common-lisp' local variable to maxima?

I am using maxima inside SBCL and I want to do the following-simple demo for real time plotting without pause/delay-:
(loop for j from 1 below 10 do
#$plot2d(sin(x),[x,0,?j*%pi])$)
error:range must be of the form [variable, min, max]; found: [x,0,%pi*j]
I have to use setf/defvar, but I want to use local variables.
Questions:
How to pass common-lisp' local variable to maxima?
Thanks in advance.
Maxima uses only dynamic scope, not lexical scope. Maxima variables are implemented as Lisp symbols which are declared special. In order for J to be visible to Maxima, it must be declared special in one way or another (either via DEFVAR/DEFPARAMETER or (DECLARE (SPECIAL ...)), I forget if there are other ways).
I know this is not satisfying since dynamic scope makes it possible to have name collisions and therefore subtle bugs. Maybe you can ensure there are no name collisions by using a gensym; maybe write a macro to substitute a gensym for another variable and declare the gensym special, something like that.
I am suing this macro:
(defmacro with-maxima (&body body)
"write normal maxima exprs."
`(progn
,#(mapcar (lambda (slot)
(destructuring-bind (&body args) slot
`(maxima:displa ,(read-from-string (concatenate 'string
"#$" (princ-to-string args) "$")))))
body)
,(read-from-string "#$reset()$")
,(read-from-string "#$kill(all)$")))
example :
(with-maxima
"y3: k-y1-2*y2"
"gradef(y1,t,v1)"
"gradef(y2,t,v2)"
"gradef(v1,t,a1)"
"gradef(v2,t,a2)"
"diff(y3,t)")

Trying to write a function that creates global symbols in common lisp

I have a global list of words (symbols) and I want to write a function that can add new words to it. I can add new words but then I run into errors that they are unbound. how can I write a function:
(defun add-symbol (aNewWord) (... ))
and have it create a global symbol
using the argument I type as its name?
Perhaps I would like a user to add new symbols during runtime.
Use PUSH to add an element to a list.
(defvar *word-list* ())
(defun add-symbol (new-word)
(push new-word *word-list*))
(add-symbol 'hello)
(add-symbol 'friday)
*word-list*
Output is:
(FRIDAY HELLO)
If you were getting errors about unbound variables, you probably forgot to quote the symbols when you used them as arguments to the function. If you don't quote a symbol, it's treated as a variable name and tries to use its value.
Generally, you want to control the namespace for user created data and not have it leak into your program structure. It is thus preferable to create some (maybe top level) datastructure inside of which you hold the data. Do not create variables from user data.
Keys for such data might be symbols, which you can create with intern. If you want to create new symbols with names given by the user, you might want to use either the keyword package:
(defun make-user-symbol (string)
(intern string '#:keyword))
or some pristine package for exactly those symbols:
(defpackage #:user-symbols)
(defun make-user-symbol (string)
(intern string '#:user-symbols))
One flexible data structure for such things are hash tables:
(defvar *user-data* (make-hash-table :test #'eq))
(defun add-user-data (keystring value)
(setf (gethash (make-user-symbol keystring) *user-data*)
value))
You could also just use strings, of course, but then the hash table needs to use :test #'equal.
If you want to have a set of words as symbols (though I do not see the need for such a conversion), your data structure might be a list:
(defvar *words* ())
(defun add-word (string)
(push (make-user-symbol string) *words*))

Common Lisp: Why progn is a special form?

Since Common Lisp's function arguments evaluate in left-to-right order, why wouldn't use an ordinary function:
(defun progn2 (&rest body)
(first (last body)))
instead of special form?
There is also another feature of PROGN which you can't get with a function:
Imagine this code in a file of Common Lisp code:
(progn
(defmacro foo () ))
vs.
(my-progn
(defmacro foo () ))
With using PROGN the compiler will treat the DEFMACRO form as a top-level form. That means for example that the compiler notes that there is a macro definition and makes it available in the compile-time environment.
Using a function MY-PROGN, the compiler won't recognize the DEFMACRO form, because it is not at top-level.
progn returns all the values of the last form it evaluates, your function returns just the first one:
(progn (values 1 2 3))
=> 1, 2, 3
(progn2 (values 1 2 3))
=> 1
Another critical feature of progn (mentioned by Rainer first) is that it keeps all its forms top-level, which makes it possible for macros to expand to multiple forms (see, e.g., my answer to "“value returned is unused” warning when byte-compiling a macro").

Resources