Menu
  • HOME
  • TAGS

Is evaluating of constructed evaluation equal to macro?

Tag: macros,lisp,common-lisp,evaluation

I want to know if these two definitions of nth are equal:

I. is defined as macro:

(defmacro -nth (n lst)
  (defun f (n1 lst1)
    (cond ((eql n1 0) lst1)
      (t `(cdr ,(f (- n1 1) lst1)))))
  `(car ,(f n lst)))

II. is defined as a bunch of functions:

(defun f (n lst)
  (cond ((eql n 0) lst)
        (t `(cdr ,(f (- n 1) lst)))))
(defun f1 (n lst)
  `(car ,(f n `',lst)))
(defun --nth (n lst)
  (eval (f1 n lst)))

Am i get the right idea? Is macro definition is evaluating of expression, constructed in its body?

Best How To :

OK, let start from the beginning.

Macro is used to create new forms that usually depend on macro's input. Before code is complied or evaluated, macro has to be expanded. Expansion of a macro is a process that takes place before evaluation of form where it is used. Result of such expansion is usually a lisp form.

So inside a macro here are a several levels of code.

  • Not quoted code will be evaluated during macroexpansion (not at run-time!), in your example you define function f when macro is expanded (for what?);
  • Next here is quoted (with usual quote or backquote or even nested backquotes) code that will become part of macroexpansion result (in its literal form); you can control what part of code will be evaluated during macroexpansion and what will stay intact (quoted, partially or completely). This allows one to construct anything before it will be executed.

Another feature of macro is that it does not evaluate its parameters before expansion, while function does. To give you picture of what is a macro, see this (just first thing that came to mind):

(defmacro aif (test then &optional else)
  `(let ((it ,test))
     (if it ,then ,else)))

You can use it like this:

CL-USER> (defparameter *x* '((a . 1) (b . 2) (c . 3) (d . 4)))
*X*
CL-USER> (aif (find 'c *x* :key #'car) (1+ (cdr it)) 0)
4

This macro creates useful lexical binding, capturing variable it. After checking of a condition, you don't have to recalculate result, it's accessible in forms 'then' and 'else'. It's impossible to do with just a function, it has introduced new control construction in language. But macro is not just about creating lexical environments.

Macro is a powerful tool. It's impossible to fully describe what you can do with it, because you can do everything. But nth is not something you need a macro for. To construct a clone of nth you can try to write a recursive function.

It's important to note that LISP macro is most powerful thing in the programming world and LISP is the only language that has this power ;-)

To inspire you, I would recommend this article: http://www.paulgraham.com/avg.html

To master macro, begin with something like this:

http://www.gigamonkeys.com/book/macros-defining-your-own.html

Then may be Paul Graham's "On Lisp", then "Let Over Lambda".

in clojure, function argument type mismatch

clojure,functional-programming,lisp

You are misunderstanding the format of a function definition. In your function, the single argument 'colors' is untyped and can be anything. The square brackets are used to denote the beginning and end of the arguments list (i.e. the symbols for the arguments are wrapped in a vector to distinguish...

How to control C Macro Precedence

c,macros

You can redirect the JOIN operation to another macro, which then does the actual pasting, in order to enforce expansion of its arguments: #define VAL1CHK 20 #define NUM 1 #define JOIN1(A, B, C) A##B##C #define JOIN(A, B, C) JOIN1(A, B, C) int x = JOIN(VAL,NUM,CHK); This technique is often used...

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

macros,julia-lang

The input expression to the macro needs to be quoted because a macro returns an expression, which are evaluated, while you would like to get the expression itself, hence you need an extra quoting. The quoting can be done as: macro mymacro(ex) Expr(:quote,ex) # this creates an expression that looks...

Accessing argument's metadata in Clojure macro

clojure,macros

I ended up finding a solution: (def ^{:a :b} my-var) (defmacro my-macro [s] (prn (meta (resolve s)))) (my-macro my-var) ;; Prints {:a :b, :name my-var, ...} So the key part here is to use resolve function to get the var associated to the symbol....

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

c++,c,macros

Defining identifiers (functions, objects) is something that happens after the preprocessing, so you can not possibly determine during preprocessing whether a function will be defined later. What you can do as workaround is that you always define a macro alongside with the function: void A(); #define A_SUPPLIED and then test...

C++ / C #define macro calculation

c++,c,macros

Are DETUNE1 and DETUNE2 calculated every time it is called? Very unlikely. Because you are calling sqrt with constants, most compilers would optimize the call to the sqrt functions and replace it with a constant value. GCC does that at -O1. So does clang. (See live). In the general...

Python-like C++ decorators

python,c++,function,macros,decorator

std::function provides most of the building blocks for my proposed solution. Here is my proposed solution. #include <iostream> #include <functional> //------------------------------- // BEGIN decorator implementation //------------------------------- template <class> struct Decorator; template <class R, class... Args> struct Decorator<R(Args ...)> { Decorator(std::function<R(Args ...)> f) : f_(f) {} R operator()(Args ... args) {...

Understanding NASM Macro

assembly,macros,ffmpeg,nasm

The DEFINE_ARGS macro defines a number single line macros the are meant to be used to refer to the arguments of the function that the cglobal macro introduces. So for example, if foo is given as the name of the first argument then DEFINE_ARGS creates the following defines: %xdefine fooq...

syntax error : missing ')' before 'constant'

c,compiler-errors,macros,syntax-error,c-preprocessor

#define is a preprocessor MACRO which acts as a textual replacement in the preprocesssing stage. In your case, with a MACRO like #define N 10 and then with a function like void displayMatrix(int *arr,int M, int N); it turns out to be void displayMatrix(int *arr,int M, int 10); //note the...

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

xml,xpath,macros,xquery

XQuery does not know such macros, you could of course use any preprocessor to do such things. But I'd rather define a function for this: declare function local:outward($context as item()) { $context/ancestor-or-self::* }; Functions can also be applied in axis steps (remember to pass the current context .): let $xml...

EVAL/APPLY: too many arguments given to F

lisp,common-lisp,clisp

This better formatting should make it easy to spot the error: (defun f (l) (cond ((null l) nil) ((listp (car l)) (append (f (car l))) (f (cdr l) (car (f (car l))))) (t (list (car l))))) If that does not help, use SBCL to compile the function. It will give...

Common Lisp Object System method execution order

lisp,common-lisp,clos

When you don't have any around methods, the order of method application is: all before methods from most specific to least specific, then the most specific primary method, and then the after methods from least specific to most specific. In your case you have two primary methods (methods without :before...

defining recursive values C

c,macros

The first is a macro with one parameter. When the pre-processor sees BLOCK_OFFSET(...) then it is replaced by (BASE_OFFSET+(...-1)*block_size) #define BLOCK_OFFSET(block) (BASE_OFFSET+(block-1)*block_size) The second is a usage of the macro as described above: Before pre-processing: lseek(fd, BLOCK_OFFSET(group->bg_inode_table)+(inode_no-1)*sizeof(struct ext2_inode),SEEK_SET); After pre-processing: lseek(fd, (BASE_OFFSET+(group->bg_inode_table-1)*block_size)+(inode_no-1)*sizeof(struct ext2_inode),SEEK_SET); If you use gcc you could use...

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

c++,qt,c++11,macros,qt5

You should be able to fix that problem by using: #include "ConflictHeader.h"//Include conflicted header #ifdef _c #undef _c #endif A better option might be to create a wrapper .h file fro ConflictHeader.h and use the wrappr .h file in rest of your code. ConflictHeaderW.h: #pragma once #include "ConflictHeader.h" #ifdef _c...

If strings are vectors, why are they immutable?

lisp,common-lisp

Strings are not immutable in Common Lisp, they are mutable: * is the last result from the Lisp listener CL-USER 5 > (make-string 10 :initial-element #\-) "----------" CL-USER 6 > (setf (aref * 5) #\|) #\| CL-USER 7 > ** "-----|----" CL-USER 8 > (concatenate 'string "aa" '(#\b #\b)) "aabb"...

Macro to push arguments onto stack

visual-c++,assembly,macros

If you are still interested in tricking the Visual C++ compiler you can try this code #define pushargs(...) for (unsigned int _esp; ;) _esp = varcount(), _esp =(_esp-varcount(__VA_ARGS__))>>2, pushargs_c(_esp, __VA_ARGS__ ); unsigned int __declspec(naked) __forceinline varcount(...) { __asm mov eax, esp; __asm ret; } unsigned int __declspec(naked) __forceinline pushargs_c(unsigned int...

Dose VS2010 pre-calculate preprocessor defined by #define?

c++,visual-studio-2010,macros,preprocessor

the #define will do a direct text replacement. Because of that everywhere you have PI it will get replaced with 4.0f*atan(1.0f). I would suspect the compiler would optimize this away during code generation but the only real way to know is to compile it and check the assembly. I found...

How does this code print odd and even?

c,if-statement,macros,logic

In binary any numbers LSB (Least Significant Bit) is set or 1 means the number is odd, and LSB 0 means the number is even. Lets take a look: Decimal binary 1 001 (odd) 2 010 (even) 3 011 (odd) 4 100 (even) 5 101 (odd) SO, the following line...

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

macros,weka,imagej

The Trainable Weka Segmentation plugin doesn't adhere to the macro recording conventions of ImageJ, mainly because of its complex structure. However, the correct way to interact with the plugin by macro scripting is described extensively in its documentation on the Fiji wiki. In summary, you need to something like: open("C:\\input\\test.tif");...

Parentheses and macro overloading in C++

c++,macros

Macro overloading is not possible. In your case since you don't want SOME_MACRO anymore once the SOME_MACRO(...) is defined, you may do following in the intended (header) file: #undef SOME_MACRO // hopefully it is not a standard macro! #define SOME_MACRO(...) // use __VA_ARGS__ Now in the code you can call...

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

c,loops,for-loop,macros,printf

There is no issue with the #define, there is one issue with the conditional statement in the for loop. I believe, you'er overlooking the <= operator. You need to have only < operator. Change for(i=0;i<=rows;++i) to for(i=0;i<rows;++i) That said, the recommended signature of main() is int main(void)....

Append the string provided by __FUNCTION__ macro

c++,macros

You can add an additional macro #define STRINGIZE(str) #str and use it like this: ADD_TIME_ENTRY(__FUNCTION__ STRINGIZE(start)) Seems like __FUNCTION__ might be not a macro so it is not particularly easy to combine it with anything in such a case. In MSVC2013 it is a macro so it is easy combinable....

Split string in macro

c++,string,split,macros

You can just change your macros so that it will accept two parameters: the namespace name and the class name. Something like #define BASICTYPE_TRAITS(namespaceName, className) \ template <> \ struct DDSTraits<namespaceName::className> \ { \ using TypeSupportImpl = namespaceName::className##Impl; \ using TypeSupport_var = namespaceName::className##TypeSupport; \ }; template <typename T> struct BASICTYPE_TRAITS...

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

linux-kernel,macros,linux-device-driver,header-files,ioctl

The _IO and _IOWR (and so forth) macros are also available in user-space headers. The definitions can be pulled into both kernel-space and user-space source by #including <linux/ioctl.h> first. You should separate your kernel header files into two parts: (a) those needed only by the kernel code -- struct definitions,...

create a macro in sas

macros,sas

proc summary allows you to control exactly which ways you want to cross the data. %macro report(year); proc import datafile="/path/to/report-&year..xls" out= salary_data dbms=csv replace ; proc summary data = salary_data; class married gender; types married gender married*gender; var sal; output out = salary_results mean(sal) = mean_salary std(sal) = std_salary; *...

Extract Argument from C Macro

c,macros,arguments,c-preprocessor

Do not use macros for this. If you must, the following will work by throwing away the left part first so just the number remains. Use with care. No guarantees. #define PIN_ALARM GPIOC,14 #define RIGHTPART_ONLY(a,b) b #define PIN_MODE_OUTPUT(a) RIGHTPART_ONLY(a) #define RESULT PIN_MODE_OUTPUT(PIN_ALARM) int main (void) { printf ("we'll pick ......

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

c++,macros,preprocessor

The preprocessor concatenates all included source files together in order. If you don't undefine a macro, it can apply to any source following where it was first defined. Since headers are often the public API of a library, any macros you define in your headers could end up in someone...

SAS Concatenate Multiple Variables to Create Data-Driven Macro Statements

sql,macros,sas,append,concatenation

Answered my own question. This does what I need: DATA TEST1; SET TEST; STRING=COMPRESS(%NRSTR("%APPEND""("||COMPRESS(YEAR)||","||COMPRESS(CONDITION)||","|| COMPRESS(QRTS)||","|| COMPRESS(SAMPLE)||")"),""""); RUN; %APPEND can then be replaced by any macro name created, so this could be very useful. ...

Defining macro function from makefile

c++,c,makefile,macros

You can insert a header from the command line to all sources by adding this to the CXX flags: -include "path/to/header.h" EDIT: In your particular case you could also pass this to the CXX flags to make a macro function: -D'dbg_print(...)=printf(__VA_ARGS__)' on windows it worked for me with " and...

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

macros,common-lisp

If you set non-terminating-p to t the macro character can appear unescaped within a symbol name (like # in the symbol foo#baz). If you leave it nil and the reader encounters the macro character while accumulating a symbol it terminates the collection of the symbol (like ' in foo'bar, which...

Backquote String Interpolation

macros,lisp,common-lisp

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

Exceed evaluation depth when forward function in Emacs Lisp

emacs,lisp,elisp

How about using lexical-let to penetrate the lambda? Is the correct answer 100? (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (lexical-let ((func func)) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index)))))) (defun test/enumerate-multiplied-indicies () (lexical-let ((sum 0))...

Writing a `define-let` macro, with hygiene

macros,racket,define-syntax,hygiene

Following the cue "syntax-parameter" from Chris, here is an one solution: #lang racket (require racket/stxparam (for-syntax syntax/strip-context)) (define-syntax (define-let stx1) (syntax-case stx1 () [(_ name [var expr] ...) (with-syntax ([(value ...) (generate-temporaries #'(expr ...))]) #`(begin (define-syntax-parameter var (syntax-rules ())) ... (define value expr) ... (define-syntax (name stx2) (syntax-case stx2 ()...

Structuring large Lisp applications

lisp,common-lisp,quicklisp,asdf

System For structuring large system use a system management tool. A 'free' one is ASDF. You would need a system declaration, which lists the parts of you library or application. Typically it goes into an own file. Then you load a system or compile a system. There should be tutorials...

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

macros,rust

Because macro_rules! is a bit dumber than you might expect. It does not, for example, bring imports with it when it expands something. It's best to think of macro expansion as mostly just a dumb copy+paste job. If you look at any reasonably well-written macro that depends on outside symbols,...

Read input into string in Lisp reader macro

macros,common-lisp,reader-macro

You can try to use read and then look at what it returns: (defun string-reader (stream char) (declare (ignore char)) (let ((this (let ((*readtable* (copy-readtable))) (setf (readtable-case *readtable*) :preserve) (read stream t nil t)))) (etypecase this (string this) (symbol (symbol-name this))))) (set-macro-character #\@ #'string-reader) Above would allow @This and @"This",...

Unexpected output printf statement [duplicate]

c,macros,printf,ternary-operator

k==MAX(i++,++j); is translated to: k==(i++) > (++j) ? (i++) : (++j); /* 2 1 3 : Precedance */ In your case i = 10 and j = 5, so the comparision would be 10 v/s 6 which would be true or 1 with side effect i becomes 11 and j...

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

c,macros,ansi

Given your code and the macro above, the C preprocessor generates the following: int main() { int temp = 999; printf("\ntemp: %d", temp); { int temp = 10; } printf("\ntemp: %d", temp); } This is the code that the C compiler receives. The inner { .. } is called a...

Combining multiple template classes to one class using typedef

c++,templates,macros,typedef

In my own code I also separate the declaration from the implementation. Sometimes I just need the code to know that there exists a template, more often I want to make it very easy to see what the interfaces are. I have solved this tedious typing with macros. However, the...

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

macros,stata

Here's one approach building on your code. . sysuse auto.dta, clear (1978 Automobile Data) . quiet describe, varlist . local vars `r(varlist)' . display "vars - `vars'" vars - make price mpg rep78 headroom trunk weight length turn displacement gear_ratio foreign . lookfor "Circle" storage display value variable name type...

Invalid specialized parameter in method lambda list

lisp,common-lisp

For defun without parameters, there should be an empty parameter list, like the following: (defun yn () (let ((ht (random 2))) (if (eq ht 1) (princ heads) (princ tails)))) ...

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

list,lisp,common-lisp

Append isn't supposed to modify anything Why doesn't append affect list y? The first sentence of the documentation on append is (emphasis added): append returns a new list that is the concatenation of the copies. No one ever said that append is supposed to modify a list. You can't change...

clojure quoting inside let

clojure,macros,eval

Kevin You were close, this should do the work (basically, you should unquote the local var in the quoted statement) (let [foo 1] (eval `(print ~foo))) Also, while eval is certainly a valid language function, what is the overall goal? There may be better ways altogether. Frank...

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

c++,static,macros,singleton

The problem is that you defined TheUniverse as Universe::GetInstance();, with a semicolon. Therefore, after macros are processed, you get Universe::GetInstance();.Initialize(); which is obviously not what you want. To fix the problem simply remove the semicolon in the macro definition.

Creating a function in compile time using a bitmap like macro

c,macros

The way I would do it would be with a macro that defined all the patterns you want, combined with other macros that defined the functions or other info you need about them. So you would have something like: #define FUNCTION_PATTERNS(M) \ M(1, 0xf) \ M(2, 0x3) \ M(3, 0x9)...

Providing new version of existing macro with parameters

c++,macros,overloading

You may change your macro to return an object with operator ()(const std::string&), something like: struct Logger2 { explicit Logger2(const std::string& name) : name(name) {} Logger2& operator << (const std::pair<const char*, const char*>& p) { std::cout << name << ":" << p.first << " " << p.second << std::endl; return...

x-macro conditional error - number comparison

c,macros,x-macros

Yes, here's a proof of concept: #pragma push_macro("X") #undef X #define X(a,b) typedef int x[(a>b)?-1:1]; LIST #pragma pop_macro("X") So, we define X to define a type of array of ints, with either -1 or 1, depending whether a is greater than b. If it is, the array of -1 elements...

Can I create a macro that unrolls loops?

macros,rust

Well, sort of. macro_rules! unroll { (0, |$i:ident| $s:stmt) => {}; (1, |$i:ident| $s:stmt) => {{ let $i: usize = 0; $s; }}; (2, |$i:ident| $s:stmt) => {{ unroll!(1, |$i| $s); let $i: usize = 1; $s; }}; (3, |$i:ident| $s:stmt) => {{ unroll!(2, |$i| $s); let $i: usize =...

how to apply macro on list of lines with vim

linux,vim,macros

If those lines have something in common, you can use the :global and :normal commands: :g/foo/norm! @1 which is slightly "smarter" but probably a bit less intuitive than: [email protected] [email protected] [email protected] See :help :global and :help :normal....