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))))))
)
Related
This question is somewhat related to an earlier one on programmatically generating symbol macros. I'm using that function in a convenience macro that throws undefined variable warnings. This macro and function:
(defmacro define-data (d body &optional doc)
(if (and doc (not (stringp doc))) (error "Documentation is not a string"))
`(let* ((d-str (string ',d))
(old-package *package*)
(*package* (if (find-package d-str) ;exists?
(find-package d-str) ;yes, return it
(make-package d-str)))) ;no, make it
;; Should we have an eval-when (:compile-toplevel) here?
(defparameter ,d ,body ,doc)
(export ',d old-package)
(define-column-names ,d)))
(defun define-column-names (d)
(maphash #'(lambda (key index)
(eval `(cl:define-symbol-macro ,key (cl:aref (columns ,d) ,index))))
(ordered-keys-table (slot-value d 'ordered-keys))))
are intended to be like defparameter, but additionally set up a few niceties for the user by defining:
a package with the name of d
a parameter in the current package with the data that will be sucked in by body
symbol-macros in package d for access to the individual data vectors
If I use defparameter from the REPL, and then call define-column-names, all is well. However when using the macro I get:
; in: DEFINE-COLUMN-NAMES FOO
; (DEFINE-COLUMN-NAMES CL-USER::FOO)
;
; caught WARNING:
; undefined variable: CL-USER::FOO
I suspect that this is because the compiler has no way of knowing that FOO will actually be defined when define-symbol-macro is called. Everything works fine, but I don't want the warning to frighten users, so am thinking of suppressing it. I hate suppressing warnings though, so thought I'd come here for a second opinion.
EDIT: I've marked an answer correct because it does correctly answer the question as asked. For an answer to the problem see my comments.
My answer to the 'when to muffle warnings' question in the title is: if it's your own code then never, under any circumstances. If it is someone else's code, then rewrite it not to warn unless you can't.
As to solving the problem I haven't thought about this hard enough, but the problem is that you definitely want the defparameter to be at top-level so the compiler can see it, and it can't really be if it's inside a let. But you can raise it to toplevel trivially since it depends on nothing inside the let.
I am then pretty certain that you want the rest of the macro to happen at compile time, because you definitely want the symbol-macros available at compile-time. So an attempt at the first macro would be (note I've fixed the handling of the docstring: (defparameter foo 1 nil) is bad):
(defmacro define-data (d body &optional doc)
(when (and doc (not (stringp doc)))
(error "Documentation is not a string"))
`(progn
(defparameter ,d ,body ,#(if doc (list doc) '()))
(eval-when (:compile-toplevel :load-toplevel :execute)
(let* ((d-str (string ',d))
(old-package *package*)
(*package* (if (find-package d-str) ;exists?
(find-package d-str) ;yes, return it
(make-package d-str)))) ;no, make it
(export ',d old-package)
(define-column-names ,d)))))
As a side note: although I think the fact that programmatically defining symbol macros is hard because CL left that out for some reason, I think I'd personally use some other approach rather than this, because eval is just so horrid. That's just me however: if you want to do this you do need eval I think (it is very rare that this is true!).
I am not sure exactly how define-columns-names works so I replaced it with a stub function that returns d.
Note also that you can use check-type and should try not injecting symbols in generated code, this introduces potential variable capture that can be avoided with gensym.
As far as I know you cannot use eval-when as suggested by your comment (see Issue EVAL-WHEN-NON-TOP-LEVEL Writeup for details).
But I have no warning if I declare the symbol as being special around the call.
(defmacro define-data (d body &optional doc)
(check-type doc (or null string))
(check-type d symbol)
(let ((d-str (string d)))
(alexandria:with-gensyms (old-package)
`(let* ((,old-package *package*)
(*package* (if (find-package ,d-str) ;exists?
(find-package ,d-str) ;yes, return it
(make-package ,d-str)))) ;no, make it
(defparameter ,d ,body ,doc)
(export ',d ,old-package)
(locally (declare (special ,d))
(define-column-names ,d))))))
It is also a bit strange that you expand into a call to define-column-names, which in turns evaluated a form built at runtime. I think it might be possible to do all you want during macroexpansion time, but as said earlier what you are trying to do is a bit unclear to me. What I have in mind is to replace define-column-names by:
,#(expand-column-names-macros d)
... where expand-column-names-macros builds a list of define-symbol-macro forms.
So consider the following code:
(define-condition some-condition (error) nil)
(defmethod print-object ((obj some-condition) stream)
(format stream "HELLO THERE"))
(defmacro error-report-test-aux (fn-to-cause-error error-type-to-catch fn-to-handle-error expected-message)
`(let ((result-message
(handler-case (funcall ,fn-to-cause-error)
(,error-type-to-catch (e) (funcall ,fn-to-handle-error e)))))
(assert (string= result-message
,expected-message))
t))
I can use it like so:
(error-report-test-aux (lambda () (error 'some-condition))
some-condition
#'princ-to-string
"HELLO THERE")
But I wanted to make error-report-test-aux a function instead of macro, so that i can pass to it a type of condition within a variable.
To simply write defun instead of defmacro and remove backquote and commas doesn't work because handler-case is macro and it doesn't evaluate error-type-to-catch.
My question is: Is there something like handler-case that would evaluate it's arguments (specifically condition type argument)?
Yes and no :-)
No to your exact question
There is no standard function that would do what you want because catching errors requires establishing bindings and one usually want to bind constant symbols (like in let/let*) because it is easier to optimize.
You might consider creating a "universal" handler using handler-bind and then declining to handle "uninteresting" conditions (as suggested by #jkiiski in comments), but I am not sure if that fits your exact requirements (untested!):
(defun error-report-test-aux (fn-to-cause-error error-type-to-catch expected-message)
(catch 'trap
(handler-bind ((error
(lambda (condition)
(when (typep condition error-type-to-catch)
(throw 'trap (string= (princ-to-string condition)
expected-message))))))
(funcall fn-to-cause-error))))
Yes, implementation-specific
IF your implementation implements handler-case/handler-bind by binding an internal global variable, you can use progv to bind it yourself and thus implement your error-report-test-aux as a function.
This is probably not the best idea (your code becomes wedded to a specific implementation).
Yes, kinda
You can use the fact that some-condition names a CLOS class and use generic functions instead of the macro.
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.
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)
...)
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