macros,lisp,common-lisp , Backquote String Interpolation

Backquote String Interpolation


Tag: 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 work for arguments like "9:00" (without double quotes).


Lisp macros operate on arguments that have already been read by lisp's reader. Because of that a macro can't change how it's arguments are read, and if you pass an argument that will signal an error when you try to read it, e.g. 9:00 in (test 9:00), the reader signals the error before the macro even starts to run.

The reader is also customizable. Not in a way that would let you read 9:00 as "9:00" in a straightforward manner, but for example you could write a short reader macro that read @9:00 as either "9:00" or as a date object.

Edit: Something like this:

(defvar *arguments-rt* (copy-readtable ()))

(defun timestring-reader (stream char &optional count)
  (declare (ignore char count))
  (with-output-to-string (s)
    (loop repeat 4 do (write-char (read-char stream) s))))

(set-macro-character #\@ #'timestring-reader () *arguments-rt*)

(let ((*readtable* *arguments-rt*))
  (let ((args "dinner @9:00"))
    (with-input-from-string (stream args)
      (loop for arg = (read stream () ())
            while arg collect arg))))

-> (DINNER "9:00")


Split string in macro

I've a class name with its namespace, like BasicType::MyType. It's possible to create a macro that split the name and uses only the part after the scope operator (I want to create a MyType object in macro without the first part)? EDIT: I'm using a library with different classes in...

Why is it not advised to define macros in header files?

The Google C++ Style Guide guide advises that macros must not be defined in a .h (header) file. What are the cons of doing it?

Exceed evaluation depth when forward function in Emacs Lisp

Here is just a simplified code snipped I have not managed to work. I do not understand what is wrong. (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index))))) The following...

How to control C Macro Precedence

#define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); With above code my expectation was int x = 20; But i get compilation error as macro expands to int x = VALNUMCHK; // Which is undefined How to make it so that NUM is replaced first...

Parentheses and macro overloading in C++

My codebase has an existing macro: #define SOME_MACRO <macro definition> For some changes I'm making, I want to add a new version of the macro that takes an argument. #define SOME_MACRO(arg1) <macro definition> I see that this question addresses selecting from multiple argument versions of a macro. However, the SOME_MACRO...

SAS Concatenate Multiple Variables to Create Data-Driven Macro Statements

In order to keep my process data-driven, I'm trying to concatenate multiple variables, separated by comma, in order to ultimately put them in a PROC SQL list to call in multiple macro statements that would otherwise clutter my SAS pogram. Take the following sample dataset: DATA TEST; INPUT YEAR CONDITION...

Use Weka from ImageJ macro: 'path' is required but unset

I have tried Calling Weka from an ImageJ(Fiji) macro: run("Trainable Weka Segmentation", "open=C:\\input\\test.tif inputfile=C:\input\test.tif path=[Ljava.lang.String;@77e655d8"); But when I run that I get an error message: 'path' is required but unset This line is exactly the line I get when recording a macro and opening test.tif when the Trainable Weka Segmentation...

Writing a `define-let` macro, with hygiene

I'm trying to write a define-let macro in racket, which "saves" the header of a (let ((var value) ...) ...) , namely just the (var value) ... part, and allows re-using it later on. The code below works as expected: #lang racket ;; define-let allows saving the header part of...

Python-like C++ decorators

Are there ways to decorate functions or methods in C++ like in python style? @decorator def decorated(self, *args, **kwargs): pass Using macros for example: DECORATE(decorator_method) int decorated(int a, float b = 0) { return 0; } or DECORATOR_MACRO void decorated(mytype& a, mytype2* b) { } Is it possible?...

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

clojure quoting inside let

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...

How to test whether an identifier that is accessible only through a #define macro is defined?

I have a #define mapping an identifier (a function name) to a new name like this: #define A doStuff This part I cannot do anything about, I have to access "A" since the actual identifier (doStuff here) may change (and this is not under my control). Now the referenced symbol...

Julia: How do I create a macro that returns its argument?

My question is quite similar to this one, but with a difference. I want to create a macro (or whatever) that behaves this way: julia> @my-macro x + 2 :(x + 2) (note that x + 2 is not enclosed in quotes). Is there something like that in Julia? And...

EVAL/APPLY: too many arguments given to F

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...

x-macro conditional error - number comparison

