Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Clojure macros different from C macros?

Tags:

clojure

I am new to Clojure. I started couple of months ago. I am trying to learn Macros.

I initially got confused understanding difference between macros and higher-order functions in Clojure as a higher order function could take lambdas and execute one of them how many times it wanted based on any conditions and filter.

So I posted a question with a simple example regarding this on StackOverflow itself. I got my doubts cleared from the answer.

This is what I understood,

  • Macros won't evaluate all the arguments unlike functions to evaluate the body.
  • Macros can be selective about what to evaluate and what not and how to convert one piece of code into another using quote,unquote and splicing syntax.
  • The final code that comes out of the macro is then evaluated.

So my question is, How is it different from preprocessor directives and macros used in C ? What power does Lisp/Clojure macros give to the developers which C macros completely lack and are often used widely.

like image 803
Amogh Talpallikar Avatar asked Jul 08 '13 12:07

Amogh Talpallikar


People also ask

What are Clojure macros?

Clojure has a programmatic macro system which allows the compiler to be extended by user code. Macros can be used to define syntactic constructs which would require primitives or built-in support in other languages. Many core constructs of Clojure are not, in fact, primitives, but are normal macros.

What is a reader macro?

Reader macros run during reading, prior to evaluation, are single characters, operate on a character string, prior to all the lisp objects being emitted from the reader, and are not restricted to being in the first, or "function", part of a form.


1 Answers

C macros are purely textual rewriting macros. There's nothing terribly C about them aside from that being where they came from – you can use the C preprocessor cpp(1) on any text. Consequently, it's easy to generate non-C forms using the C preprocessor, and you often have to jump through hoops to do fairly trivial things as far as C itself goes. C macros are full of pitfalls because of this.

Clojure macros are Clojure code that executes using a different set of rules than regular Clojure functions. Instead of receiving evaluated arguments and returning a result, they receive unevaluated forms and return a form, which might eventually be evaluated during the course of normal execution.

like image 190
Jeremy W. Sherman Avatar answered Sep 22 '22 18:09

Jeremy W. Sherman