Re:Wolfram Language
by gohrt on Saturday May 16, 2015 @01:11AM
(#9555125)
Can the user define a macro in Mathematica language?
[ Parent
| on HN ]
There aren't read-time macros (yet). I'm actually in the process of designing a new package system that solves this (among many other problems).
the concept of "macros" in Mathematica doesn't really exist as its own concept because the whole system is based on rewriting structure. for example, the ReplaceAll function[1] which is commonly used in idiomatic code is basically an in-place macro definition and execution, yet it wouldn't occur to most people that it's anything special.
if you're trying to make a traditional macro, you would implement it as a function with the HoldFirst et al attribute.
an important thing to know is that ReplaceAll uses arbitrary structural patterns. it's not a simple "turn every a into b". you can say things like "turn every application of the symbol F on an even number into an application of G on that number divided by two".
expr /. F[n_?EvenQ] :> G[n/2]
[1] https://reference.wolfram.com/language/ref/ReplaceAll.html