common-lisp,eval , Format both an expression and its result without eval


Format both an expression and its result without eval

Question:

Tag: common-lisp,eval

I am trying to format an arbitrary expression, say (+ 2 3), and at the same time, its result, 5.

I have the following:

(defun expr-and-result (expr)
  (format t "~a returns ~a~%" expr (eval expr)))

CL-USER> (expr-and-result '(+ 2 3))
  (+ 2 3) returns 5

Though it's a simple matter by using eval, I'm curious if this effect can be accomplished without it (because I heard a lot that eval is to be avoided).

I understand that quoting the argument is necessary, because otherwise the given expression will be evaluated as the first step in calling expr-and-result, and only its result could be used inside expr-and-result. Therefore, any possible solution requires the input to be quoted, right?

I thought a bit about macros but I feel like it's the wrong approach to what I am looking for.

Edit: My intent was to construct a simple test-suite, such as:

(progn
  (mapcar #'expr-and-result
          '((= (my-remainder 7 3) 1)
            (= (my-remainder 7 3) 2)))
  'end-of-tests)

Outputs: 
(= (MY-REMAINDER 7 3) 1) returns T
(= (MY-REMAINDER 7 3) 2) returns NIL
END-OF-TESTS

After reading Paulo's comment, it seems that eval is the shortest and cleanest solution for my purposes.


Answer:

Here is a simple macro:

(defmacro exec-and-report (form)
  `(format t "~S returns ~S~%" ',form ,form))
(macroexpand '(exec-and-report (+ 1 2)))
==>
(FORMAT T "~S returns ~S~%" '(+ 1 2) (+ 1 2)) ;
T
(exec-and-report (+ 1 2))
==>
(+ 1 2) returns 3
NIL

PS. I second @Sylvester's suggestion not to reinvent the wheel


Related:


Execute external Javascript NodeJS


javascript,node.js,buffer,eval,external
I would like to execute an JS file passed in argument in my NodeJS app (without require each others) Example : $ node myapp test.js test.js console.log("Do some work") test(); myapp.js var test = function(){ console.log("Test working"); here_execute_js_in_process.argv[2](); I tried the simplest option, read file thanks to fs.readFile and eval...

Read input into string in Lisp reader macro


macros,common-lisp,reader-macro
I am trying to make a reader macro that would convert @this into "this". This is what I currently have: (defun string-reader (stream char) (declare (ignore char)) (format nil "\"~a\"" (read-line stream t nil t)) ) (set-macro-character #\@ #'string-reader ) The problem is that this requires that I put a...

Remove quotation marks from an object


ruby,string,eval
I want to call User.first, but I get it like "User.first". How can I strip the quotation marks so I can call User? Using a regex like this: gsub!(/\A"|"\Z/, "") returns nil instead of the expression.

Is this eval() in python safe?


python,eval,code-injection
consider this code: from re import sub input = request.POST['input'] sub_pattern = {'1':"sub('pattern1','txt1',input)", '2':"sub('pattern2','txt2',input)", } eval(sub_pattern['1']) is there code-injection in this code? can you provide POC on this code injection?...

where is the text printed by C printf


io,common-lisp,cffi
I happened encounter a trouble with calling C printf function from SBCL via cffi. The problem is when I call printf function, I can't find the output text, just the return value of printf function show on the REPL. But when I quit SBCL, the output text appears on the...

clojure quoting inside let


clojure,macros,eval
Quoting (both syntax and non-syntax) seems to fail to detect vars inside a let statement: (let [foo 1] (eval `(print foo))) This will generate an error or use whatever prior value bound was bound to foo in (def foo bar). Is there a way to make the syntax quote use...

Modify list and return it inside a function in lisp


lisp,elisp,common-lisp
(defun testthis (node index newvalue) (set-nth node index newvalue) node ) I would like to modify the nth element of a list in a function and then returns this list to save the modification performed. How can I do a such function in lisp?...

EVAL/APPLY: too many arguments given to F


lisp,common-lisp,clisp
Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

Updating the window in response to CLIM frame commands


common-lisp,clim,mcclim
While trying to figure out CLIM, I ran into this example program. It's a simple maze game. The author claims to have tested it in LispWorks (and even has #+Genera in there, implying that this program would work on a real Lisp Machine), but I'm trying to get it working...