I would like to generate compile time error for X-macro for all X(a, b) where a > b /* X(a, b) */ #define LIST \ X(10, 20) \ X(5, 20) \ X(30, 20) \ X(1, 20) So, generate error for X(30, 20) Is this possible in C? EDIT: example usage...

how to apply macro on list of lines with vim

let's suppose I want to apply a macro stored on register 1 on lines: 2, 5, 9 but without applying on lines in between. I saw that you can give a range but that is not what I want. I've tried some variation on :2, 5, 9 @1 without success

syntax error : missing ')' before 'constant'

I have some syntax problems that I don't know how to fix. I'm trying to build some functions to matrix, can someone help me resolve those problems? 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143: syntax error : missing ')' before 'constant' 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143:...

create a macro in sas

I have a report that is generated once a year. each report has the form of the year inside the name - report-2011.xls, report-2012.xls etc. each report contains the following vars: ID, SAL=average monthly salary of that year, Gender (0=male, 1=female), Married (0=not married, 1=married), I need to create a...

Invalid specialized parameter in method lambda list

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 does the non-terminating-p argument of set-macro-character do?

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?

Why don't I get a warning when I declare a variable with same name in a macro that already exists in a function?

Playing with a macro and thought about the following scenario. Declaring variable in a macro which already exists in function from which this macro has been called, why compiler doesn't complain. When I declare in a code a variable it give me a warning: Redefinition of 'temp' I think that...

Dose VS2010 pre-calculate preprocessor defined by #define?

For Visual Studio 2010, if I define #define PI 4.0f*atan(1.0f) when PI is used somewhere later in the code, does the value needs to be calculate again or simply 3.1415926... being plugged in? Thanks. EDIT: Because I heard someone says the compiler might optimize to replace it with 3.1415926.., depending...

Common Lisp Object System method execution order

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!"))...

Defining Macros that are equal to functions that return objects in C++

So I have the singleton pattern working the way I want to, I think the main problem is something with pointers and refrences. ("..." represents irrelevent code). Universe.h ... #define TheUniverse Universe::GetInstance (); ... public: static Universe& GetInstance (); ... private: static Universe* x_instance; ... Universe.cpp ... Universe* Universe::x_instance =...

Providing new version of existing macro with parameters

We have an existing log macro in our code. Lets call it LOG_XXX where XXX is the log level to use, such as LOG_INFO, LOG_DEBUG, LOG_ERROR etc. We stream log messages to the macro: LOG_INFO << "This is a log message."; Under the covers, the macro creates a temporary object...

Why is my C code printing out an extra line of rows?

#include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } So here is my code, what it does is it prints the number of rows set by #define and creates a right...

How does this code print odd and even?

#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

Backquote String Interpolation

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...

Why do I have to expose a macro implementation's 'use' in the client library?

I'm trying to use a macro I've created in a separate module. With reference to this SO question, I've imported a macro fine. However it seems that I have Update to add macro implementation #![macro_use] use std::fmt; use std::ffi::CString; use std::ffi::CStr; use std::str; extern crate libc; pub enum DbaxError...

Is there any way to skip macro replacement(During preprocessing) when macro is used as a variable name?

ConflictHeader.h #define _c 6 //This is third party header, canot change, since // there is no sorce code to rebuild testclass.h #ifndef TESTCLASS_H #define TESTCLASS_H #include <QObject> #include "ConflictHeader.h"//Include conflicted header class TestClass : public QObject { Q_OBJECT public: TestClass(QObject *parent); ~TestClass(); private: }; #endif // TESTCLASS_H testclass.cpp #include "testclass.h"...

defining recursive values C

#define BLOCK_OFFSET(block) (BASE_OFFSET+(block-1)*block_size) usage lseek(fd, BLOCK_OFFSET(group->bg_inode_table)+(inode_no-1)*sizeof(struct ext2_inode),SEEK_SET); This is a fragment of a code im trying to understand and I have no idea how that definition works. Is it recursive? Can someone explain step by step whats happening in that lseek?...

Can I create a macro that unrolls loops?

I'm trying to write some fast matrix code in Rust and to do this needs to ensure that loops are unrolled. Is there a way to create a compile-time for-loop? E.g: I want unroll_loop!(f, a, 3); to generate f(a, 0); f(a, 1); f(a, 2); ...

