Skip to main content

meta programming - Macro functions in GeneralUtilities?


Questions have been asked about the Macros package before (e.g., (83815)), but I'm interested if anyone has some examples of using the macro related functions in GeneralUtilities:


In[2397]:= Names["GeneralUtilities`*Macro*"]

Out[2397]= {"DefineLiteralMacro", "DefineMacro", "MacroEvaluate", \
"MacroExpand", "MacroExpandList", "MacroPanic", "MacroRules", \
"UseMacros", "$MacroDebugMode"}


I find their docstrings a bit cryptic:


enter image description here



Answer



The only official information about the Macro functions I am aware of can be found in a short segment in this presentation, which describes the "Macro System" as an essential part of the next compiler generation. However, the CreateMExpr shown there isn't included in Mathematica 10.4.1. (But maybe someone can find parts of it digging deeper into it?)


Nevertheless, one can already apply the Macro System practically (while being aware that this is an undocumented functionality with all the consequences involved) outside of that next generation compiler context.


First let's load the GeneralUtilities package and see what Macro functions are available as of version 10.4.1.


Needs["GeneralUtilities`"]
Names["*Macro*"]



{"DefineLiteralMacro", "DefineMacro", "MacroEvaluate", "MacroExpand", "MacroExpandList", 
"MacroPanic", "MacroRules", "UseMacros", $MacroDebugMode"}

First


?MacroRules

MacroRulesUsage


can be used to see how macros are defined within Mathematica. The most illustrating example is


MacroRules[DoWhile]


DoWhileMacro


One can get an overview of all predefined macros (that I found) using


MacroRules /@ List @@ GeneralUtilities`Control`PackagePrivate`$MacroHeadsPattern //
Grid[#, Frame -> All, Alignment -> Left] &

The Panels are how Quoted code is displayed in the Front End.


?Quoted

Quoded_Usage




Let's assume we don't like the common Increment syntax and want to use an incr function instead.


DefineMacro[incr, incr[n_] := Quoted[n++]]

incrMacro


incr itself doesn't have any DownValues, therefore


counter = 0;
Table[incr[counter], 5]


{incr[0], incr[0], incr[0], incr[0], incr[0]}




The macro can be applied using


MacroEvaluate@Table[incr[counter], 5]


{0, 1, 2, 3, 4}



To see what the macro does, one can use


MacroExpand@Table[incr[counter], 5]


MacroExpand_incr


and


MacroExpandList@Table[incr[counter], 5]

MacroExpandList_incr



Let's say we have some code that contains some Table expressions in the form Table[expr, n] and we want to replace them with Array and add 1 to every expr. To do this a macro can be defined in the following way:


DefineMacro[macro1, macro1[Table[expr_, n_?IntegerQ]] := Quoted[Array[1 + expr &, n]]]

macro1



Just applying macro1 to a Table does nothing special


macro1[Table[RandomReal[], 5]]


macro1[{0.0977249, 0.987251, 0.484049, 0.712003, 0.358444}]



but


MacroEvaluate@macro1@Table[RandomReal[], 5]



{1.60094, 1.53355, 1.49432, 1.74318, 1.648}



does make use of the macro.


MacroExpand[macro1[Table[RandomReal[], 5]]]

MacroExpand_macro1


MacroExpandList[macro1[Table[RandomReal[], 5]]]

MacroExpandList_macro1


If one tries to apply this macro to a Table having a different syntax pattern a Failure message is created.



MacroExpand[macro1[Table[RandomReal[], {i, 5}]]]

FailureMessage


Using replacement rules instead of a macro is less convenient, as the syntax is more complex.


Unevaluated@
Table[RandomReal[], 5] /. {Verbatim[Table][expr_, n_?IntegerQ] :> Array[1 + expr &, n],
___ -> $Failed}


{1.14275, 1.55058, 1.13318, 1.05475, 1.75428}





Let's assume we have defined a function


f[n_] := Table[RandomReal[], n]

and now we realize that for big integers n this implementation does perform much worse than RandomReal[{0, 1}, n]. A macro can be used to refactor our code.


DefineMacro[f, f[n_] := Quoted[RandomReal[{0, 1}, n] + 1]]

(The + 1 is just added to directly judge by the output, if the macro has been applied.)


For small n the overhead of using the Macro System does outweigh the performance increase of not using Table,



Table[RandomReal[], 10]; // AbsoluteTiming
RandomReal[{0, 1}, 10]; // AbsoluteTiming
RandomReal[{0, 1}, 10] + 1; // AbsoluteTiming
MacroEvaluate[f[10]]; // AbsoluteTiming


{0.0000126977, Null}
{8.35374*10^-6, Null}
{0.0000110269, Null}
{0.00018278, Null}


but becomes neglectable for big n.


f[1000000]; // AbsoluteTiming
MacroEvaluate[f[1000000]]; // AbsoluteTiming


{0.0549422, Null}
{0.0149402, Null}

One interesting thing to note is that the macro gets automatically applied when f is used to define an other function. For example



g[m_] := f[m]

DownValues@g


{HoldPattern[g[m_]] :> RandomReal[{0, 1}, m] + 1}



That this will be happening in other cases too becomes evident by looking at


 ?? f


Using the Macro System is also very helpful in conjunction with Compile.


cf = MacroEvaluate@Compile[{{n, _Integer, 0}},
f[n]
]

CompilePrint@cf

CompilePrint@cf


Here using MacroEvaluate has two effects:




  1. The macro for f gets applied and therefore the more efficient version is compiled.

  2. f[n] can directly been put into Compile.


Without the Macro System directly using f[n] inside Compile results in a call to MainEvaluate.


Compile[{{n, _Integer, 0}},
f[n]
] // CompilePrint

CompilePrint


Comments

Popular posts from this blog

plotting - How to draw lines between specified dots on ListPlot?

I would like to create a plot where I have unconnected dots and some connected. So far, I have figured out how to draw the dots. My code is the following: ListPlot[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4,13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full] I have thought using ListLinePlot command, but I don't know how to specify to the command to draw only selected lines between the dots. Do have any suggestions/hints on how to do that? Thank you. Answer One possibility would be to use Epilog with Line : ListPlot[ {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4, 13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full, Epilog -> { Line[ ...

equation solving - Invert and fit implicitly defined curve

I need to fit an implicitly defined curve. I thought I could get some data out of Solve , and then using FindFit . Therefore, I would like to find the relation the parametric curve defined by $F(x,y)=0$: Solve[-(1/2) + 1/2 (0.41202 BesselK[0, 0.1 Sqrt[x^2 + y^2]] + (0.101483 x BesselK[1, 0.1 Sqrt[x^2 + y^2]])/Sqrt[x^2 + y^2]) == 0, y] But I can't get an output: Solve was unable to solve the system with inexact coefficients or the system obtained by direct rationalization of inexact numbers present in the system. Since many of the methods used by Solve require exact input, providing Solve with an exact version of the system may help. >> Edit: In particular, I would like to fit the data coming from the curve with the expression of another curve, and not with a function $f(x)$. In particular, since this clearly looks like a cardioid , I would like it to fit to something like it. What other strategies could I try?

dynamic - How can I make a clickable ArrayPlot that returns input?

I would like to create a dynamic ArrayPlot so that the rectangles, when clicked, provide the input. Can I use ArrayPlot for this? Or is there something else I should have to use? Answer ArrayPlot is much more than just a simple array like Grid : it represents a ranged 2D dataset, and its visualization can be finetuned by options like DataReversed and DataRange . These features make it quite complicated to reproduce the same layout and order with Grid . Here I offer AnnotatedArrayPlot which comes in handy when your dataset is more than just a flat 2D array. The dynamic interface allows highlighting individual cells and possibly interacting with them. AnnotatedArrayPlot works the same way as ArrayPlot and accepts the same options plus Enabled , HighlightCoordinates , HighlightStyle and HighlightElementFunction . data = {{Missing["HasSomeMoreData"], GrayLevel[ 1], {RGBColor[0, 1, 1], RGBColor[0, 0, 1], GrayLevel[1]}, RGBColor[0, 1, 0]}, {GrayLevel[0], GrayLevel...