Measures Concepts
GitHub icon

Macros

Macros - language feature

< >
Example from C, C++, Objective-C, Tick C:
// https://learn.microsoft.com/en-us/cpp/preprocessor/macros-c-cpp?redirectedfrom=MSDN&view=msvc-170 // https://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html #define min(X, Y) ((X) < (Y) ? (X) : (Y)) x = min(a, b); → x = ((a) < (b) ? (a) : (b)); y = min(1, 2); → y = ((1) < (2) ? (1) : (2)); z = min(a + 28, *p); → z = ((a + 28) < (*p) ? (a + 28) : (*p));
Example from Scala:
// https://docs.scala-lang.org/scala3/guides/macros/macros.html import scala.quoted.* // imports Quotes, Expr def inspectCode(x: Expr[Any])(using Quotes): Expr[Any] = println(x.show) x
Example from Rust:
// https://doc.rust-lang.org/book/ch19-06-macros.html #[macro_export] macro_rules! vec { ( $( $x:expr ),* ) => { { let mut temp_vec = Vec::new(); $( temp_vec.push($x); )* temp_vec } }; }
Example from Julia:
# https://jkrumbiegel.com/pages/2021-06-07-macros-for-beginners/ macro show_value(variable) quote println("The ", $(string(variable)), " you passed is ", $(esc(variable))) end end @show_value(orange) @show_value(apple)
Example from Clojure:
; https://www.braveclojure.com/writing-macros/ ; https://clojure.org/reference/macros (defmacro and "Evaluates exprs one at a time, from left to right. If a form returns logical false (nil or false), and returns that value and doesn't evaluate any of the other expressions, otherwise it returns the value of the last expr. (and) returns true." {:added "1.0"} ([] true) ([x] x) ([x & next] `(let [and# ~x] (if and# (and ~@next) and#))))
Example from Prolog, CLPR, GAEA, Progol:
term_expansion(parent_child(Parent, Child), child_parent(Child, Parent)). parent_child(trevor, simon). % With the above definitions, we can query (even though the predicate child_parent/2 is nowhere explicitly defined in the code above): ?- child_parent(Child, Parent). Child = simon, Parent = trevor.
Example from Elixir:
# https://hexdocs.pm/elixir/Macro.html defmodule Example do defmacro macro_inspect(value) do IO.inspect(value) value end def fun_inspect(value) do IO.inspect(value) value end end
Example from Erlang:
-define(Const, Replacement). -define(Func(Var1,...,VarN), Replacement).
Example from Scheme:
(define-syntax backwards (syntax-rules () ((_) (syntax-error "(backwards) not allowed")) ((_ e) e) ((_ e1 ... e2) (begin e2 (backwards e1 ...)))))
Example from Racket:
; https://docs.racket-lang.org/guide/macros.html (define-syntax-rule (swap x y) (let ([tmp x]) (set! x y) (set! y tmp)))
Example from Nim:
# https://hookrace.net/blog/introduction-to-metaprogramming-in-nim/#macros import macros dumpTree: result = 10
Example from Dylan:
define macro table { table(?table-class:expression, ?table-contents) } => { let ht = make(?table-class); ?table-contents; ht; } { table(?rest:*) } => { table(<table>, ?rest); } table-contents: { } => { } { ?key:expression => ?value:expression, ... } => { ht[?key] := ?value; ... } end macro table
Example from Nemerle:
// http://nemerle.org/About def title = "Programming language authors"; def authors = ["Anders Hejlsberg", "Simon Peyton-Jones"]; // 'xml' - macro from Nemerle.Xml.Macro library which alows to inline XML literals into the nemerle-code def html = xml <# <html> <head> <title>$title</title> </head> <body> <ul $when(authors.Any())> <li $foreach(author in authors)>$author</li> </ul> </body> </html> #> Trace.Assert(html.GetType().Equals(typeof(XElement))); WriteLine(html.GetType());
Example from Arc:
; http://www.arclanguage.org/tut.txt ; We know enough now to start writing macros. Macros are basically ; functions that generate code. Of course, generating code is easy; ; just call list. ; ; arc> (list '+ 1 2) ; (+ 1 2) ; ; What macros offer is a way of getting code generated this way into ; your programs. Here's a (rather stupid) macro definition: ; ; arc> (mac foo () ; (list '+ 1 2)) ; *** redefining foo ; #3(tagged mac #<procedure>) ; ; Notice that a macro definition looks exactly like a function ; definition, but with def replaced by mac. ; ; What this macro says is that whenever the expression (foo) occurs ; in your code, it shouldn't be evaluated in the normal way like a ; function call. Instead it should be replaced by the result of ; evaluating the body of the macro definition, (list '+ 1 2). ; This is called the "expansion" of the macro call.
Example from Pike:
#define CYCLES 20
Example from C3:
macro square(x) { return x * x; }
Example from High Level Assembly:
// _SortCases_ // // This routine does a bubble sort on an array // of _caseRecord_ objects. It sorts in ascending // order using the "value" field as the key. // // This is a good old fashioned bubble sort which // turns out to be very efficient because: // // (1) The list of cases is usually quite small, and // (2) The data is usually already sorted (or mostly sorted). macro _SortCases_( ary, size ):i, bnd, didswap, temp; ?bnd := size - 1; ?didswap := true; #while( didswap ) ?didswap := false; ?i := 0; #while( i < bnd ) #if( ary[i].value > ary[i+1].value ) ?temp := ary[i]; ?ary[i] := ary[i+1]; ?ary[i+1] := temp; ?didswap := true; #endif ?i := i + 1; #endwhile ?bnd := bnd - 1; #endwhile; endmacro;
Example from Bel:
; A macro is essentially a function that generates code. I would have ; liked the first example of a macro to be something simpler, but fn ; is the one we need first. So I'll introduce macros using a simpler ; macro that isn't part of Bel, then explain fn. ; Here is a very simple macro: (mac nilwith (x) (list 'cons nil x))
Example from groff:
.de P . br . sp .8v ..
Example from YAMP:
- defmacro: name: foo args: [who] value: Hello: who - foo: who: World

Languages with Macros include C, C++, Scala, Rust, Julia, Clojure, Prolog, Objective-C, Elixir, Erlang, Scheme, Racket, Nim, Dylan, Nemerle, Arc, Factor, Pike, C3, Speedie, High Level Assembly, Slope, Bel, groff, Gerbil Scheme, CLPR, YAMP, Tick C, GAEA, honu, Progol

Languages without Macros include Java, JavaScript, Python, HTML, XML, JSON, Kotlin, TypeScript, Smalltalk, JSON5, Cython, Ion, progsbase, Pizza, JSONiq, JSON with Comments, Superjson, Jsonnet, Hocon, Oracle Java, Deesel

This question asks: Does the language have a compile-time macro pass?

Read more about Macros on the web: 1.

HTML of this page generated by Features.ts

View source

- Build the next great programming language · Search · Add Language · Features · Creators · Resources · About · Blog · Acknowledgements · Queries · Stats · Sponsor · Day 605 · feedback@pldb.io · Logout