Dynamic 2d array in lisp


common-lisp,clisp
I want to have a 2D array in Lisp . But each row can have different number of elements(At max 5). So I thought of maintaining another single list to store the current sizes of each row, and update them whenever required. So, my code goes like this : (setq...

Creating A Process Queue in Common Lisp


common-lisp
I have a server running Hunchentoot (CentOS and SBCL). When a user submits a specific type of post request, a subprocess is launched (run-program) which can take up to four minutes to complete. If five people perform that specific type of request at the same time, the server runs out...

How to use FFI:def-call-in in clisp


lisp,common-lisp,ffi,clisp
I have figured out how to make use of shared objects created from C code into Clisp using FFI:def-call-out but I am not able to figure out how to use FFI:Def-call-in. I don't know the process and actually I am confused if clisp will also create some .so file that...

Is there a better alternative to eval() for my function checking algorithm


javascript,jquery,eval,jquery-mask
I have the following code below designed to check that a function exists at anytime. This code does not have any errors currently. I'm using this because my javascript files load in arbitrary orders and is necessary for my project its done that way. Since my javascript files are separated...

If strings are vectors, why are they immutable?


lisp,common-lisp
if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

Invalid specialized parameter in method lambda list


lisp,common-lisp
I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

What is an alternative to using 'eval' to accessing a variable by name to “sync” it with another?


javascript,eval
I want to keep two JavaScript variables in sync when I run a function. The variable that is to be pointed to is in an object. The code I have so far is this: var myname = "bob"; var thevar = ""; var varobj = {tvar: "myname"}; var syncvar =...

Macro that defines functions whose names are based on the macro's arguments


macros,common-lisp,symbols,sbcl
*Note: Despite having frequented StackOverflow for a long time, this is the first question that I have posted myself. Apologies if it's a bit verbose. Constructive criticism appreciated. When I define a struct in Common Lisp using defstruct, a predicate function is automatically generated that tests whether its argument is...

EMACS-Live + Slime error at startup


emacs,common-lisp,slime,kubuntu
Ok, I must be missing something obvious. I'm getting stuck since yesterday to launch Emacs-live + slime. I'm using EMACS 24.3.1, installed Emacs-live and it worked well (if I start emacs-live without Slime it works), downloaded Slime-Pack from git and added this line to .emacs-live.el (live-append-packs '(~/.live-packs/slime-pack/)) I'm on a...

Eval not working on multi-line string


python,eval
I am having issues with executing a multi-line string with the python eval function/ code = ''' def main(): print "this is a test" main() ''' eval(code) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> eval(code) File "<string>", line 3 def main(): ^ SyntaxError: invalid syntax ...

lisp: dynamic scope vs explicit parameter passing


design-patterns,coding-style,common-lisp,anti-patterns,dynamic-scope
I see two different patterns for "output" functions in (common) lisp: (defun implicit () (format t "Life? Don't talk to me about life!")) (defun explicit (stream) (format stream "This will all end in tears.")) (defun test-im-vs-ex-plicit () (values (with-output-to-string (stream) (let ((*standard-output* stream)) (implicit))) (with-output-to-string (stream) (explicit stream)))) Is using...

Is there a way to insert raw javascript in parenscript code?


common-lisp,parenscript
The following code inserts third-party generated javascript as a string which will need to be eval'ed. (ps (let ((x (lisp (json:encode-json-alist-to-string '((:a . 1) (:b . 2)))))))) "(function () { var x = '{\"a\":1,\"b\":2}'; return null; })();" Is there a way to tell parenscript to insert a string unquoted?...

Backquote String Interpolation


macros,lisp,common-lisp
Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

Common Lisp Object System method execution order


lisp,common-lisp,clos
I have the following two classes: (defclass person () ()) (defmethod speak ((s person) string) (format t "-A" string)) (defmethod speak :before ((s person) string) (print "Hello! ")) (defmethod speak :after ((s person) string) (print "Have a nice day!")) (defclass speaker (person) ()) (defmethod speak ((i speaker) string) (print "Bonjour!"))...

combine multiple expressions in R into one big expression


