What is the purpose of macros?

My common focus here is the Scala and Lisp / Scheme macros, not the ones specified in C / C ++ / Obj-C

I just don't see the point.

The way I understand this is that macros extend the language. But also functions.

I understand that some things cannot be implemented purely due to some language restrictions, and therefore such a macro should be a way. But the many examples that I see with macros seem to be things that are pretty simple to implement using regular functions.

So what is the purpose? Pure macros or others, someone, please enlighten me. If possible, provide sample code that can be executed in macros, but with normal functions this is not possible / difficult.

+4
source share
3 answers

There is a brief overview of what has been done with Scala macros: http://scalamacros.org/paperstalks/2014-02-04-WhatAreMacrosGoodFor.pdf . To summarize, it is known that macros are good for: 1) code generation, 2) extended static checks, 3) extension of domain access rights. The presence of macros in Scala, to be type-based, provides an additional and powerful turn to the capabilities commonly found in macros in Lisp languages.

, - (, ), (, - ). , Akka , . , scala/async , API- .

, . , , , , http://scalamacros.org/paperstalks/2014-03-01-MacrosVsTypes.pdf. , , -, .

+7

Common Lisp Scheme , , .

, Scheme, CL if, cond case, if .

, , , . , .

. , with-*, , , / .

+2

, Lisp ( Scala):

  • : - . : defun, defgeneric, defclass ( ), deftable ( ).
  • Unwind-protect wrappers: . , , . : with-open-file (), with-transaction ( ).
  • : , CL-WHO (HTML), Parenscript (JavaScript). Lisp, , .

: Java 7 Closable try -:

try (SomeClosable foo = openFoo()) {
    foo.doSomething();
}

Java 6 :

SomeClosable foo;
try {
    foo = openFoo();
    foo.doSomething();
} finally {
    if (foo != null && foo.isOpen()) {
        foo.close();
    }
}

Java , . Lisp :

(defmacro with-open-foo ((var &rest options) &body body)
  `(let ((,var (open-foo ,@options)))
     (unwind-protect
         (progn ,@body)
       (when ,var (close ,var)))))

(with-open-foo (f :bar baz)
  (do-some-foo f)
  (and-something-else))

(let ((f (open-foo :bar baz)))
  (unwind-protect
      (progn
        (do-some-foo f)
        (and-something-else))
    (when f (close f))))
+1
source

All Articles