Can i Un-call a function in Common Lisp - function
I'm learning defclass and defmethod and defgeneric, so I made a defclass called savings-account with a member balance.
I created a defun (shown below) to begin to alter the value of balance, but it's not finished.
(defun balance (account)
(slot-value account 'balance))
Then I decided to go with a defgeneric (below) instead.
(defgeneric balance (account))
But when I ran the defgeneric I got this error:
BALANCE already names an ordinary function or a macro.
Is there a way to un-call or undeclare balance easily so I don't have to restart my Emacs session?
You can remove a function definition (created either with defun or defgeneric) with fmakunbound.
Any self-respecting Lisp will offer you an error restart to change the definition.
Here SLIME and Clozure CL:
The function BALANCE is defined as something other than a generic function.
[Condition of type CCL::SIMPLE-PROGRAM-ERROR]
Restarts:
0: [CONTINUE] Try to remove any global non-generic function or macro definition.
1: [RETRY] Retry SLIME REPL evaluation request.
2: [*ABORT] Return to SLIME's top level.
3: [ABORT-BREAK] Reset this thread
4: [ABORT] Kill this thread
Just select the CONTINUE restart by either typing 0 in that buffer or by selecting the respective line and pressing return.
Additionally to Xach's answer, using SLIME you can just move the text cursor on the function name and type c-c c-u, which calls SLIME-UNDEFINE-FUNCTION.
Related
Emacs: how hooks work?
I had gone through a different tutorials and manuals, but still can't put a things together. As I understand, when I need to add a new function to an event while an old functional still saved, I am add a hook by calling add-hook. From the manual entry on the add-hook: FUNCTION is added (if necessary) at the beginning of the hook list unless the optional argument APPEND is non-nil So the hook is just a list of a functions. But how is this list looks like? Works? From my little research I found that every cons cell besides the car and cdr have also an invisible unmentioned slot for a function pointer(may be an index, it doesn't matter). So how can I create manually a list of a functions, and execute it? Probably with add-to-list function, but everything I tried just triggers an errors. Also in the manual mentioned: You can set a hook variable with setq like any other Lisp variable, Something is wrong here, because a pointer to a function don't get copied with setq. I.e.: (defun myfunc1 () (message "hello")) (setq onemorefunc 'myfunc1) After I execute the (onemorefunc), debugger triggers, the setq just ignores a value of the unnamed element in which the pointer stored.
To call a function that's in a variable, you have to use funcall or apply: (funcall onemorefunc) (apply onemorefunc '()) When Emacs is processing a hook variable, it iterates through the list: (do ((hooks blah-hook (cdr hooks))) ((null hooks)) (funcall (car hooks)))
In your example, your setq merely makes onemorefunc another name for myfunc1. A hook needs to be a list, and you need to add your hook function to that list using add-hook, which is a glorified version of push, not replace the list completely with your function using setq. The mention of setq has misled you, though it's clear to someone who's familiar with hooks that it is telling you something else correctly. It says you can set a hook variable -- not a hook itself -- using setq, and you can, but what it doesn't make clear is that what you have to set that hook variable to is another list (of zero or more functions) not a function. Thus, assuming my-mode-start-hook is empty to begin: (add-hook 'my-mode-start-hook #'my-func) is equivalent to: (setq my-mode-start-hook (list #'my-func)) In practice, you should always do the former, never the latter unless and until you're really sure you know what you're doing.
MATLAB Updating a global variable from one function does not get reflected in the other function
I have a function that uses a global variable and I want to change its value from another function. Even though I tried in many ways, the function that uses the value seems not getting updated with the new value of the global variable. Here's the code I'm using. calculate.m function calculateTest() global isStop; global value; value=0; while ~isStop pause(1); value = value+1 end end start.m function start() global isStop; isStop = 0; calculateTest(); end stop.m function stop() global isStop; isStop = 1; end When I call start() the value starts getting printed. But even if I call stop(), it never stops. It keeps on printing. Do you have any idea of what I am missing? (I have tried while isStop==0 as well. But the result was the same.
I think what you need is a background thread that would do the calculateTest while leaving you the possibility to run stop from a matlab script/command line. This functionality is not supported by MATLAB in the pure sense. You can sometimes implement similar things using the timer functionality. Essentially, you tell MATLAB to run a function repeatedly after some time has passed. However, MATLAB is running the timer function in the foreground. And while it is doing that you can not run your stop script. So you can not implement a long loop in the timer function. timer is only good to schedule some tasks to be executed by MATLAB every now and then, but does not implement threading. You could implement your own background thread using a MEX function. You could then call the MEX function to pass 'start'/'stop' commands to your thread. But the MEX thread would have to do the data processing inside. You can not e.g. call some matlab script to do the job. Another thing. start and stop are MATLAB functions that manage the timer. Do not use those identifiers as names of your own functions - that is allowed, but considered a bad practice.
You haven't actually called the stop function anywhere in your code, so there is no opportunity for it to update the global variable. You could, for example, modify calculateTest() by adding a conditional test which calls the stop function when "value" reaches a certain number, such as 5:- function calculateTest() global isStop; global value; value=0; while ~isStop pause(1); value = value+1 if value == 5 stop; end end end You will find that this stops it perfectly well. If you added the stop command into start instead, after CalculateTest, that will not work because the flow of control never reaches that line - it remains on CalculateTest until that function is terminated.
AllegroServe Exception Handling
How can I avoid getting an error when passing as argument to the function do-http-request an invalid host. Is there any way that I can catch the error like the Java's exception-handling mechanism ?
Sure, CL has a very nice condition system. One easy option would be wrapping the call to do-http-request in ignore-errors, which returns nil (and the condition as a second value) if an error condition was signalled in the wrapped code. You could then check for nil afterwards. If you want something more like exception handling in Java, just use handler-case and add an appropriate error clause (I don't have AllegroServe installed, but I suppose you get a socket-error for providing a wrong URL – just change that part if I misread): (handler-case (do-http-request …) (socket-error () …)) If you need finally-like functionality, use unwind-protect: (unwind-protect (handler-case (do-http-request …) (socket-error (condition) ; bind the signalled condition …) ; code to run when a socket-error was signalled (:no-error (value) ; bind the returned value …)) ; code to run when no condition was signalled …) ; cleanup code (finally) You can even get more fancy, and e.g. use handler-bind to handle the condition stack upwards by invoking a restart somewhere down the stack, without unwinding it. For example, if do-http-request provided a restart to try again with another URL, you could handle your error condition by invoking that restart with a new URL to retry. I just mention this for the sake of completeness – it would be overkill for your use case, but being able to resume (possibly expensive) computations easily can be a rather convenient feature.
Embedded ECL Lisp error handling fetch default error string and possibly line number
Please see #7755661 first. I am using ECL and basically want to execute some code, trap any kind of condition that may occur and then continue execution, without prompting or entering the debugger. This is easy to achieve with the following handler-case macro: (handler-case (load "code.lisp") ; this may raise a condition (error (condition) (print condition))) ; this prints sth like #<a UNBOUND-VARIABLE> My only problem is that I cannot find a generic way to print a more meaningful error for the user. Indeed my application is an HTTP server and the output goes to a web page. code.lisp is written by the user and it can raise any kind of condition, I do now want to list them all in my code. I would just like to print the same error message I see on the REPL when I do not use handler-case, but in the HTML page, e.g. for an "unbound variable" error, a string like "The variable VAR is unbound". By inspecting a condition object of type UNBOUND-VARIABLE I see it has two slots: SI:REPORT-FUNCTION, which is a compiled function and SI:NAME, set to the name of the variable in this case. I guess SI:REPORT-FUNCTION could be what I need to invoke but how can I call it? If I try: (handler-case foo (error (condition) (SI::REPORT-FUNCTION condition))) it tells me that SI:REPORT-FUNCTION is undefined. SI or SYS in ECL is a package for functions and variables internal to the implementation, but I don't worry if my code is not portable, as long as it works. BTW in other kinds of condition objects there are also other apparently useful slots for my purpose, named SI:FORMAT-CONTROL and SI:FORMAT-ARGUMENT, but I cannot access any of them from my code too. I was looking for somethink alike to the getMessage() method of Java exception objects in Lisp, but none of my sources ever mentions something like that. Moreover, is there any hope to be able to get the line number in code.lisp where the error occurred too? Without that it would be difficult for the user to locate the problem in his code.lisp source file. I would really want to provide this information and stopping at the first error is acceptable for me.
In Common Lisp when print escaping is disabled, the error message is printed. CL-USER > (handler-case a (error (condition) (write condition :escape nil))) The variable A is unbound. #<UNBOUND-VARIABLE 4020059743> Note that PRINT binds *print-escape* to T. Using PRINC works - it binds *print-escape* to NIL. CL-USER > (handler-case a (error (condition) (princ condition))) The variable A is unbound. #<UNBOUND-VARIABLE 4020175C0B> This is described in CLHS 9.1.3 Printing Conditions. Also note, when you have an object, which has a slot and the value of this slot is a function, then you need to get the slot value using the function SLOT-VALUE and then use FUNCALL or APPLY and call the function with the correct arguments. If you have a condition of type simple-condition then it has a format-control and a format-argument information. This is described with an example how to use it for FORMAT in CLHS Function SIMPLE-CONDITION-FORMAT-CONTROL, SIMPLE-CONDITION-FORMAT-ARGUMENTS
My answer below is based on one I already gave at the ECL mailing list. Actually I would claim that this is not an embedding problem, but a Lisp one. You want to get some information at the file position of the form which caused the error. This is not attached to a condition because conditions happen independently of whether the form evaluated was interpreted, compiled or part of a function that is already installed in the Lisp image. In other words, it is up to you to know the position of the file which is being read and do some wrapping that adds the information. The following is nonstandard and prone to change: ECL helps you by defining a variable ext::source-location when LOAD is used on a source file. This variable contains a CONS that should NEVER be changed or stored by the user, but you can get the file as (CAR EXT:*SOURCE-LOCATION*) and the file position as (CDR EXT:*SOURCE-LOCATION*). The plan is then to embed your LOAD form inside a HANDLER-BIND (defparameter *error-message* nil) (defparameter *error-tag* (cons)) (defun capture-error (condition) (setf *error* (format nil "At character ~S in file ~S an error was found:~%~A" (cdr ext:*source-location*) (car ext:*source-location*) condition))) (throw *error-tag* *error-message*)) (defun safely-load (file) (handler-bind ((serious-condition #'capture-error)) (catch *error-tag* (load file) nil))) (SAFELY-LOAD "myfile.lisp") will return either NIL or the formatted error. In any case I strongly believe that relying on LOAD for this is doomed to fail. You should create your own version of LOAD, starting from this (defun my-load (userfile) (with-open-file (stream userfile :direction :input :external-format ....whateverformat...) (loop for form = (read stream nil nil nil) while form do (eval-form-with-error-catching form)))) where EVAL-FORM-.... implements something like the code above. This function can be made more sophisticated and you may keep track of file positions, line numbers, etc. Your code will also be more portable this way. So please, read the ANSI Spec and learn the language. The fact that you did not know how to print readably a condition and instead tried to play with ECL internals shows that you might face further problems in the future, trying to go with non-portable solutions (hidden slot names, report functions, etc) instead of first trying the standard way.
'Invalid Handle object' when using a timer inside a function in MatLab
I am using a script in MatLab that works perfectly fine by itself, but I need to make a function out of it. The script read a .csv file, extract all values, start a timer, and at each tick displays the corresponding coordinates extracted from the .csv, resulting in a 3D animation of my graph. What I would like is to give it the location of the .csv, so that it starts displaying the graphs for this csv. Here is what I have come up with: function handFig(fileLoc) csv=csvread(fileLoc,1,0); both = csv(:,2:19); ax=axes; set(ax,'NextPlot','replacechildren'); Dt=0.1; %sampling period in secs k=1; hp1=text(both(k,1),both(k,2),both(k,3),'thumb'); %get handle to dot object hold on; hp2=text(both(k,4),both(k,5),both(k,6),'index'); hp3=text(both(k,7),both(k,8),both(k,9),'middle'); hp4=text(both(k,10),both(k,11),both(k,12),'ring'); hp5=text(both(k,13),both(k,14),both(k,15),'pinky'); hp6=text(both(k,16),both(k,17),both(k,18),'HAND'); L1=plot3([both(k,1),both(k,16)],[both(k,2),both(k,17)],[both(k,3),both(k,18)]); L2=plot3([both(k,4),both(k,16)],[both(k,5),both(k,17)],[both(k,6),both(k,18)]); L3=plot3([both(k,7),both(k,16)],[both(k,8),both(k,17)],[both(k,9),both(k,18)]); L4=plot3([both(k,10),both(k,16)],[both(k,11),both(k,17)],[both(k,12),both(k,18)]); L5=plot3([both(k,13),both(k,16)],[both(k,14),both(k,17)],[both(k,15),both(k,18)]); hold off; t1=timer('TimerFcn','k=doPlot(hp1,hp2,hp3,hp4,hp5,hp6,L1,L2,L3,L4,L5,both,t1,k)','Period', Dt,'ExecutionMode','fixedRate'); start(t1); end And the doplot function used: function k=doPlot(hp1,hp2,hp3,hp4,hp5,hp6,L1,L2,L3,L4,L5,pos,t1,k) k=k+1; if k<5000%length(pos) set(hp1,'pos',[pos(k,1),pos(k,2),pos(k,3)]); axis([0 255 0 255 0 255]); set(hp2,'pos',[pos(k,4),pos(k,5),pos(k,6)]); set(hp3,'pos',[pos(k,7),pos(k,8),pos(k,9)]); set(hp4,'pos',[pos(k,10),pos(k,11),pos(k,12)]); set(hp5,'pos',[pos(k,13),pos(k,14),pos(k,15)]); set(hp6,'pos',[pos(k,16),pos(k,17),pos(k,18)]); set(L1,'XData',[pos(k,1),pos(k,16)],'YData',[pos(k,2),pos(k,17)],'ZData',[pos(k,3),pos(k,18)]); set(L2,'XData',[pos(k,4),pos(k,16)],'YData',[pos(k,5),pos(k,17)],'ZData',[pos(k,6),pos(k,18)]); set(L3,'XData',[pos(k,7),pos(k,16)],'YData',[pos(k,8),pos(k,17)],'ZData',[pos(k,9),pos(k,18)]); set(L4,'XData',[pos(k,10),pos(k,16)],'YData',[pos(k,11),pos(k,17)],'ZData',[pos(k,12),pos(k,18)]); set(L5,'XData',[pos(k,13),pos(k,16)],'YData',[pos(k,14),pos(k,17)],'ZData',[pos(k,15),pos(k,18)]); else k=1; set(hp1,'pos',[pos(k,1),pos(k,2),pos(k,3)]); axis([0 255 0 255 0 255]); set(hp2,'pos',[pos(k,4),pos(k,5),pos(k,6)]); set(hp3,'pos',[pos(k,7),pos(k,8),pos(k,9)]); set(hp4,'pos',[pos(k,10),pos(k,11),pos(k,12)]); set(hp5,'pos',[pos(k,13),pos(k,14),pos(k,15)]); set(hp6,'pos',[pos(k,16),pos(k,17),pos(k,18)]); end However, when I run handFig('fileName.csv'), I obtain the same error everytime: ??? Error while evaluating TimerFcn for timer 'timer-7' Invalid handle object. I figured that it might come from the function trying to create a new 'csv' and 'both' everytime, so I tried removing them, and feeding the function the data directly, without results. What is exactly the problem? Is there a solution? Thanks a lot!
I think it's because when you call doPlot in the timer for the first time, you pass in t1 as an argument, and it might not exist the first time. Does doPlot need t1 at all? I'd suggest modifying it so it's not used, and then your call to: t1=timer('TimerFcn','k=doPlot(hp1,hp2,hp3,hp4,hp5,hp6,L1,L2,L3,L4,L5,both,k)','Period', Dt,'ExecutionMode','fixedRate'); Note the missing t1 in the doPlot call. Either that, or initialise your t1 before you create the timer so it has some value to pass in. Update (as an aside, can you use pause(Dct) in a loop instead? seems easier) Actually, now I think it's a problem of scope. It took a bit of digging to get to this, but looking at the Matlab documentation for function callbacks, it says: When MATLAB evaluates function handles, the same variables are in scope as when the function handle was created. (In contrast, callbacks specified as strings are evaluated in the base workspace.) You currently give your TimerFcn argument as a string, so k=doPlot(...) is evaluated in the base workspace. If you were to go to the matlab prompt, run handFig, and then type h1, you'd get an error because h1 is not available in the global workspace -- it's hidden inside handFig. That's the problem you're running into. However, the workaround is to specify your function as a function handle rather than a string (it says function handles are evaluated in the scope in which they are created, ie within handFig). Function handles to TimerFcn have to have two arguments obj and event (see Creating Callback Functions). Also, that help file says you have to put doPlot in its own m-file to have it not evaluate in the base Matlab workspace. In addition to these two required input arguments, your callback function can accept application-specific arguments. To receive these input arguments, you must use a cell array when specifying the name of the function as the value of a callback property. For more information, see Specifying the Value of Callback Function Properties. It goes through an example of what you have to do to get this working. Something like: % create timer t = timer('Period', Dt,'ExecutionMode','fixedRate'); % attach `k` to t so it can be accessed within doPlot set(t,'UserData',k); % specify TimerFcn and its extra arguments: t.TimerFcn = { #doPlot, hp1, hp2, hp3, ...., both }; start(t) Note -- the reason k is set in UserData is because it needs to be somehow saved and modified between calls to doPlot. Then modify your doPlot to have two arguments at the beginning (which aren't used), and not accept the k argument. To extract k you do get(timer_obj,'UserData') from within doPlot: function k=doPlot(timer_obj, event, hp1,hp2,hp3,.....) k = get(timer_obj,'UserData'); .... % rest of code here. % save back k so it's changed for next time! set(timer_obj,'UserData',k); I think that's on the right track - play around with it. I'd highly recommend the mathworks forums for this sort of thing too, those people are whizzes. This thread from the mathworks forum was what got me started and might prove helpful to you. Good luck!