DEFUNs inside a LET - why? - common-lisp

I was reading the source for ChanL the other day. It contains an example use of channels, to implement futures. The DEFUNs were declared inside a LET, like so:
(let ((some-var some-value))
(defun foo () ... (reference some-var) ... )
(defun bar () ...))
What purpose does this serve? Is it just to provide some common value that several functions can share, and keep the encapsulation clean?

You already answered your question: to provide shared bindings for a group of functions and keep encapsulation clean.
Simple example from http://letoverlambda.com/textmode.cl/guest/chap2.html:
(let ((direction 'down))
(defun toggle-direction ()
(setq direction
(if (eq direction 'up)
'down
'up))))
(toggle-direction) => UP
(toggle-direction) => DOWN
(toggle-direction) => UP
(toggle-direction) => DOWN
You can also add a function inside this closure which behavior depends on direction.

Those are just closures. Just for the historical context [1],
Closures play a more conspicuous role in a style of programming
promoted by Abelson and Sussman’s classic Structure and Interpretation
of Computer Programs. Closures are functions with local state. The
simplest way to use this state is in a situation like the following:
(let ((counter 0))
(defun new-id () (incf counter))
(defun reset-id () (setq counter 0)))
These two functions share a variable which serves as a counter. The
first one returns successive values of the counter, and the second
resets the counter to 0. The same thing could be done by making the
counter a global variable, but this way it is protected from
unintended references.
Paul Graham - On lisp

Related

Let, flet, macrolet : is there a way to do a "class-let"?

I have a macro which defines a class under certain rules, pseudo-code :
(defvar *all-my-classes* nil)
(defmacro my-macro (param)
`(if ,param
(progn
(defclass class-A () ...)
(push class-A *all-my-classes*))
(progn
(defclass class-B () ...)
(push class-B *all-my-classes*))))
I want to test the behaviour of the macro. Let is a convenient tool to mock variables. If I have an instance of *all-my-classes* running, I just have to do :
(let ((*all-my-classes* my-new-value)) ; generally `nil` for the test
(my-macro false))
But I would like to conserve the correspondance between *all-my-classes* and the classes defined. Since I want to test all the cases, let us suppose class-A is defined in the current environment, and i want to test if running (my-macro false) correctly defines class-B.
Since it is just a test, I would like the test to assert that class-B is currently defined, and that class-A is undefined in the current local environment; then when the test is over, class-B is undefined in the global environment, and class-A is still defined (without any alteration).
This way would be the best for my use :
(let ((*all-my-classes* nil))
(class-let ((class-A nil) ; or a way to map to a pre-defined
(class-B nil)) ; empty class temporarily.
(my-macro false)
(and
;; assert that the class is added to the list
(eql (length *all-my-classes*) 1)
;; assert that class-A is not defined
(null (find-class 'class-A))
;; assert that class-B is defined
(find-class 'class-B))))
I've searched to see if I can undefine a class, but it seems to be complex and implementation-dependent. And I want to preserve the current environment.
Restarting LISP each time for each tests is too long, and I would prefer a solution without having to load-unload packages for each tests (I don't know if it could work and if the classes will be garbage-collected when unloading the package...).
Thank you for your answers.
I do not think so.
The mechanism of how classes are stored is completely implementation defined, they just need to conform to the MOP (at least as far as it is mandated by the standard). However, the MOP does not prescribe anything that would make the classes registry dynamic. In fact, types and class names are specified to be part of the global environment (CLHS ch. 3.1.1.1), so it would be difficult for a conforming implementation to get dynamic here.
As you wrote, there is also no specified way to get rid of a class once defined.
As a rationale, I think that without this it would be very difficult to provide the kind of optimized runtime that the existing implementations have. Class lookup needs to be fast.
Now, to get to the meta question: what are you trying to do? Usually, while code is data, you should not confuse program logic with the programmed logic. What you propose looks like it might be intended to have code represent data. I'd advise to think about a clean separation and orthogonal representation.

Accessing structure fields from the structure itself in Common LISP

For my project, I specifically need a structure that has (among other things) 2 slots:
one holds data (current-state, a structure)
one holds a function (is-state-a-solution)
That function slot must evaluate the current-state and return a result based on it. However, I can't find how to do this properly. Here's a segment of my code.
(defstruct state moves-left)
(defstruct problem
(current-state)
(solution (function (lambda () (null (state-moves-left :current-state)))))
)
No errors on compiling, but they happen when I interpret this:
> (setq p0 (make-problem :current-state (make-state)))
> (funcall (problem-solution p0))
SYSTEM::%STRUCTURE-REF: :CURRENT-STATE is not a structure of type STATE
Anyone knows how to solve this? I usually just use common functions, but these structure and slots are hard requirements.
EDIT: thanks for the answers. After learning this was impossible, I reread the requirements more thoroughly and posted the answer here.
You could have a separate create function:
(defun create-problem (state)
(let ((problem (make-problem :current-state state)))
(setf (problem-solution problem)
(lambda ()
(null (state-moves-left (problem-current-state problem)))))
problem))
But: Why not use a function/method directly?
(defmethod problem-solution ((p problem))
(null (state-moves-left (problem-current-state p))))
The reason for the error is that structures in Common Lisp cannot be used as classes: inside the function default value of the slot solution there is no way of referring to the slots of the structure itself (as you are trying to do with (state-moves-left :current-state).
If you insist in using structures instead of classes, one possibility is to define the function with a parameter, and pass the structure itself when the function is called. Something like:
(defstruct problem
(current-state)
(solution (function (lambda (p) (null (state-moves-left p))))))
(let ((p0 (make-problem :current-state (make-state))))
(funcall (problem-solution p0) p0))
After learning this was impossible, I reread the requirements more thoroughly and found out this function will actually receive an argument (a state). So, the code now works:
(defstruct problem
(current-state)
(solution (function (lambda (state) (not (null (state-moves-left state))))))
)

Intercept and modify user input in Common Lisp

I defined an evaluator in common lisp that can simply be called like:
(repl)
From then on, the repl can interpret function calls like (.cos arg) that are otherwise unknown to lisp.
Ofcourse, to use it, one has to call (repl) first, or lisp doesn't know what .cos is.
I would like to be able to simply call (.cos 90) though, and have it run in the repl. Is there anyway to use lisp's reflection to intercept all user input and call another function before it?
Thanks!
The better way would be to make my-eval, then you can do
(defun my-cos (arg)
(my-eval (list '.cos arg)))
repl would be something like
(defun my-repl ()
(my-eval '((lambda (ev)
(ev ev))
(lambda (ev)
(print (eval (read)))
(ev ev)))))
I assume you have print, eval and read defined in your evaluators null environment.

Unbound variable in Common Lisp

I'm new to Lisp and I was reading about an text-generator example in ANSI Common Lisp, Chapter 8. I follow the example and defined a function "see" in the scope of a LET variable "prec",
(let ((prec '|.|))
(defun see (symb)
(let ((pair (assoc symb (gethash prev *words*))))
(if (null pair)
(push (cons symb 1) (gethash prev *words*))
(incf (cdr pair))))
(setf prev symb)))
and saved it into a lisp file.
Then when I returned to REPL and tried to invoke see after loading the compiled version of the file, an error occurred:
The variable PREV is unbound.
[Condition of type UNBOUND-VARIABLE]
How do I invoke see properly? And what's a lexical closure for? I'm all confused.
Thanks for helping.
Looks like you've typed prec instead of prev in the enclosing let form.
Lexical closures are functions that 'close over' a part of the lexical environment (hence the name). There are many good introductions to closures in lisp that I will not attempt to repeat here but, essentially, let is the most common way to manipulate the lexical environment; in this case, you want to add the binding for prev, which will then be available to code within the body of the form. Your function see will 'close over' this binding, and so each call to see has access to it, even though when you make these calls, you will no longer be in the lexical environment established by the let form. You could say the function definition takes the binding with it, in a sense.
As you appear to have mis-typed the name of the prev, your function is trying to refer to a binding that has not been established at that point in the code.

Optional Arguments in defgeneric?

I'm writing some methods to emit HTML for various elements. Each method has the same output, but doesn't necessarily need the same input.
The method for echoing a game-board needs to take a player as well (because each player only sees their own pieces)
(defmethod echo ((board game-board) (p player)) ... )
Echoing a board space doesn't require changing per player (that dispatch is actually done in the game-board method, which later calls echo on a space). Ideally, I'd be able to do
(defmethod echo ((space board-space)) ... )
(defmethod echo ((space empty-space)) ... )
It's also conceivable that I later run into an object that will need to know more than just the player in order to display itself properly. Since there are already methods specializing on the same generic, though, that would give the error
The generic function #<STANDARD-GENERIC-FUNCTION ECHO (4)> takes 2 required arguments;
It seems less than ideal to go back and name these methods echo-space, echo-board and so on.
Is there a canonical way of varying other arguments based on the specialized object? Should I do something like
(defgeneric echo (thing &key player ...) ...)
or
(defgeneric echo (thing &rest other-args) ...)
? More generally, can anyone point me to a decent tutorial on defgeneric specifically? (I've read the relevant PCL chapters and some CLOS tutorials, but they don't cover the situation I'm asking about here).
Generally speaking if interfaces of two functions are too different it indicates that they are not actually a specializations of the same operation and should not have the same name. If you only want to specialize on optional/key arguments the way to achieve that is to use a normal function which calls a generic function and provides it with default values for missing arguments to specialize on.
Keene's book is, I believe, the most comprehensive guide to CLOS. Unfortunately it seems to be available only in book form.
It's easier whenever the methods take the same parameters but only differ on the data type. But in cases where the generic function and methods all use the same name (of course) yet have lambda lists that vary significantly, I personally tend to use &key parameters to make my intentions explicit, rather than using &optional parameters. I think it helps with readability later.
Try something like this (pretending we already have classes class-a and class-b):
(defgeneric foo (object &key &allow-other-keys)
(:documentation "The generic function. Here is where the docstring is defined."))
(defmethod foo ((object class-a) &key &allow-other-keys)
(print "Code goes here. We dispatched based on type Class A."))
(defmethod foo ((object class-b) &key (x 1) (y 2) &allow-other-keys)
(print "Code goes here. We dispatched based on type Class B. We have args X and Y."))
Since "method combination" is involved, in order for the dispatching logic to "flow" through its possible choices of methods to use, we need to think of the method definitions somewhat like a chain where incompatible lambda lists (i.e. parameter lists) will break that chain. That's why there's the &key and &allow-other-keys in the method definitions that don't specifically need them. Putting them in DEFGENERIC and the method definitions allows us to have the method definition where we dispatch based on class-b.
DISCLAIMER: I'm a Common Lisp newbie myself, so take this with a grain of salt!
What about restructuring the objects/classes so that each object you want to echo has all required properties in its own (and inherited) slots?
That way you don't have to pass them as arguments when you call echo on the object, since what you need is already stored in the object.
Stepped in the same problem today and found a nice workaround, but it will work only if you have a fixed number of class-specified args, placed at the beginning.
The example for the single class-specific arg:
(defgeneric foo (obj &rest args))
(defmacro my-defmethod (name args code)
(let ((rst (gensym))
`(defmethod ,name (,(car args) &rest ,rst)
(apply (lambda (,(caar args) ,(cdr args)) ,code) (cons ,(caar args) ,rst)))))
(my-defmethod foo ((x class1) y z &optional a b c)
...)
(my-defmethod foo ((x class2) &key a b)
...)

Resources