r,expression,eval
I am new to R expression handling. I am stuck with below problem. Any input is appreciated. I am trying to generate two individual equations and combine them into one expression and pass it to an algorithm to find optimal value. OLD_PRICE ELAST Units 1 59.98 1.3 151 2 59.98...

Insertion into a list doesn't reflect outside function whereas deletion does?


list,lisp,common-lisp
I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

Using eval() to check if global variable isset


php,eval,constants
I am trying to check defined variables based on passing a single portion of the variable. (The rest of the variable is static and all other portions of it are the same), so I made a test to find out if this is possible. It does not work, but perhaps...

What is a common-lisp analogue of python's argparse?


python,common-lisp,argparse
What is a common-lisp analogue of python's argparse library for parsing command-line arguments?

How are `tagbody` and `go` implemented under the hood in Common Lisp?


compiler-construction,common-lisp
How are tagbody and go implemented in Common Lisp? Is it some form of setjmp/longjmp or is there a more elegant way of handling this? I'm writing a lispy language implemented in C and would like to have something like this....

Parse Perl range string such as “1,4..7,10,11” [duplicate]


perl,parsing,eval
This question already has an answer here: Is there a Perl module for parsing numbers, including ranges? 1 answer Given a string such as 1,4..7,10,11, is there a neat way to parse it into the list (1,4,5,6,7,10,11)? The string is given as a command-line argument. My plan is ensure...

SBCL: Deploying Hunchentoot application as executable


common-lisp,executable,sbcl,hunchentoot
Dear StackOverflow community, I started playing with SBCL Common Lisp and want to develop a small web application using Hunchentoot. For easy deployment I planned to save everything in a binary using sb-ext:save-lisp-and-die as I can live with the big output size. For the executable you need to supply a...

sbcl run-program hang when there is large amount of output from program