Understanding NASM Macro

I've come around this macro in a assembly source file and I just can't figure out how it's working. So first I come around this function (hevc_deblock.h): cglobal hevc_v_loop_filter_chroma_8, 3, 5, 7, pix, stride, tc, pix0, r3stride sub pixq, 2 lea r3strideq, [3*strideq] mov pix0q, pixq add pixq, r3strideq TRANSPOSE4x8B_LOAD...

Creating a function in compile time using a bitmap like macro

I have an ansi C function to sum up values from an array, based on patterns. Something like: long sum_all_according_to_pattern(int n, int *values, int *pattern) { long sum = 0; int i = 0; for(;i<n;i++){ if(pattern[i]) sum+=values[i]; } return sum; } Let's say I've a set of patterns such as:...

If strings are vectors, why are they immutable?

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?

Can I create a macro or shortuct for a step of XPath in XQuery?

Do we have Macros in XQuery? If yes, could you please give an example of their usage. I have the following code let $x := //price/ancestor::* Can I someway, using macros or other things write it as follows: let $x := //price/outward So, the outward should mean ancestor::*...

How to share same header files between kernel modules and userspace applications.

I want to implement a simple module in which an ioctl() method is used. In the kernel module, I use kernel macros, such as _IO(), _IOWR(), etc., to define my own ioctl sub-commands. In facts, I don't care the actual values of these definitions for that I will always use...

Append the string provided by __FUNCTION__ macro

I have defined a macro as following: #define ADD_TIME_ENTRY(_name_) m_pTimeMeasurement->addTimeEntry(_name_); Now, I want to pass the function name through ADD_TIME_ENTRY() in whichsoever function I put ADD_TIME_ENTRY() ADD_TIME_ENTRY(__FUNCTION__) works fine for me but now, I want to add "_start" or "_stop" at the end of the function name. I mean, I...

Read input into string in 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...

Macro to push arguments onto stack

I've been working on a fun little project to mess around with how functions are called and I need a macro to push arguments as it'll be quite time consuming to push the arguments manually for every instance of this obfuscated call. This is my code so far: #define pushargs(...)...

Combining multiple template classes to one class using typedef

I have the following piece of code. Let us have the function declaration and implementation seperate. #include <iostream> class Y1 {}; class Y2 {}; template <class T1, class T2> class A { public: explicit A(); void foo() const; int bar() const; }; template <class T1, class T2> A<T1, T2>::A() {}...

Accessing argument's metadata in Clojure macro

Is there a way to retrieve the metadata of the arguments inside a clojure macro without using eval? The only thing I could come up with so far is this: (def ^{:a :b} my-var) (defmacro my-macro [s] (prn (eval `(meta (var ~s))))) (my-macro my-var) ;; Prints {:a :b, :name my-var,...

Structuring large Lisp applications

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,...

C++ / C #define macro calculation

Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

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

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...

Extract Argument from C Macro

I have a number of definitions consisting of two comma-separated expressions, like this: #define PIN_ALARM GPIOC,14 I want to pass the second expression of those definitions (14 in the case above) to unary macros like the following: #define _PIN_MODE_OUTPUT(n) (1U << ((n) * 2U)) How can I extract the second...

Defining macro function from makefile

Suppose I have following entry in my makefile: ifeq ($(MY_DEBUG),yes) EXTRACXXFLAGS += -DMY_DEBUG=2 endif I am invoking it with make foo MY_DEBUG=yes and now I basically have #define MY_DEBUG 2 for all project files available. Question: Can I define the macro function all over the project this way, without including...

Unexpected output printf statement [duplicate]

This question already has an answer here: Why is ā€œiā€ variable getting incremented twice in my program? 8 answers Why outputs of i and j in the following two printf()s are different? #include <cstdio> #define MAX(x,y) (x)>(y)?(x):(y) int main() { int i=10,j=5,k=0; k==MAX(i++,++j); printf("%d %d %d\n",i,j,k); i=10,j=5,k=0; k=MAX(i++,++j); printf("%d...

Stata- Stopping at the variable before a specified variable in a varlist

I'm stuck on a tricky data management question, which I need to do in Stata. I'm using Stata 13.1. I have 40+ datasets I need to work on using a subset of variables that is different in each dataset. I can't include the data or specific analysis I'm doing for...