Generate TeX to typeset Sierpinski Triangle Fractal

Python 2, 32 bytes

exec"print'x'"+".join('{^_}')"*5

Try it online!


plain TeX, 29 bytes

\def~#1x{{#1x_#1x^#1x}}~~~~~x

That outputs what others have output. But if we need the code to be compilable it would be 6 bytes more

\def~#1x{{#1x_#1x^#1x}}$~~~~~x$\bye

Explanation

~ is an active character in TeX, so we can give it a (new) definition.

\def~#1x{{#1x_#1x^#1x}} defines ~ as a macro, so that when TeX sees ~, it does the following:

  • Read everything up to the next x, and call that #1 (pattern-matching).
  • Replace the whole thing with {#1x_#1x^#1x}

For example, ~ABCx would get replaced with {ABCx_ABCx^ABCx}.

When ~~~~~x is used, #1 is ~~~~, so the whole thing gets replaced with {~~~~x_~~~~x^~~~~x}. And so on.

Once we have the long string, we can print it out to terminal with \message (and ending with a \bye so TeX stops), so \message{~~~~~x}\bye. Or typeset the resulting expression (as a mathematical formula), by surrounding it in $s : so $~~~~~x$\bye.


SOGL V0.12, 16 12 bytes

 x5{"{^_}”;∑

Try it Here!

Port of Erik The Outgolfer's Python 2 answer