Example. Forester 4.2 › First-class functions and lazy arguments › Combining fluid bindings and lazy arguments [00YG]
Forester 4.0’s enhanced XML support makes it possible (see Example [00RL]) to write MathML directly as an alternative to using Forester’s TeX-like math mode via KaTeX. For example, we can write the following wrappers for some basic MathML elements:
\xmlns:mml{http://www.w3.org/1998/Math/MathML}
\def\math[body]{\<mml:math>{\body}}
\def\mrow[body]{\<mml:mrow>{\body}}
\def\mi[x]{\<mml:mi>{\x}}
\def\mo[o]{\<mml:mo>{\o}}
\def\mn[n]{\<mml:mn>{\n}}With this in hand, we can write prose involving MathML content, like so:
\p{Let \math{\mi{x}} and \math{\mi{y}} be integers such that \math{\mrow{\mrow{\mi{x}\mo{-}\mi{y}}\mo{=}\mn{0}}}.}The above is a bit messy. We can clean it up with some function definitions:
\def\plus[x][y]{\mrow{\x \mo{+} \y}}
\def\equals[x][y]{\mrow{\x \mo{=} \y}}
\let\x{\mi{x}}
\let\y{\mi{y}}
\p{Let \math{\x} and \math{\y} be integers such that \math{\equals{\plus{\x}{\y}}{\mn{0}}}.}It is annoying that we have to always wrap things in \math. By combining first-class functions, lazy arguments, and fluid bindings, we can lift this requirement:
% Allocate a fluid binding to hold the function that enters math mode.
\alloc\math-wrapper
% Ensure that a given (lazy) argument is evaluated inside a
% <mml:math> element.
\def\ensure-math[~body]{%
\scope{%
% Set a default value for \math-wrapper (no-op if already set).
\put?\math-wrapper{\fun[x]{\<mml:math>{\x}}}%
%
% Apply the current function bound to \math-wrapper.
\get\math-wrapper{%
% Bind \math-wrapper to the identity function in the current scope so that
% we do not get redundant <mml:math> nodes.
\put\math-wrapper{\fun[x]{\x}}%
%
% Force the \body thunk to evaluate the body within the wrapper.
\body{}%
}%
}%
}We now re-define our macro library to use the \ensure-math:
\def\mrow[~x]{\ensure-math{\<mml:mrow>{\x{}}}}
\def\mi[~x]{\ensure-math{\<mml:mi>{\x{}}}}
\def\mo[~x]{\ensure-math{\<mml:mo>{\x{}}}}
\def\mn[~x]{\ensure-math{\<mml:mn>{\x{}}}}
\def\plus[~x][~y]{\mrow{\x{} \mo{+} \y{}}}
\def\equals[~x][~y]{\mrow{\x{} \mo{=} \y{}}}Now, we can put MathML content freely into prose without needing to wrap it each time.
\let\x{\mi{x}}
\let\y{\mi{y}}
\p{Let \x and \y be integers such that \equals{\plus{\x}{\y}}{\mn{0}}.}