common-lisp,hang,sbcl
Recently I find a run-program hang issue of sbcl 1.2.7 (32bits, linux). The code as following (progn (with-open-file (s "test.out" :direction :output :if-exists :supersede) (loop repeat 900 do (write-line (make-string 76 :initial-element #\x) s))) (run-program "/bin/bash" (list "-c" "cat test.out") :output :stream)) That is when the "cat test.out" produce many...

How to use a parameter in a macro call?


macros,lisp,common-lisp,sbcl
I have defined the following simple macro: (defmacro define-class (class-name) `(defclass ,class-name ()())) And now I want to use it in the following function: (defun create-data (mode) (define-class mode)) After compiling the last function I get the following message, the variable MODE is defined but never used. And when I...

No-argument (and) returns t


clojure,scheme,lisp,common-lisp
Both CL and Scheme define (and) to return t (or #t) with no arguments. I'm trying to understand the rationale for this. My naive assumption is that an empty set is false, and passing in zero arguments feels like passing in nothing that can be true. Edit: clojure follows the...

using Eval of ASP Listview as an inline CSS value


asp.net,listview,warnings,eval
my code is : <asp:ListView ID="lst1" runat="server"> <ItemTemplate> <div style="width:<%#Eval("Rating")%>%"> </div> </ItemTemplate> </asp:ListView> It works great, but in VisualStudio editor it's considered as invalid. Is there any way to make it valid? I know that I can create the whole ' style="width:xxx%" ' in the Eval but I'm looking for...

appending multiple similar functions to protoype


javascript,node.js,eval
I want to avoid redundant code for one of my projects, which is a simple logger. This logger needs functions like *.alert, *.notice, etc. and I also decided to assign aliases to them (.alert = .al, etc.). This leads to multiple similar functions, that only differ by one number, and...

What does the non-terminating-p argument of set-macro-character do?


macros,common-lisp
Set-macro-character has an optional argument called non-terminating-p. It seems to be used to indicate whether another character should be read after reading the macro character, but the reader algorithm seems to ignore this argument. Is there a difference whether I set it to true or false?

Emacsclient crashes when evaluating window functions


emacs,window,eval
To not bore anyone here with specifics, whenever I evaluate an expression similar to this one: emacsclient -t -e '(set-buffer *scratch*)' the client will flash up on the terminal and crash. This seems to be happening with all window-changing functions. Is the client not supposed to work like that? Running...

Get element from list of list in lisp


lisp,elisp,common-lisp
I am a beginner with lisp. I manipulate list of list: ((name1, second) (name2, second2)) The goal of my function is to get the second element of the list that have name as it first node. For example: my list is: ((name1, second1) (name2, second2)) getelement list name1 should return...

What are the limits to inheritance in ggplot2?


r,ggplot2,eval
I have been trying to work out a few things about ggplot2, and how supplemntary arguments inherit from the first part ggplot(). Specifically, if inheritance is passed on beyond the geom_*** part. I have a histogram of data: ggplot(data = faithful, aes(eruptions)) + geom_histogram() Which produces a fine chart, though...

Structuring large Lisp applications


lisp,common-lisp,quicklisp,asdf
I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...

How to move a file in Lisp using rename-file


lisp,common-lisp,pathname
What's the best way to move a file in Lisp in an implementation-independent way? For example I have an image file: (setq oldpath #P"SERVER:PICTURES;TEMP;PHOTO.PNG") and I want to move it out of the TEMP directory into the PICTURES directory. This seems to work: (setq newpath (make-pathname :host (pathname-host oldpath) :directory...

Trying to multiply all elements in a list of sublists with elements in another list in lisp


list,common-lisp
I'm trying to multiply a list with n sublists with a list with n scalars. It's supposed to work like this: (kmult-matrix '((3 4 2 4) (2 5 6 9) (1 -2 8 10)) '(2 3 5)) => ((6 8 4 8) (6 15 18 27) (5 -10 40 50))...

Running compiled lisp program with clisp-2.49 on OS X


common-lisp,clisp
I have just started out programming in Common Lisp using GNU clisp-2.49 (compiled from source) as my implementation on OS X 10.10 Yosemite. I've written a simple "Hello World" program as follows: (EXT:SAVEINITMEM "test" :INIT-FUNCTION 'main :EXECUTABLE t) (defun main () (format t "Hello World!") (EXT:EXIT)) When I run: $...

How to execute JavaScript function in an Ajax() Response


javascript,jquery,ajax,function,eval
I have a home page that load the ajax() response and post it to UL as LI content, with the same page I have script function that can select the LI content with trigger for another function, but isn’t working. PAGE 1 HTML <ul id="feature-deals" class="list-products allShopping-deals"> </ul> SCRIPT $(document).ready(function(){...

Weird non-lisp errors with capturing labels with a lambda and `reduce`


lambda,crash,closures,common-lisp,allegro-cl
I stumbled across a very weird bug (?) while I was developing an application in Allegro Common Lisp, v9.0 for Windows. I do not get the regular lisp errors, instead I get system errors encapsulated in a lisp condition. I managed to create a simple test-case to reproduce the error...

How do I best save/read data structures?


common-lisp,clos
I want to write some data structures pointed to by FOO and BAR to a file, and to read the data structures back into the symbols FOO and BAR when I start a new session of Common Lisp. It would appear *PRINT-READABLY* allows objects to be printed in a fashion...

Local dynamic binding in common lisp


closures,common-lisp,dynamic-binding
Honnestly, I'm not sure I fully understand what it means for a binding to be "dynamic" versus "lexical". But I understand that when I use defvar or defparameterto define a binding, 1. it declares a global variable 2. the binding is declared "special", so that it can be shadowed by...

Long integer to string and vice versa, operation with digits


common-lisp,sbcl
Solving the Euler project problems I get that I need to make operations with the digits of a long number normally as a string. I work in linux, emacs, slime with sbcl. For example, to get the sum of the digits of this power 2¹⁰⁰⁰, I work this way, 1)...

SBCL: Gather output of run-program process while running


subprocess,common-lisp,sbcl
Dear StackExchange members, I recently began toying around with Common Lisp and want to create a web interface for administrating a modded Minecraft server. I already tried out this solution but in this case the function just hangs and never returns. My code looks like this: (defvar *proc*) (defun create-minecraft-proc...

Char Comparison in Common Lisp


sorting,char,comparison,lisp,common-lisp
How can i compare characters with Common Lisp? I have google it and found out that there are some functions to do the comparison, like char=, char/=, char<, char>, char<=, and char>=. But, i can't use all of the functions just like: (char= 'a 'a) (char< 'a 'b) If i...