title: Tips for golfing in Mathematica

text:
# Question
Title: Tips for golfing in Mathematica
What general tips do you have for golfing in Mathematica? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Mathematica (e.g. "remove comments" is not an answer).

# Answer
Tips below vary from the most economical to the most often used:

1. Use Mathematica's high-level commands where possible, even bulky ones:
2. Use `Graphics and` `Text` for Ascii art: e.g Star programming! and Build an analog clock
3. Dedicated symbols:

* logic and set operations symbols instead of their long form names: ⋂, ⋃, ∧, ∨
    * `Map` and `Apply`: `/@`, `//@`. `@@`, `@@@`
4. Prefix and infix notation:

* `Print@"hello"` in place of `Print["hello"]`
    * `a~f~b` in place of `f[a,b]`
5. When a function is used only once, a pure function may economize a character or two.
6. Joining strings in a list. `""<>{"a","b","c"}` instead of `StringJoin@{"a","b","c"}`
7. Exploit listable functions. The longer the lists the better.

`{a, b, c} + {x, y, z}= {a+x, b+y, c+z}`

`{2, 3, 4} {5, 6, 7}= {10, 18, 28}`

`{{a, b}, {c, d}}^{2, 3} = {{a^2, b^2}, {c^3, d^3}}`
> 34 votes

# Answer
Some built-in functions with long names can be replaced with shorter expressions.

For example:

* `Total` =\> `Tr` for 1d arrays
* `Transpose` =\> `Thread` or  (`\[Transpose]`)
* `True` =\> `1<2`
* `False` =\> `1>2`
* `Times` =\> `1##&`
* `Alternatives` =\> `$|##&`
* `IntegerQ` =\> `⌊#⌋==#&` or `1∣#&` (Thanks to @Misha Lavrov)
* `a[[1]]` =\> `#&@@a`
* `a[[All,1]]` =\> `#&@@@a`
* `ConstantArray[a,n]` =\> `Array[a&,n]` or `Table[a,n]`
* `Union@a` =\> `{}⋃a` or `a⋃a`
* `ToExpression@n` =\> `FromDigits@n` if `n` is a number
* `Divisible[n,m]` =\> `m∣n`
* `FromDigits[n,2]` =\> `Fold[#+##&,n]` if `n` is a list of `0`s and `1`s
* `Complex@z` =\> `{1,I}.z` where `z` is a list of the form `{x,y}`
* `Rest@FoldList[f[#,#2]&,x,l]` =\> `t=x;(t=f[t,#])&/@l`
* `Table[f[i,l],{i,Length@l}]` =\> `i=1;f[i++,l]&/@l`
* `CoefficientList[f,x]` =\> `(f+O@x^n)[[3]]` if you know that the degree of the polynomial `f` is `n` and the constant term is not zero
* `FractionalPart[x]` =\> `Mod[x,1]` if x is nonnegative
> 41 votes

# Answer
## Lists with repeated values

This is quite a common vector to work with:

```
{0,0}

```

It turns out this can be shortened by a byte:

```
0{,}

```

Even more bytes are saved if the vector is longer than two zeros. This can also be used to initialise zero matrices, e.g. the following gives a 2x2 matrix of zeros:

```
0{{,},{,}}

```

This can also be used for non-zero values if they're sufficiently large or sufficiently many or negative. Compare the following pairs:

```
{100,100}
0{,}+100

```

```
{-1,-1}
0{,}-1

```

```
{3,3,3,3}
0{,,,}+3

```

But remember that starting at 6 values, you're better off with `1~Table~6` in this case (potentially earlier, depending on precedence requirements).

The reason this works is that `,` introduces two arguments to the list, but omitted arguments (anywhere in Mathematica) are implicit `Null`s. Furthermore, multiplication is `Listable`, and `0*x` is `0` for almost any `x` (except for things like `Infinity` and `Indeterminate`), so here is what's happening:

```
  0{,}
= 0*{,}
= 0*{Null,Null}
= {0*Null,0*Null}
= {0,0}

```

For lists of `1`s, you can use a similar trick by making use of exponentiation rules. There are two different ways to save bytes if you have at least three `1`s in the list:

```
{1,1,1}
1^{,,}
{,,}^0

```
> 25 votes

# Answer
# Know your pure function arguments

When golfing code, you'll often employ a functional approach, where you use anonymous (pure) functions with the `&` shorthand syntax. There are a lot of different ways to access the arguments of such a function, and you can often shave off a couple of bytes by having a good grasp on the possibilities.

## Accessing single arguments

You probably know this if you've used pure functions before. The **n**th argument is referred to as `#n`, and `#` acts as an alias for `#1`. So if, say, you want to write a function that takes as parameters another function and its argument (to pass the argument to that function), use

```
#@#2&

```

This does *not* work with negative numbers (such as you might use when accessing lists).

## Accessing named arguments (new in V10)

One of the major new language features in Mathematica 10 is `Association`s, which are basically key-value maps with arbitrary key types, written like

```
<| x -> 1, "abc" -> 2, 5 -> 3 |>

```

If such an association is passed in as the *first* argument to a pure function, you can access some if its arguments as named parameters:

```
{#, #2, #3, #abc, #xyz} & [<| "abc" -> "1st", "xyz" -> "2nd", abc -> "3rd" |>, "4th", "5th"]
(* {<| "abc" -> "1st", "xyz" -> "2nd", abc -> "3rd" |>, "4th", "5th", "1st", "2nd"} *)

```

Note that `#` still refers to the entire association as expected. For the named parameters to work, the keys have to be *strings* (it won't work if you use undefined variables for instance), and those strings must begin with a letter and only contain letters and digits.

## The "self" argument `#0`

A lesser known feature is that `#0` also exists, and gives you the function object itself. This can be really useful in quines and generalised quines. In fact, the shortest Mathematica quine (I know of) is

```
ToString[#0][] & []

```

What's slightly annoying is that it won't give you the exact characters you entered. E.g. if use `@` for function application, it will still render as `[...]` and spaces will be inserted in some places. This will usually make the quine a bit longer than you'd like it to be, but it will always work, by golfing the quine first, and then just copying its output - which should now be a real quine.

Apart from quines, this also means that you can write recursive code without having to name your function. Compare these three (naive but golfed) Fibonacci implementations:

```
f@0=0;f@1=1;f@n_:=f[n-1]+f[n-2]
f@n_:=If[n<2,n,f[n-1]+f[n-2]]
If[#<2,#,#0[#-1]+#0[#-2]]&

```

## Sequences of arguments

Now this is where the real magic starts. Sequences aren't used often in golfing, because `Sequence` it's just too long a name to be worth it most of the time. But in pure functions is where they shine. If you're not familiar with sequences, they are basically like splats in some other languages, if you use a sequence in a `List` or the argument list of a function, it's elements will automatically be expanded into separate slots. So

```
{1, Sequence[2, 3, 4], 5} == {1, 2, 3, 4, 5}
f["a", Sequence[0, {}], "b"] == f["a", 0, {}, "b"]

```

Now, in pure functions `##` or `##1` is a sequence of all the arguments. Likewise, `##2` is a sequence of all arguments starting from the second, `##3` all arguments starting from the third etc. So for a start, we can just reimplement `Sequence` as `##&`, saving 5 bytes. As an example usage, this provides us with an alternative to `Join@@list` (see this tip), which doesn't save any bytes, but is good to know about anyway:

```
 ##&@@@list

```

This effectively flattens the first level of a nested list. What else can we do with this? Here is a 1-byte saving for `RotateLeft`:

```
 RotateLeft@list
 {##2,#}&@@list

```

For these things alone it's worth keeping this feature in mind. However, we can do better! Sequences get really interesting when consider that operators are actually implemented as functions under the hood. E.g. `a+b` actually evaluates to `Plus[a,b]`. So if we give that a sequence...

```
1+##&[1,2,3]
=> Plus[1,##]
=> Plus[1,1,2,3]
=> 7

```

This trick has been use in this tip to save a byte on `Times`, because juxtaposition is technically also just an operator:

```
1##&[1,2,3]
=> Times[1,##]
=> Times[1,1,2,3]
=> 6

```

You can also use it to save a byte on `Unequal` if you have a single-character value or variable you know is not in your arguments (`N` will probably work in 99% of the cases):

```
Unequal[a,b,c]
N!=##&[a,b,c]

```

This gets even more interesting with unary operators and `-` and `/` \- the latter two are actually implemented in terms of multiplication and exponentiation. Here is a list of things you can do, where the last column assumes that the function was passed the arguments `a, b, c`:

```
Operator    Function                Expanded                    Equivalent to

+##         Plus[##]                Plus[a,b,c]                 a+b+c
1##         Times[1,##]             Times[1,a,b,c]              a*b*c
-##         Times[-1,##]            Times[-1,a,b,c]             -a*b*c
x+##        Plus[x,##]              Plus[x,a,b,c]               x+a+b+c
x-##        Plus[x,Times[-1,##]]    Plus[x,Times[-1,a,b,c]]     x-a*b*c
x##         Times[x,##]             Times[x,a,b,c]              x*a*b*c
x/##        Times[x,Power[##,-1]]   Times[x,Power[a,b,c,-1]]    x*a^b^c^-1
##/x        Times[##,Power[x,-1]]   Times[a,b,c,Power[x,-1]]    a*b*c/x
x^##        Power[x,##]             Power[x,a,b,c]              x^a^b^c
##^x        Power[##,x]             Power[a,b,c,#]              a^b^c^x
x.##        Dot[x,##]               Dot[x,a,b,c]                x.a.b.c

```

Other common operators are `!=`, `==`, `&&`, `||`. Less common ones to keep in mind are `|`, `@*`, `/*`. To conclude, here is a little bonus trick:

```
####        Times[##,##]            Times[a,b,c,a,b,c]          (a*b*c)^2

```

Keep experimenting with these, and let me know if you find any other useful or particularly interesting applications!
> 22 votes

# Answer
`Sqrt@2` or `2^.5` =\> `√2`

`a[[1]]`=\>`a〚1〛`

`#+#2&`=\>`+##&`

`Flatten@a`=\>`Join@@a` (sometimes)

`Function[x,x^2]`=\>`xx^2` or `#^2&`

`a〚1;;-1;;2〛`=\>`a〚;;;;2〛`

`a〚2;;-1 ;;2〛`=\>`a〚2;;;;2〛`

`a〚All,1〛`=\>`a〚;;,1〛`

`{{1}}〚1,1〛`=\>`Tr@{{1}}`

`0&~Array~10`=\>`0Range@10`

`Range[10^3]`=\>`Range@1*^3`
> 19 votes

# Answer
## Operators as Functions

Inspired by Dennis's recent discovery for Julia I thought I'd look into this for Mathematica. I was aware that Mathematica defines a large number of unused operators, but never paid much attention to it.

For reference, the list of all operators can be found here in the form of a precedence table. The triangle in the last column indicates whether that operator has a built-in meaning or not. While not all of those that don't can be defined easily, most of them can.

Conveniently, there are two unused operators with a codepoint less than 256, such that they can be used as single bytes in an ISO 8859-1 encoded source file:

* `±` (0xB1) can be used either as a unary prefix operator or a binary infix operator.
* `·` (0xB7) can be used as a variadic or n-ary infix operator, for n \> 2.

There's one more catch though: for some weird reason when *defining* these operators you need one space in front of them, or else Mathematica tries to parse a multiplication. When using them you don't need any spaces though:

```
±x_:=2x
x_ ±y_:=x+y
x_ ·y_ ·z_:=x*y+z
Print[±5]  (* 10 *)
Print[3±4] (*  7 *)
Print[3·4·5] (* 17 *)

```

Compare this with:

```
f@x_:=2x
x_~g~y_:=x+y
h[x_,y_,z_]:=x*y+z
Print[f@5]   (* 10 *)
Print[3~g~4] (*  7 *)
Print[h[x,y,z]] (* 17 *)

```

So this saves one byte when defining the function and two bytes when using it. Note that the definition of `·` will not save bytes for four operands and will start costing bytes for more operands, but the usage may still save bytes, depending the precedence of operators used in the arguments. It's also good to note that you can cheaply define a variadic function that can then be called much more efficiently:

```
x_ ·y__:={y}
Print[1·2·3·4·5] (* {2, 3, 4, 5} *)

```

But note that it's not easily possible to call these variadic functions with a single argument. (You could do `CenterDot[x]` or `##&[]·x` but if you actually need that there's a good chance you're better off with a different solution.)

Of course, this isn't saving anything for solutions where an unnamed function suffices, but sometimes you need to define helper functions for use later on, and sometimes it's shorter to define named functions e.g. to set up different definitions for different parameters. In those cases, using an operator instead can save a decent amount of bytes.

Note that using these ISO 8859-1 encoded files requires `$CharacterEncoding` to be set to a compatible value, like the Windows default `WindowsANSI`. On some systems this defaults to `UTF-8` which won't be able to read these code points from single bytes.
> 14 votes

# Answer
1. **Explore recursive solutions** \- Mathematica is multi-paradigm, but the functional approach is often the most economical. `NestWhile` can be a very compact solution to searching problems, and `NestWhileList` and `FoldList` are powerful when you need to return or process the results of intermediate iterations. `Map (/@)`, `Apply (@@, @@@)`, `MapThread`, and really everything on Wolfram's Functional Programming documentation page is potent stuff.
2. **Shortened form for increment/decrement** \- For example, instead of `While[i<1,*code*;i++]` you can do
`While[i++<1,*code*]`
3. **Don't forget you can pre-increment/decrement** \- For example, `--i` instead of `i--`. This can sometimes save you a few bytes in the surrounding code by eliminating a preparatory operation.
4. Corollary to David Carraher's #5: **When the same function is used many times, assigning a symbol to it can save bytes.** For example, if you are using `ToExpression` 4 times in a solution, `t=ToExpression` enables you to use `t@*expression*` thereafter. However, before you do this consider whether the repeated application of the same function indicates an opportunity for a more economical recursive approach.
> 11 votes

# Answer
# Choosing values based on integer

The naive approach to choose between `y` and `z`, depending on whether `x` is `0` or `1` is

```
If[x<1,y,z]

```

However, there's a shorter way:

```
y[z][[x]]

```

This works because `[[0]]` gives the `Head` of an expression, in this case `y`, whereas `[[1]]` just gives the first element - in this case the first argument, `z`.

You can even use this to choose between more than two values:

```
u[v,w][[x]]

```

Note that this won't work if `u` is a function that actually evaluates to something. It's important that Mathematica keeps `u[v,w]` as it is. However, this works in most cases, including if `u` is a is a number, a string or a list.

Credits for this trick go to alephalpha - I discovered this in one of his answer.

If `x` is 1-based instead of zero-based, just use

```
{y,z}[[x]]

```

or

```
{u,v,w}[[x]]

```

In some rare cases, you can even make use of the fact that multiplication is not evaluated for some values:

```
{"abc","def"}[[x]]
("abc""def")[[x]]

```

Note though that Mathematica will actually reorder the arguments, of a multiplication if it remains unevaluated, so the above is *identical* to

```
("def""abc")[[x]]

```
> 11 votes

# Answer
## Alternatives to `Length`

*This has been entirely rewritten with some suggestions from LegionMammal978 and Misha Lavrov. Many thanks to both of them.*

In many cases, `Length` can be shortened a bit by making use of `Tr`. The basic idea is to turn the input into a list of `1`s, so that `Tr` sums them up which will then equal the length of the list.

The most common way to do this is to use `1^x` (for a list `x`). This works because `Power` is `Listable` and `1^n` for most atomic values `n` is just `1` (including all numbers, strings and symbols). So we can already save one byte with this:

```
Length@x
Tr[1^x]

```

Of course, this assumes that `x` is an expression with higher precedence than `^`.

If `x` contains only `0`s and `1`s, we can save another byte using `Factorial` (assuming `x` has higher precedence than `!`):

```
Length@x
Tr[x!]

```

In some rare cases, `x` might have lower precedence than `^` but still higher precedence than multiplication. In that case it will also have lower precedence than `@`, so we really need to compare with `Length[x]`. An example of such an operator is `.`. In those cases, you can still save a byte with this form:

```
Length[x.y]
Tr[0x.y+1]

```

Finally, some remarks about what kind of lists this works on:

As mentioned at the top, this works on flat lists containing only numbers, strings and symbols. However, it will also work on some deeper lists, although it actually computes something slightly different. For an **n**-D rectangular array, using `Tr` gives you the *shortest* dimension (as opposed to the first). If you know that the outermost dimension is the shortest, or you know they're all the same, than the `Tr`-expressions are still equivalent to `Length`.
> 9 votes

# Answer
# Don't use `{}` if you are using `@@@`.

In some cases, you may encounter an expression like:

```
f@@@{{a,b},{c,d}}

```

It is possible to reduce bytes by writing:

```
f@@@{a|b,c|d}

```

`Alternatives` has a very low precedence, so it's generally okay to write expressions (a notable exception is pure functions; you can use it only in the leftmost element of `Alternatives`).

```
f@@@{f@a|b~g~1,#^2&@c|d@2}

```

Note that `f@@a|b|c` (instead of `f@@{a,b,c}`) does not work because `Apply` has a higher precedence than `Alternative`.

In this case, you should simply use `f@@{a,b,c}`.
> 9 votes

# Answer
# Don't write 0-argument functions

There is no need for code like this:

```
f[]:=DoSomething[1,2]
(*...*)
f[]
(*...*)
f[]

```

You can simply use a variable with `:=` to force re-evaluation of the right-hand side:

```
f:=DoSomething[1,2]
(*...*)
f
(*...*)
f

```

This also means that you can alias any action that you perform often (even if it's just something like `n++`) to a single character at the cost of 5 bytes. So in the case of `n++` it pays back after the fourth use:

```
n++;n++;n++;n++
f:=n++;f;f;f;f

```
> 7 votes

# Answer
## Mathematica 10 only

**Operator forms**

Mathematica 10 supports so-called "operator forms", which basically means some functions can be curried. Currying a function is to create a new function by fixing one of its operators. Say, you're using `SortBy[list, somereallylongfunction&]` a lot of different `list`s. Before, you probably would have assigned `SortBy` to `s` and the pure function to `f` so

```
s=SortBy;
f=somereallylongfunction&;
list1~s~f;
list2~s~f;
list3~s~f;

```

Now you can curry `SortBy`, which means you can now do

```
s=SortBy[somereallylongfunction&];
s@list1;
s@list2;
s@list3;

```

The same works for a lot of other functions, which take a list or function argument, including (but not limited to) `Select`, `Map`, `Nearest`, etc.

ybeltukov over on Mathematica.SE was able to produce a complete list of these:

```
{"AllTrue", "AnyTrue", "Append", "Apply", "AssociationMap", "Cases",
 "Count", "CountDistinctBy", "CountsBy", "Delete", "DeleteCases",
 "DeleteDuplicatesBy", "Extract", "FirstCase", "FirstPosition",
 "FreeQ", "GroupBy", "Insert", "KeyDrop", "KeyExistsQ", "KeyMap",
 "KeySelect", "KeySortBy", "KeyTake", "Map", "MapAt", "MapIndexed",
 "MatchQ", "MaximalBy", "MemberQ", "Merge", "MinimalBy", "NoneTrue",
 "Position", "Prepend", "Replace", "ReplacePart", "Scan", "Select",
 "SelectFirst", "SortBy", "StringCases"}

```

**Composition and RightComposition**

There are new shorthands for `Composition` (`@*`) and `RightComposition` (`/*`). An obviously contrived example where these can save characters is seen in the following three equivalent lines

```
Last@Range@# & /@ Range[5]
Last@*Range /@ Range[5]
Range /* Last /@ Range[5]

```
> 6 votes

# Answer
If you need a list of numbers sorted in reverse, don't use

```
Reverse@Sort@x

```

but

```
-Sort@-x

```

to save six bytes. Sorting by a negative value is also useful for `SortBy` scenarios:

```
Reverse@SortBy[x,Last]
SortBy[x,-Last@#&]

```
> 6 votes

# Answer
# Use `Null` as an iteration variable

As has been mentioned elsewhere, missing arguments are interpreted as `Null`. Since iterators such as those used in `Sum` or `Table` localize the iteration variable, symbols such as `Null` can be used as the iteration variable, potentially saving bytes.

For example,

```
Sum[,{,10}]

```

is interpreted as `Sum[Null,{Null,10}]`, which evaluates to the expected `55`.
> 6 votes

# Answer
# Checking if a list is sorted

This is essentially a corollary of this tip but this is a sufficiently common task that I think it warrants its own answer.

The naive way to check if a list is in order is to use

```
OrderedQ@a

```

We can do one byte better with

```
Sort@a==a

```

However, this doesn't work if we don't have the thing we want to check in a variable already. (We'd need something like `Sort[a=...]==a` which is unnecessarily long.) However, there's another option:

```
#<=##&@@a

```

The best thing is that this can be used to check whether the input is reverse sorted for the same byte count:

```
#>=##&@@a

```

One more byte can be saved if a) we know that the list elements are distinct and b) we know a lower bound between 0 and 9 (inclusive; or upper bound for reverse sorted order):

```
0<##&@@a
5>##&@@a

```

To see why this works, check out "Sequences of arguments" in the tip linked at the top.
> 5 votes

# Answer
# Use `%` to get a free variable

**This tip is only applicable if Mathematica's REPL environment can be assumed.** `%` is not defined when code is run as a script.

When you *can* make use of the REPL features, don't do this:

```
a=someLongExpression;some[other*a,expression@a,using^a]

```

Instead, remember that Mathematica stores the last evaluated (newline-terminated) expression in `%`:

```
someLongExpression;
some[other*%,expression@%,using^%]

```

The added newline costs a byte, but you are saving two by removing `a=`, so overall this saves one byte.

In some cases (e.g. when you want to print the value of `a` anyway), you can even leave off the `;`, saving two bytes:

```
someLongExpression
some[other*%,expression@%,using^%]

```

One or two bytes may seem fairly minor, but this is an important case, because it makes extraction of repeated expressions (which is a very common technique) much more useful when golfing:

The normal technique of extracting repeated expressions costs four bytes of overhead, which need to be saved by further uses of the expression. Here is a short table of the minimum number of uses of an expression (by length of the expression) for extraction into a named variable to save anything:

```
Length   Min. Uses
2        6
3        4
4        3
5        3
6        2
...      2

```

By using the unnamed variable, it will be possible to save a couple of bytes much more often:

```
When ; is required                        When ; can be omitted

Length   Min. Uses                        Length   Min. Uses
2        5                                2        4
3        3                                3        3
4        3                                4        2
5        2                                ...      2
...      2

```

---

I don't think `%%` or `%n` can be used for golfing, because if you don't use them at least twice, you can just put the expression right where it's needed. And if you use it twice, the additional character in the variable name cancels out the savings from omitting some `x=`.
> 5 votes

# Answer
# Mathematica 10.2: `BlockMap` is `Partition`+`Map`

This tip could also be titled, "Read the release notes, all of them". (For reference, here are the release notes for 10.2 and here of today's 10.3 release.)

Anyway, even minor releases contain a wealth of new features, and one of the more useful ones (for golfing) from 10.2 is the new `BlockMap` function. It essentially combines `Partition` and `Map`, which is great for is golfers, because `Partition` is used quite often, and it's a really annoyingly long function name. The new function won't shorten `Partition` by itself, but whenever you want to map a function onto the partitions (which probably happens more often than not), you can now save a byte or two:

```
#&/@l~Partition~2
BlockMap[#&,l,2]

```

```
#&/@Partition[l,3,1]
BlockMap[#&,l,3,1]

```

The savings get even bigger when the new position of the unnamed function allows you to save yourself some parentheses:

```
#&@@(#&/@Partition[l,3,1])
#&@@BlockMap[#&,l,3,1]

```

Unfortunately, I have no idea why didn't also add `BlockApply` while they were at it...

Also note that `BlockMap` does not support the 4th parameter you can use with `Partition` to get a cyclic list:

```
Partition[Range@5, 2, 1, 1]
(* Gives {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 1}} *)
BlockMap[f, Range@5, 2, 1, 1]
(* Nope... *)

```
> 5 votes

# Answer
### Repeating a string

Instead of `StringRepeat[str,n]` use `(0Range[n]+str)<>""`. Or if `str` doesn't depend on any slot arguments, even better is `Array[str&,n]<>""` as per this tip.
> 5 votes

# Answer
You can stick an expression in `Break` which can save one or two characters. Example (*other details not golfed for clarity*):

```
result = False;
Break[]

```

can be turned into

```
Break[result = False]

```

to save one character. If the expression in question does not have lower precedence than function application you can even save another character:

```
Print@x;
Break[]

```

can be turned into

```
Break@Print@x

```

Although undocumented, the argument to `Break` seems to be returned by the surrounding loop, which can potentially lead to even more savings.
> 4 votes

# Answer
Here is a list with loads of operator input forms which can shorten a lot of things. Some of these have been mentioned in other posts, but the list is *long* and I'm always surprised to find a few new things on there:
> 4 votes

# Answer
To remove all whitespace from a string `s`, use

```
StringSplit@s<>""

```

That is, use `StringSplit`'s default (split into non-whitespace components) and simply join them back together. The same is probably still the shortest if you want to get rid of any other character or substring:

```
s~StringSplit~"x"<>""

```
> 4 votes

# Answer
## Alternatives to `Range`

A very common task is to apply some sort of function to all numbers from 1 to a `n` (usually given as input). There are essentially 3 ways to do this (using an unnamed identity function as an example):

```
#&/@Range@n
Array[#&,n]
Table[i,{i,n}]

```

I tend to go for the first one (for whatever reason), but this is rarely the best choice.

### Using `Array` instead

The above example shows that using `Array` has the same byte count. However, it has the advantage that it is a single expression. In particular, if you want to further process the result with a function `f` you can use prefix notation, which saves a byte over `Range`:

```
f[#&/@Range@n]
f@Array[#&,n]

```

Furthermore, you may be able omit parentheses around your unnamed function which you might have needed with `Range`, e.g.

```
15/(#&)/@Range@n
15/Array[#&,n]

```

If you *don't* want to use it further (or with an operator which has lesser precedence), you can instead write `Array` itself in infix notation and also save a byte:

```
#&/@Range@n
#&~Array~n

```

Hence, `Array` is almost certainly better than `Range`.

### Using `Table` instead

Now table has to make up for 3 bytes, or at least 2 when infix notation is an option:

```
#&/@Range@n
i~Table~{i,n}

```

When *not* using infix notation, `Table` might allow you to omit parentheses if your function consists of several statements:

```
(#;#)&/@Range@n
Table[i;i,{i,n}]

```

This is still longer, but gives extra savings with in the case mentioned below.

The real savings stem from the fact that `Table` gives the running variable a name should not be dismissed. Often, you'll have nested unnamed functions where you want to use the outer variable inside one of the inner functions. When that happens, `Table` is shorter than `Range`:

```
(i=#;i&[])&/@Range@n
Table[i&[],{i,n}]
i&[]~Table~{i,n}

```

Not only do you save the characters for assigning `i`, you might also be able to reduce the function to a single statement in the process, which allows you to use infix notation on top of it. For reference, `Array` is also longer in this case, but still shorter than `Range`:

```
(i=#;i&[])&~Array~n

```

### When would you actually use `Range`?

Whenever you don't need a function call to process the values, e.g. when the mapping can be performed via a vectorised operation. For instance:

```
5#&~Array~n
5Range@n

```

```
#^2&~Array~n
Range@n^2

```

Of course, it's also shorter if you don't want to map any function at all, e.g.

```
Mean@Array[#&,n]
Mean@Range@n

```
> 4 votes

# Answer
# Finding the smallest number that satisfies a condition

Some construct like `i=1;While[cond[i],i++]` is fine as is, but there is an alternative that is two bytes shorter:

```
1//.i_/;cond[i]:>i+1

```

The above code repeatedly replaces a number `i` with `i+1` while it meets the condition `cond[i]`. In this case, `i` starts at `1`.

Note that the default maximum number of iterations is 2^16 (= 65536). If you need more iterations than that, `While` would be better. (`MaxIterations->∞` is too long)
> 4 votes

# Answer
# Storing functions and expressions in a variable

If your answer ends up using the same functions or expressions multiple times, you may want to consider storing them in variables.

If your expression is length `l` and you use it `n` times, it would normally use up `l * n` bytes.

However, if you store it in a length-1 variable, it would take only `3 + l + n` bytes (or `2 + l + n` bytes, if you assign the variable where you won't need `CompoundExpression (;)` or parentheses).

---

For example, let's consider a simple problem, finding twin primes less than N.

One could write this 54 byte solution:

```
Select[Range@#,PrimeQ@#&&(PrimeQ[#+2]||PrimeQ[#-2])&]&

```

In this example, the function `PrimeQ` is used three times.

By assigning `PrimeQ` a variable name, the byte count can be reduced. Both of the following are 48 bytes (54 - 6 bytes):

```
Select[p=PrimeQ;Range@#,p@#&&(p[#+2]||p[#-2])&]&
Select[Range@#,(p=PrimeQ)@#&&(p[#+2]||p[#-2])&]&

```
> 4 votes

# Answer
# Abuse short-circuit evaluation

You can sometimes replace `If` with a logical operator.

For instance, let's say you want to make a function that checks whether a number is prime, and print `2*(number) - 1` is if it's true:

```
If[PrimeQ@#,Print[2#-1]]&

```

It's shorter if you use `&&` instead:

```
PrimeQ@#&&Print[2#-1]&

```

Even when you have multiple expressions, you still save byte(s):

```
If[PrimeQ@#,a++;Print[2#-1]]&

PrimeQ@#&&a++&&Print[2#-1]&
(* or *)
PrimeQ@#&&(a++;Print[2#-1])&

```

You can use `||` for cases when you want the condition to be `False`:

```
If[!PrimeQ@#,Print[2#-1]]&
(* or *)
If[PrimeQ@#,,Print[2#-1]]&
(* can become *)
PrimeQ@#||Print[2#-1]&

```

These tricks work because logical operators can be short-circuited; the second argument and thereafter don't even need to be valid boolean expressions.

Of course, this does not work if you need the return value of `If` or when you need both truthy and falsy arguments of `If`.
> 4 votes

# Answer
# Special characters

**This post is community wiki. Feel free to edit and add more characters that you find useful.**

Mathematica has many special named characters. Some of them are helpful for golfing. But these characters are hard to type outside Mathematica. Some are even in the Private Use Areas.

The following is a list of commonly used named characters, so that you can copy and paste.

Other than the 2-byte `°` (`\[Degree]`), all of these characters are 3 bytes long.

* : `\[Conjugate]`, conjugate of a complex number
* : `\[ConjugateTranspose]`, conjugate transpose of a matrix
* : `\[Cross]`, cross product
* `°`: `\[Degree]`, degree, symbol that equals `Pi/180`
* : `\[DirectedEdge]`, directed edges in a graph; `->` often works instead
* : `\[Divides]`, `a∣b` means `b` is divisible by `a`
* : `\[Element]`, tests membership in a domain or region (e.g. `Primes`, `Ball[]`)
* : `\[Equivalent]`, logical equivalence
* : `\[Function]`, anonymous functions; in Mathematica 12.3 or newer versions you can write `|->`
* : `\[HermitianConjugate]`, the same as  (`\[ConjugateTranspose]`)
* : `\[Implies]`, logical implication
* : `\[Infinity]`, infinity
* : `\[Intersection]`, set intersection
* : `\[LeftCeiling]`, `⌈x⌉` is the ceiling of `x`
* : `\[LeftFloor]`, `⌊x⌋` is the floor of `x`
* : `\[Nand]`, logical nand
* : `\[Nor]`, logical nor
* : `\[Piecewise]`, `{{a,b}...}` is mostly equivalent to `Which[b,a,...,True,0]`
* : `\[RightCeiling]`, `⌈x⌉` is the ceiling of `x`
* : `\[RightFloor]`, `⌊x⌋` is the floor of `x`
* : `\[Sqrt]`, square root
* : `\[Transpose]`, transpose of a matrix
* : `\[UndirectedEdge]`, undirected edges in a graph; `<->` often works instead
* : `\[Union]`, set union
* : `\[VectorLess]`, `xy` means `x[[i]]<y[[i]]` for every `i`
* : `\[VectorLessEqual]`, `xy` means `x[[i]]<=y[[i]]` for every `i`
* : `\[VectorGreater]`, `xy` means `x[[i]]>y[[i]]` for every `i`
* : `\[VectorGreaterEqual]`, `xy` means `x[[i]]>=y[[i]]` for every `i`
* : `\[Xnor]`, logical xnor
* : `\[Xor]`, logical xor

More can be found in this link: https://reference.wolfram.com/language/guide/ListingOfNamedCharacters.html
> 4 votes

# Answer
# Using `Optional (:)`

`Optional (:)` can be used to expand lists in replacements, without having to define a separate rule for the expansion.

This answer by me and this answer by @ngenisis are examples.

**Usage**

```
... /. {p___, a_: 0, b_, q___} /; cond[b] :> ...

```

The above replacement first uses the pattern `{p___, a_, b_, q___}` and finds a match such that `b` meets a certain condition.

When no such match is find, it omits `a_` and instead searches for `{p___, b_, q___}`. `a` is not included in the search and is assumed to have the value `0`.

Note that the second pattern search would only work for `b` that occurs at the beginning of the list; if a `b` value satisfying a condition is in the middle, then `{p___, a_, b_, q___}` (which has a higher precedence) would match it instead.

The replacement is equivalent to prepending a `0` when a `b` satisfying a condition occurs at the beginning of the list. (i.e. there is no need to define a separate rule, `{b_, q___} /; cond[b] :> ...`)
> 3 votes

# Answer
## Know when (and when not) to use named pure function arguments

For code golf, pure `Function` arguments are most commonly referenced using `Slot`s; e.g. `#` for the first argument, `#2` for the second, etc. (see this answer for more details).

In many cases, you will want to nest `Function`s. For example, `1##&@@#&` is a `Function` which takes a list as its first argument and outputs the product of its elements. Here is that function in `TreeForm`:

Arguments passed to the top level `Function` can only fill `Slot`s and `SlotSequence`s present at the top level, which in this case means that the `SlotSequence` in the inner `Function` will not have any way of accessing arguments to the top level `Function`.

In some cases, though, you may want a `Function` nested within another `Function` to be able to reference arguments to the outer `Function`. For example, you may want something like `Array[fun,...]&`, where the function `fun` depends on an argument to the top level `Function`. For concreteness, let's say that `fun` should give the remainder of the square of its input modulo the input to the top level `Function`. One way to accomplish this is to assign the top level argument to a variable:

```
(x=#;Array[Mod[#^2,x]&,...])&

```

Wherever `x` appears in the inner `Function` `Mod[#^2,x]&`, it will refer to the first argument to the outer `Function`, whereas `#` will refer to the first argument to the inner `Function`. A better approach is to use the fact that `Function` has a two argument form where the first argument is a symbol or list of symbols that will represent named arguments to the `Function` (as opposed to unnamed `Slot`s). This ends up saving us three bytes in this case:

```
xArray[Mod[#^2,x]&,...]

```

is the three byte private use character `U+F4A1` representing the binary infix operator `\[Function]`. You may also use the binary form of `Function` within another `Function`:

```
Array[xMod[x^2,#],...]&

```

This is equivalent to the above. The reason is that, if you are using named arguments, then `Slot`s and `SlotSequences` are assumed to belong to next `Function` above which does not use named arguments.

Now just because we can nest `Function`s in this way, doesn't mean we always should. For example, if we wanted to pick out those elements of a list that are less than the input, we might be tempted to do something like the following:

```
Select[...,xx<#]&

```

It would actually be shorter to use `Cases` and avoid the need for a nested `Function` entirely:

```
Cases[...,x_/;x<#]&

```
> 3 votes

# Answer
You can save a byte by working around `Prepend` or `PrependTo`:

```
l~Prepend~x
{x}~Join~l
{x,##}&@@l

```

or

```
l~PrependTo~x
l={x}~Join~l
l={x,##}&@@l

```

Unfortunately, this doesn't help for the more common `Append`, which seems to be the shortest equivalent of an `Array.push()` in other languages.
> 2 votes

# Answer
# To achieve an ascending key-value list, use `Sort` instead of `SortBy`

For lists such as `list = {{1, "world"}, {0, "universe"}, {2, "country"}}`, the following three statements are almost equivalent.

```
SortBy[list,#[[1]]&]
list~SortBy~First
Sort@list

```

# Combine `Select` and `SortBy`

Sometimes we need to pick entries out of a larger set and sort them to find a minimum / maximum. **Under some circumstances**, two operations could be combined into one.

For example, for a minimum, the following two statements are almost equivalent.

```
SortBy[Select[l,SomeFormula==SomeConstant&],SortValue&]
SortBy[l,SortValue+99!(SomeFormula-SomeConstant)^2&]

```

and

```
SortBy[Select[l,SomeFormula!=SomeConstant&],SortValue&]
SortBy[l,SortValue+1/(SomeFormula-SomeConstant)&]

```

`1/0` is `ComplexInfinity`, which is "larger" than all real numbers.

For a key-value list, for example:

```
{SortValue,#}&/@SortBy[Select[l,SomeFormula==SomeConstant],SortValue&]
Sort[{SortValue+99!(SomeFormula-SomeConstant)^2,#})&/@l]

```
> 2 votes

# Answer
## Flattening an `Array`

When using a multidimensional Array to compute a list of results that needs to be flattened, use a function with the attribute `Flat` as the fourth argument. The final result will be flattened with the specified head.

There are 23 such built-in functions at the time of this writing, 13 of which are also not `Orderless`. Some of the more generally applicable of those might be:

* `Or`, if there are no booleans,
* `Dot`, if there are no consecutive vectors with matching dimensions,
* `Join`, if not all elements have the same head.

In addition, `##&` will also flatten the array's elements; however, `Sequence`s have special behavior when used in most functions, so the Array may often need to be wrapped in `{ }`.

For comparison,

```
Array[f,dims,origin,Or]
{Array[f,dims,origin,##&]}
Join@@Array[f,dims,origin]  (*2d array only*)
Flatten@Array[f,dims,origin]

(* origin = 1 *)
Array[f,dims,1,Or]
{Array[f,dims,1,##&]}
Join@@Array[f,dims]         (*2d array only*)
Flatten[f~Array~dims]

```
> 2 votes

# Answer
# Default values

Default values deal with missing pattern arguments in an efficient way. For example, if we want to pattern match `Exp[c_*x]` in a rule for any value of `c`, the naïve

```
Exp[x] + Exp[2x] /. {Exp[c_*x] -> f[c], Exp[x] -> f[1]}
(*    f[1] + f[2]    *)

```

uses many more bytes than if we use the default value for `c` whenever it is missing:

```
Exp[x] + Exp[2 x] /. Exp[c_.*x] -> f[c]
(*    f[1] + f[2]    *)

```

The use of a default is indicated with a dot after the pattern: `c_.`.

Default values are associated with operations: in the above example, the operation is `Times` in `c_.*x`, and a missing value for `c_` is thus taken from the default value associated with `Times`, which is 1. For `Plus`, the default value is 0:

```
Exp[x] + Exp[x + 2] /. Exp[x + c_.] -> f[c]
(*    f[0] + f[2]    *)

```

For `Power` exponents, the default is 1:

```
x + x^2 /. x^n_. -> p[n]
(*    p[1] + p[2]    *)

```
> 2 votes

# Answer
# Solve and Reduce: automatic list of variables

When the list of variables for `Solve` and `Reduce` is omitted, they solve for all free variables in the expression(s). Examples:

```
Solve[x^4==1]
(*    {{x -> -1}, {x -> -I}, {x -> I}, {x -> 1}}    *)
(*    two bytes saved on Solve[x^4==1,x]            *)

Solve[x^2+y^2==25,Integers]
(*    {{x -> -5, y -> 0}, {x -> -4, y -> -3}, {x -> -4, y -> 3}, {x -> -3, y -> -4},
       {x -> -3, y -> 4}, {x -> 0, y -> -5}, {x -> 0, y -> 5}, {x -> 3, y -> -4},
       {x -> 3, y -> 4}, {x -> 4, y -> -3}, {x -> 4, y -> 3}, {x -> 5, y -> 0}}    *)
(*    six bytes saved on Solve[x^2+y^2==25,{x,y},Integers]                         *)

Reduce[x^2+y^2<25,Reals]
(*    -5 < y < 5 && -Sqrt[25 - y^2] < x < Sqrt[25 - y^2]    *)
(*    six bytes saved on Reduce[x^2+y^2<25,{x,y},Reals]     *)

```

Particularly `Solve` over the `Integers`, `NonNegativeIntegers`, and `PositiveIntegers` is extremely powerful for enumeration problems.
> 2 votes

# Answer
# Use `Alphabet[]` instead of `FromLetterNumber`

The function `Alphabet` was introduced in version 10.1, and it can reduce byte counts when you need to output lower-case/case-insensitive alphabetic strings.

```
FromLetterNumber@{8,5,12,12,15}<>"" (* 35 bytes *)
Alphabet[][[{8,5,12,12,15}]]<>""    (* 32 bytes *)

```
> 2 votes

# Answer
# Use anonymous `RuleDelayed` (`:>`) instead of defining a single-argument function `f@n_:=...`

Sometimes an answer cannot be given as an anonymous function `...#...&` but must be defined as a regular function `f@n_:=...` because of slot collisions. Such a definition, for example

```
f@n_:=Select[Range@n,#~CoprimeQ~n&]

```

can be shortened by two bytes to an anonymous delayed rule

```
n_:>Select[Range@n,#~CoprimeQ~n&]

```

that can be applied to a single argument.
> 2 votes

# Answer
## Consider `Set` instead of `##&[]` and `##2&`

`Set` is equivalent to `(#=##2)&` \- that is, `Set[a, ...]` is interpreted as `a=Sequence[...]`. This returns a `Sequence` of all arguments after the first. Try it online!

As a result, `Set@a` can be used like `##&[]`, but without the precedence issues.

```
a/.b_->Set@c
a/.b_->(##&[])
a/.b_->Nothing

```
> 2 votes

# Answer
# Short forms for function-option combinations

In addition to its extensive list of operator short forms, like `/@` for `Map`, Mathematica also has at least a couple of system-defined short forms for function-option combinations

* `Log[2, n]`=\> `Log2@n`
* `Log[10, n]` =\> `Log10@n`

I don't know of any others, so feel free to either mention them in the comments, or edit this post to add more.
> 2 votes

# Answer
# Use vector inequalities

Vector inequalities `VectorLess`, `VectorLessEqual`, `VectorGreater`, and `VectorGreaterEqual` were introduced in 12.0.

Importantly for golfing, they all have 3-byte private-use characters assigned, making them more efficient than, say, threading a comparison or using a difference.
Their respective characters are:

Note that these operators look similar to, but are distinct from the previously-existing `\[Precedes]`, `\[PrecedesEqual]`, `\[Succeeds]`, `\[SucceedsEqual]`.

---

Like scalar inequalities, the vector inequalities can take any number of arguments and can be chained (into a `Developer`VectorInequality`). They also thread over scalar arguments, including being able to take only scalar inputs. For the most part, they can be thought of as scalar inequalities that thread over lists and return results with `And` applied.

Some edge cases: they return unevaluated if there are non-list non-numeric elements (including e.g. \\$\\{0,a\\}\succ\\{1,0\\}\\$), and as far as I can tell, they always return `False` when the inputs are of different (non-scalar) dimensions.

As a small caveat, the calling syntax is different from that of regular inequalities: \\$a\prec b\\$ is `VectorLess[{a, b}]`, not `VectorLess[a, b]`.
> 2 votes

# Answer
# Change the head when pattern matching subsequences

When pattern matching and replacing a short subsequence in a long list, we usually do something like:

```
{x___,a_,b_,y___}/;someCond:>{x,someExpr,y}

```

Sometimes we can change the head before pattern matching to something with the attribute `Flat`, like `Or` or `Dot`.

For example, this simple bubble sort (38 bytes)

```
#//.{x___,a_,b_,y___}/;a>b:>{x,b,a,y}&

```

can be written as (34 bytes)

```
List@@(Or@@#//.a_||b_/;a>b:>b||a)&

```

or (also 34 bytes)

```
List@@(Dot@@#//.a_ .b_/;a>b:>b.a)&

```

Don't forget to add a space between `_` and `.` when you are using `Dot`, otherwise Mathematica would parse it as an Optional pattern.

But this only works when the input and output both have at least 2 elements.
> 2 votes

# Answer
## Finding the product of a list post-processing

A typical golfy way to find the product of a list of values is by applying `1##&`:

```
1##&@@expr

```

Sometimes, we may need to apply a pure function on all of the values first. In such cases, it's often shorter to wrap the result of that preprocessing in a `List` and use `Dot` instead:

```
Product[bodi,{i,expr}]
1##&@@(body&/@expr)
{body}&/@Dot@@expr

```

If the list has known arguments:

```
1##&@@(body&/@{a,b,c})
{body}&/@Dot[a,b,c]
{body}&/@(a.b.c)

(g=body&)[a]g[b]g@c
#@a#@b#@c&[body&]

```
> 2 votes

# Answer
## Localizing temporary expressions

Some function submissions may involve defining a local expression which should not persist between different calls. For example, this answer uses expressions with head `g` to build paths, (re-)defining `g[#]` for each value in the input list. These paths should be reset on each new input.

The canonical way to do this is with `Module[{g},...]`/`Block[{g},...]`, control structures which localize variables so that definitions made inside them will not propagate outside. For golfing, most of the time we can save a few bytes over these by using `Clear@g` instead, though it may not play nicely with recursion.

In some cases, we can do even better by setting `g=h@#` (or `g=h@##`). However, as subsequent definitions will not be cleared on repeated function calls, care needs to be taken to ensure that the function handles such repeated calls on the same input properly (for example, this answer would fail to do so). Where applicable, though, it not only saves bytes, but also has no issues with recursion.

Comparing these strategies for the linked example:

```
{g}~Module~Depth[i=0;(g@i=g[++i+#]!)&/@#]-3&
{g}~Block~Depth[i=0;(g@i=g[++i+#]!)&/@#]-3&
Depth[i=0Clear@g;(g@i=g[++i+#]!)&/@#]-3&
Depth[g=h@#;i=0;(g@i=g[++i+#]!)&/@#]-3&

```

When using two or more such local expressions, `Block` or `Clear` are the best bet:

```
Module[{a,b},...]
Block[{a,b},...]
(a~Clear~b;...)
(a=p@#;b=q@#;...)

```
> 2 votes

# Answer
## `PreIncrement`/`PreDecrement` can save parentheses

When called on a non-atomic, non-list argument, `PreIncrement`/`PreDecrement` return the incremented/decremented value, albeit with an error message. This can save bytes on increments/decrements that would otherwise require parentheses.

For example, to generate the golden ratio:

```
(√5+1)/2
√5/2+1/2
++√5/2

```

Try it online!

Prepending `+` to an atom or list allows `++`/`--` to be used on them as well, thanks to the `HoldFirst` attribute. `-` works as well if the target is not a literal number. In my experience, this is most often useful when used with `#`. Try it online!

This is also only possible because, for whatever reason, `+++x` is interpreted as `++ +x` instead of `+ ++x`.
> 2 votes

# Answer
# Golfing nested pure functions

This is my first post here, would be grateful for comments and corrections!

Let there is some pure function as criterion in `Select`, `MaximalBy` etc.:

```
Select[list, crit[#]&]

```

And inside this criterion we need some calculations with `Map`, `Table` etc which may also be presented as pure function:

```
crit[arr_, x_] := Table[f[x, e], {e, arr}]

```

eq to

```
crit[arr_, x_] := f[x, #]&/@arr

```

Sometimes the whole construction may be effectively golfed with `Fold`, `Outer` etc.
But sometimes not, and we have troubles with correctly using slots in nested pure functions:

```
Select[ list, (f[#!!wrong!!, #]&/@arr)& ]

```

Possible golfing solution (without Table or Map) may be like this (thanks to @att):

```
Select[list, (x=#;f[x,#]&/@arr)&]

```

or

```
Select[list, x|->f[x,#]&/@arr]

```

or sometimes

```
(f[x,#]&/@arr)/.x->#&

```
> 1 votes

# Answer
# Check for duplicates

`UnsameQ@@` is 6 bytes shorter than `DuplicateFreeQ@`.
But if performance matters, `UnsameQ` is over 1000 times slower.
> 1 votes

---
Tags: code-golf, tips
---


title: Esolang-Comment-Template-Generator

text:
# Question
Title: Esolang-Comment-Template-Generator
Lots of people on this site use esoteric languages, and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was

```
abcdefghijklmnop

```

And this languages uses `#` for comments, they would write an explanation like this:

```
a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth

```

I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template:

```
a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #

```

# The Challenge:

You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (`|`) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input:

```
"a|bc|d|e|fgh|ij|k|l|mn|op", "#"

```

Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines.

Hopefully you can infer what to do from the testcases, but I'll try to clarify some things.

You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character".

One trailing newline is allowed.

Here is another example. For the input

```
"Hello|World", "/"

```

The first *section* of code is "Hello" and the second is "World". So it should give the output:

```
Hello      /
     World /

```

Here are some more samples:

```
Input:
"a|b|c|d|e|f|g", ","

Output:
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

Input:
"abcdefg", ":"

Output:
abcdefg :

Input:
"4|8|15|16|23|42", "%"

Output:
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

Input:
"E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!"

Output:
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

Input:
"This|Code|has||empty||sections", "@"

Output:
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @

```

# Rules:

You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is , so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. Standard loopholes are banned.

# Answer
# Pyth - ~~28~~ ~~27~~ ~~24~~ 23 bytes

~~Might be able to golf a little off.~~ A lot off, apparently!

```
jt+R+;zC.t.u+*lNdYcQ\|k

```

Try it online here.
> 7 votes

# Answer
# Java 11, ~~189~~ ~~159~~ 136 bytes

```
s->c->{int p=0;for(var a:s.split("\\|"))System.out.println(" ".repeat(p)+a+" ".repeat(s.replace("|","").length()-(p+=a.length())+1)+c);}

```

-30 bytes converting Java 7 to Java 10 and optimizing the loops.
-23 bytes converting Java 10 to Java 11, so `String#repeat` builtin can be used.

Try it online.

**Explanation:**

```
s->c->{                     // Method with String & char parameters and no return-type
  int p=0;                  //  Position-integer, starting at 0
  for(var a:s.split("\\|")) //  Loop over the parts split by "|":
    System.out.println(     //   Print with trailing newline:
      " ".repeat(p)         //    `p` amount of spaces
      +a                    //    plus the current part
      " ".repeat(s.replace("|","").length()-(p+=a.length())+1)
                            //    plus the correct trailing amount of spaces
                            //    (and add the length of the current part to `p` at the
                            //    same time)
      +c);}                 //    plus the current comment character

```
> 10 votes

# Answer
## Retina, ~~35~~ 34 bytes

Byte count assumes ISO 8859-1 encoding.

```
\|
·$'¶$`±
T0-2`·±|p`___ `.+±.|·.+

```

The two input strings are separated by a space (which is unambiguous since we know that the comment delimiter is always a single character).

Try it online!
> 9 votes

# Answer
## Pyke, ~~31~~ ~~28~~ 24 bytes

```
\|cDslF2l-hd*Q+Zi:il?+ZK

```

Try it here!
> 6 votes

# Answer
## JavaScript (ES6), 92 bytes

```
f=
(s,c)=>s.split`|`.map((_,i,a)=>a.map((e,j)=>i-j?e.replace(/./g,` `):e).join``+` `+c).join`
`
;
```

```
<div oninput=o.textContent=f(s.value,c.value)><input id=s placeholder=Code><input id=c size=1 maxlength=1 value=#><pre id=o>
```
> 5 votes

# Answer
# Python 2, ~~107~~ ~~105~~ ~~102~~ 99 bytes

Tested with all test cases above

**EDIT** Golfed off 2 bytes by changing d=a.split("|");i=0 to d,i=a.split("|"),0 Not sure how I missed that one. Thanks @Oliver Ni

Another 3 bytes gone. Thanks again.

Suggestion from @Jonathan actually saves 3 bytes and takes it down to the magic 99. Thanks.

```
def c(a,b):
 d,i=a.split("|"),0
 for e in d:j=i+len(e);print" "*i+e+" "*(len("".join(d))-j+1)+b;i=j

```
> 4 votes

# Answer
# GNU sed (85 + 1 for -r) 86

```
:s;h;:;s,\|( *)[^ \|](.),|\1 \2,;t;s,\|,,g
p;g;:l;s,^( *)[^ \|],\1 ,;tl;s,\|,,;/\S/bs

```

The inputs are strings separated by a space.

**Tests:**
input.txt:

```
a|b|c|d|e|f|g ,
abcdefg :
4|8|15|16|23|42 %
E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last! !
This|Code|has||empty||sections @

```

Output:

```
$ cat input.txt | sed -rf template
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

abcdefg :

4          %
 8         %
  15       %
    16     %
      23   %
        42 %

E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @

```
> 4 votes

# Answer
# Python 2, ~~125 124~~ 132 bytes

-1 byte thanks to @TuukkaX (missed golfing the space from `i, v`)

```
def g(s,c):x=s.split('|');print((' '+c+'\n').join(' '*len(''.join(x[:i]))+v+' '*len(''.join(x[i+1:]))for i,v in enumerate(x))+' '+c)

```

All test cases on **ideone**
> 3 votes

# Answer
# Haskell, ~~139~~ 135 bytes

```
s#p=j$foldl g("",0)s where g(a,n)c|c=='|'=(j(a,n)++"\n"++q n,n)|1>0=(a++[c],n+1);q m=' '<$[1..m];j(a,n)=a++q(sum[1|c<-s,c/='|']-n+1)++p

```

Saved 4 bytes by inlining a definition.

**Ungolfed:**

```
template :: String -> String -> String
template code comment = format $ foldl g ("", 0) code
    where g (acc, n) c
            | c == '|' = (format (acc, n) ++ "\n" ++ spaces n, n)
            | otherwise = (acc ++ [c], n+1)
          l = length $ filter (/= '|') code
          spaces n = replicate n ' '
          format (acc, n) = acc ++ spaces (l-n+1) ++ comment

```
> 3 votes

# Answer
# Groovy, ~~120~~ ~~113~~ 111 Bytes

```
def m(s,c){s.split(/\|/).inject(0,{e,t->println((' '*e+t).padRight(s.replace('|','').size()+1)+c);e+t.size()})}

```

**ungolfed\***

```
def m(s,c){
  s.split(/\|/).inject(0, { e, t ->
    println((' '*e+t).padRight(s.replace('|','').size())+' '+c)
    e+t.size()
  })
}

```

# (First Draft with 120 Bytes)

```
def m(s,c){def l=0;s.split(/\|/).collect{l+=it.size();it.padLeft(l).padRight(s.replace('|','').size())+' '+c}.join('\n')}

```

**ungolfed\***

```
def m(s,c){
  def l=0 // minimized version needs a semicolon here
  s.split(/\|/).collect{
    l+=it.size() // minimized version needs a semicolon here
    it.padLeft(l).padRight(s.replace('|','').size())+' '+c
  }.join('\n')
}

```

**Tests**

```
%> m('a|bc|d|e|fgh|ij|k|l|mn|op', '#')
a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #

%> m('Hello|World', '/')
Hello      /
     World /

%> m('a|b|c|d|e|f|g', ',')
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

%> m('abcdefg', ':')
abcdefg :

%> m('4|8|15|16|23|42', '%')
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

%> m('E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!', '!')
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

%> m('This|Code|has||empty||sections', '@')
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @

```
> 3 votes

# Answer
# 05AB1E, ~~29~~ ~~38~~ ~~31~~ 29 bytes

```
'|„ǝʒ:'ǝ¡'ʒмεD®>úsg®+©s}.Bεð²J,

```

Can definitely be golfed, but at least its working now..
+9 bytes because `¡` (split) removes empty items automatically, so I had to add `'|„ǝʒ:'ǝ¡'ʒм`..
-2 bytes thanks to *@MagicOctopusUrn* by changing `'|„ǝʒ:'ǝ¡'ʒм` to `'|¶:.BεðÜ}` (current solution doesn't work on items with trailing spaces, but I've assumed that's allowed according to the test cases).

Try it online.

**Explanation:**

```
'|¶:           # Take the first input, and replace every "|" with "¶"
               #  i.e. "abc|d|e||fg" → "abc¶d¶e¶¶fg" (¶ are new-lines in 05AB1E)
    .B         # Box all the items (appending trailing whitespace to make it a rectangle)
               #  i.e. "abc¶d¶e¶¶fg" → ['abc','d  ','e  ','   ','fg ']
      εðÜ}     # Remove all trailing spaces from each item
               #  i.e. ['abc','d  ','e  ','   ','fg '] → ['abc','d,'e','','fg']
               #  NOTE: `'|¡` would have resulted in ['abc','d','e','fd'], hence the use of
               #        Box which implicitly splits on new-lines to keep empty items
ε              # For-each:
 D             #  Duplicate the current item
  ®>ú          #  Prepend global_variable + 1 amount of spaces
               #  (+1 because the global_variable is -1 by default)
               #   i.e. "e" and 3+1 → "    e"
 sg            #  Swap so the duplicated item is at the top, and take its length
   ®+          #  Sum it with the global_variable
               #   i.e. "e" (→ 1) and 4 → 5
     ©         #  And store it as new global_variable
      s        #  Then swap so the space appended item is at the end again
       }       # And end the for-each loop
.B             # Box all the items (appending the appropriate amount of spaces)
               #  i.e. ['abc','   d','    e','     ','     fg']
               #   → ['abc    ','   d   ','    e  ','       ','     fg']
ε              # For-each again:
 ð             #  A space character
  I            #  The second input-character
   J           #  Join both together with the current item
    ,          #  And print the current row with trailing new-line

```
> 3 votes

# Answer
# Japt `-R`, 17 bytes

There's a byte to be saved here, *at least*, I just can't quite see it.

```
q| ËùT±DÊÃú Ë+ViS

```

Try it

```
q| ËùT±DÊÃú Ë+ViS     :Implicit input of strings U=programme & V=character
q|                    :Split U on |
   Ë                  :Map each D
    ù                 :  Left pad with spaces to length
     T±               :    Increment T (initially 0) by
       DÊ             :    Length of D
         Ã            :End map
          ú           :Right pad each with spaces to length of longest
            Ë         :Map
             +        :  Append
              Vi      :    V prepended with
                S     :      Space
                      :Implicit output joined with newlines

```
> 3 votes

# Answer
## PowerShell v2+, ~~103~~ 99 bytes

```
param($a,$b)$a-split'\|'|%{" "*$l+$_+" "*(($a-replace'\|').length+1-$_.length-$l)+$b;$l+=$_.Length}

```

Takes input as two strings, `-split`s the first on literal pipe (since split uses regex syntax), and feeds the elements into a loop `|%{...}`.

Each iteration, we construct a string as being a number of spaces defined by `$l` concatenated with the current element. For the first loop, `$l` initializes to `$null`, which gets evaluate here as `0`.

That string is further concatenated with another number of spaces (defined by how long `$a` would be if we `-replace`d every pipe with nothing, plus `1` for the additional padding between code and comments, minus the `.length` of the current element, minus `$l` which is how many spaces we padded left on this iteration), concatenated with our comment character `$b`. That's left on the pipeline.

We then update `$l` for the next iteration.

The resultant strings are all left on the pipeline, and output via implicit `Write-Output` happens at program execution, with a newline between them by default.

### Examples

```
PS C:\Tools\Scripts\golfing> .\esolang-comment-template-generator.ps1 "This|Code|has||empty||sections" "@"
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @

PS C:\Tools\Scripts\golfing> .\esolang-comment-template-generator.ps1 "a|bc|def|ghi|h" "|"
a          |
 bc        |
   def     |
      ghi  |
         h |

```
> 2 votes

# Answer
# Vim, ~~39~~ 38 keystrokes

-1 byte thanks to DJMcMayhem

Expects as input a buffer (e.g. a file) whose first character is the comment delimiter, followed by the code, e.g. `#foo|bar|baz`.

```
"cxqaf|m`Yp<Ctrl+o>v$r jv0r x@aq@a$p<Ctrl+v>gg$C <Ctrl+r>c<Esc>

```

## Explanation

("`_`" denotes a literal space.)

```
"cx          " Delete the first character (the comment delimiter) and store in register 'c'
qa           " Start recording macro 'a'
f|m`         " Advance to the first '|' on the line and set mark
Yp<Ctrl+o>   " Duplicate this line and return to mark
v$r_         " Replace everything after the cursor on this line (inclusive) with spaces
jv0r_x       " Go down a line and replace everything before the cursor on this line (inclusive) with
             "   spaces, then delete one space
@a           " Call macro recursively
q@a          " Stop recording and immediately call the macro
$p           " Paste the deleted space at the end of the last line
<Ctrl+v>gg$       " Highlight the column where the comment delimiters will go and all trailing spaces
C_<Ctrl+r>c<Esc>  " Replace the highlighted text on each line with a space and the contents of
                  "   register 'c' (the comment delimiter)

```
> 2 votes

# Answer
# Floroid \- 94 bytes

```
Ah(a,b):c=a.fn("|");z(" "+b+"\n".y(' '*Z("".y(c[:j]))+l+" "*Z("".y(c[j+1:]))Kj,lIai(c))+' '+b)

```

Uses an approach similar to @JonathanAllans' Python solution.

## Testcases

```
Call: h("a|bc|d|e|fgh|ij|k|l|mn|op", "#")
Output:
a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #

```
> 2 votes

# Answer
# C# 176 167 154 bytes

```
string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c)d+=b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n";return d;}

```

UnGolfed

```
string f(string s, char x)
{
    var c = s.Split('|');
    var d = "";
    int i = 0;
    foreach (var b in c)
        d += b.PadLeft(i += b.Length).PadRight(s.Length + 2 - c.Length) + x + "\n";
    return d;
}

```

A LINQ solution would have been 146 but needed `using System.Linq;` bringing it back up to 164:

```
string f(string s,char x){var c=s.Split('|');int i=0;return c.Aggregate("",(g,b)=>g+b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n");}

```

Old solutions:

167 bytes:

```
string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=b.PadLeft(i+b.Length).PadRight(s.Length+2-c.Length)+x+"\n";i+=b.Length;}return d;}

```

176 bytes using string interpolation

```
string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=string.Format($"{{1,{i}}}{{0,-{s.Length+2-c.Length-i}}}{x}\n",b,"");i+=b.Length;}return d;}

```
> 2 votes

# Answer
# Perl, 63 bytes

Includes +5 for `-Xpi`

Run with input on STDIN and comment character after -i:

```
perl -Xpi% esolang.pl <<< "Ab|Cd||ef"

```

`esolang.pl`:

```
s/
/|/;s%(.*?)\|%$"x$`=~y/|//c.$1.$"x$'=~y/|//c." $^I
"%eg

```

Totally boring straightforward solution
> 2 votes

# Answer
# Jelly, 10 bytes

```
ṣ”|⁶ṁ;ɗ\pG

```

Try it online!
> 2 votes

# Answer
# AWK, 107 104 103 bytes

```
w=2-(n=split($1,p,"|"))+gsub(t=".",FS,$1){for(;s++<n;gsub(t,FS,b))y=y substr((b=b p[s])$1,1,w)$2RS}$0=y

```

Try it online!

*Thanks to Pedro Maimere for helping shave off more 3 chars*

One interesting thing about this challenge... I found a quirk about the TIO AWK setup. I can't figure out way to specify input where a positional argument can contain a space. Meaning setup a TIO test that behaves like this commandline,

```
echo "this is the first parameter" second | gawk '{ print $1 }'

```

In TIO, the first parameter will be `"this` not the whole string. That means while it works in a terminal window, I can't show that it handle the second test for this challenge in TIO.

Here's how the code works... The test associated with the codeblock is always truthy, so the code always runs. It's only a test (rather then code) to avoid needing a `;` character. It does a couple of things by using AWK's willingness to combine multiple expressions into one "line" of code.

```
w=2-(n=split($1,p,"|"))+gsub(t=".",FS,$1)

```

First is splits the first parameter into in array of strings using the pipe character as the delimeter with `n=split($1,p,"|")`. It also saves the number of substrings generated in `n`. Then it changes all the characters in the first parameter to spaces with `gsub(t=".",FS,$1)` setting convenience constants `t` and `n` in the process.

Finally the value of `w` is set to the number of non-pipe characters in the first parameter by subtracting the number of sub-strings from the total number of characters in the original.

The associated code block is one statement, a `for` loop, that processes each substring.

```
for(;s++<n;gsub(t,FS,b))y=y substr((b=b p[s])$1,1,w)$2RS

```

The iteration check is simple `s++<n`. The end of loop statement converts all the characters in the previous output line to blanks `gsub(t,FS,b)`, which turns it into the prefix for the next line. The body of the loop constructs and appends the next line of output to an accumulator `y`. That string is a concatenation of the previous string, plus the current string (code fragment) with a bunch of blanks appended (meaning `$1`) `(b=b p[s])$1`. That mess is truncated to the length we want `w` and the comment delimiter and LF are appended with `y=y substr(...,w)$2RS`.

Once all the code substrings have been processes, assigning `$0` to the accumulator takes care if printing out the results.

```
$0=y

```
> 2 votes

# Answer
# JavaScript (Node.js), 79 bytes

```
c=>s=>s.split`|`.map((_,i,a)=>a.map(y=>i--?y.replace(/./g,' '):y).join``+' '+c)

```

Attempt This Online!

+4 to add an extra space before `#`
> 2 votes

# Answer
# Vyxal `j`, 74 bits<sup>v2</sup>, 9.25 bytes

```
\|/:¦↳:t↲Ḋ

```

Try it Online!

Bitstring:

```
01101010100010101110000101000000110001011111111110001111111100110011110001

```

## Explained

```
\|/:¦↳:t↲Ḋ
\|/         # Split on "|"s
   :¦       # Push the cumulative sums without popping. This acts as the space length before each section
     ↳      # Pad each item right with spaces to length in ^
      :t↲   # And pad each item left with spaces to length of tail of ^
         Ḋ  # Append " {comment char}" to each
Implicitly join on newlines

```

Created with the help of Luminespire and not this challenge.
> 2 votes

# Answer
# Ruby, ~~96~~ 80 bytes

```
->s,c{s.gsub(/(^|\|)([^|]*)/){" "*$`.count(t="^|")+$2+" "*(1+$'.count(t))+c+$/}}

```

See it on eval.in: https://eval.in/639012

I really ought to just learn Retina.
> 1 votes

# Answer
# PHP, ~~120~~ ~~117~~ ~~116~~ ~~110~~ 109 bytes

```
foreach($a=split('\|',$argv[1])as$i=>$t){$c=preg_replace('#.#',' ',$a);$c[$i]=$t;echo join($c)," $argv[2]
";}

```

or

```
foreach($a=split('\|',$argv[1])as$t){$c=preg_replace('#.#',' ',$a);$c[$i++|0]=$t;echo join($c)," $argv[2]
";}

```
> 1 votes

# Answer
# MATL, ~~33~~ 31 bytes

```
'\|'0'|'hYXo8M&YbY:&YdtaZ)0ihYc

```

Try it online!

### Explanation

The builtin function `Yd` (`blkdiag`), which builds a block-diagonal matrix from its inputs, does most of the work. The fill values in the matrix are 0, and char 0 is treated as a space for displaying purposes. The code would simply split on `|`, build a matrix from the resulting blocks, convert to char, and append two columns with space and comment symbol.

However, the possibility of empty sections in the input string ~~complicates~~ makes the problem more interesting: the resulting block would be empty and thus wouldn't show in the resulting matrix.

To solve this, we introduce a char 0 before each `|`, so no block will be empty; and then in the resulting char matrix we remove columns that are formed by char 0 only. A non-empty code section will have some printable ASCII char, and thus the columns it spans will survive. An empty section will contribute a row, but won't introduce an extra column.

```
'\|'    % Push this string: source for regexp matching. It's just | escaped
0'|'h   % Push a string formed by char 0 followed by | (no escaping needed)
YX      % Input string implicitly. Replace first of the above string by the second
o       % Convert from chars to code points. Gives a numeric vector
8M      % Push '|' again
&Yb     % Split numeric vector at occurences of | (the latter is automatically
        % converted  to its code point). This gives a cell array of numeric vectors
Y:      % Unbox cell array: pushes the numeric vectors it contains
&Yd     % Form a block-diagonal matrix from those vectors
ta      % Duplicate. Compute vector that equals true for columns that have some
        % nonzero value
Z)      % Used that as a logical index (mask) for the columns of the matrix.
        % This removes columns that contain only zeros
0ih     % Input comment symbol and prepend char 0 (which will be displayed as space)
Yc      % Append that to each row of the matrix. The matrix is automatically
        % converted from code points to chars
        % Display implicitly

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 28 bytes

Full program. Prompts for code, then for comment character.

```
⍞,⍤1⍨⎕FMT⎕TC[2]@('|'∘=)⍞,' '

```

Try it online!

`⍞,' '` append a space the to prompted-for code

`⎕TC[2]@(``)` place the 2nd Terminal Control character (Line Feed) **at** the positions indicated by:

`'|'∘=` the mask indicating where the pipe symbol is equal to the characters

`⎕FMT` ForMaT as a character matrix, evaluating terminal control characters (Line Feed moves the "cursor" down one line)

`⍞,⍤1⍨` prompt for comment character and append it to each line (lit. to each 1D sub-array)
> 1 votes

# Answer
# Pyth, 30 bytes

```
VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN

```

or

```
jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ

```

Both are full programs that take input on STDIN of the comment string, and then the program string, newline-separated.

Try the first version online

Try the second version online

**How they work**

```
VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN  Program. Inputs: E, Q
  cE\|                          Split E on "|"
 J                              Assign to J
                                Implicit Z=0
V                               For N in that:
       [                )        Create a list with elements:
        *Zd                       Z spaces
           N                      N
               -lsJZ              len(concatenate(J))-Z
              -     lN             -len(N)
             h                     +1
            *         d            spaces
                       Q          Q
      s                          Concatenate the list
                                 Implicitly print
                        =+ZlN    Z=Z+len(N)

jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ  Program. Inputs: E, Q
                       +Ed      Add a trailing space to E
                      c   \|    Split that on "|"
                     J          Assign to J
             .u                 Cumulatively reduce J with:
                            k    starting value empty string and
                                 function N, Y ->
                l+NY              len(N+Y)
               *    d             spaces
            ,                J  Two-element list of that and J
           C                    Transpose
         +M                     Map concatenation over that
       .t                       Transpose, padding with spaces
     .t                         Transpose again
 m+dQ                           Map concatenation with Q over that
j                               Join on newlines
                                Implicitly print

```
> 1 votes

# Answer
# GolfScript, 85 bytes

```
{(;);}:r;", "%(r\(r n+:c;;.,\'|'%.,@\-)):l;0:m;{.,0>}{" "m*\(.,m+:m l\-" "\*+c@}while

```

Try it online

# 2017 Update - GolfScript \- 71 bytes

```
', '/~~:c;~1/.,\.{'|'=},,@\-):l;['|']/0:i;{.,i+:i l i-' '*c+\' '*"
"\}/

```

### Explanation

```
', '/~~:c;~1/        # Parses input
.,\.{'|'=},,@\-):l;  # Computes string length without '|'
['|']/               # Splits the array
0:i;                 # Counter
{.,                  # Length of the substring
i+:i                 # Counter update
l i-' '*c+\          # Adds spaces after the substring
' '*"\n"\            # Adds spaces before the next substring
}/                   # ...For each substring

```
> 1 votes

# Answer
# Turtlèd, 35 bytes (noncompeting)

Takes one input, the last character is the comment character. Does not work with comment character as space, but I assume that isn't necessary.

```
!' [*.+(|' dl)r_]' r[*+.(|u)_][ .d]

```

Explanation:

```
!                                  take input into string variable
 '                                 write space over current cell
   [*           ]                  while cell is not *
     .+                            write pointed char of string, stringpointer+1 (starts 0)
       (|    )                     if current cell is |
         ' dl                      write space (over |), move down, left
              r_                   move right, write * if pointed char is
                                   last char, else space

                 ' r               write space, move right
                    [*       ]     while cell is not *
                      +.           increment pointer and write pointed char
                        (|u)       if cell is |, move up
                            _      write * if the pointed char is the last char

                              [   ] while cell is not space
                                .d  write the pointed char from string, move down

```
> 1 votes

# Answer
# Funky, 89 bytes

```
s=>c=>{y=0forn inl=s::split"|"print((v=" "::rep)(y)+l[n]+v((#l::reduce@++1)-y+=#l[n])+c)}

```

Try it online!
> 1 votes

# Answer
# Python 3, 108 bytes

```
s,c=input().split("|"),input()
i,S=0,len("".join(s))
for l in s:L=len(l);print(" "*i+l+" "*(S-L-i+1)+c);i+=L

```

Try it online! Simple solution -- keep track of how many spaces we have (i) and accumulate.
> 1 votes

# Answer
# Python 3.8 (pre-release), 99 bytes

Different approach:

```
def f(c,d,i=0):
 for y in(x:=c.split('|')):z=[' '*len(e)for e in x];z[i]=y;print(''.join(z),d);i+=1

```

Try it online!

Ungolfed with explanation:

```
def f(c,d,i=0):
 x=c.split('|')              # break string by '|'
 for y in x:                 # for each element of list
  z=[' '*len(e) for e in x]  # create a list of blank strings
  z[i]=y                     # insert element we care about into otherwise blank list
  print(''.join(z),d)        # print line
  i+=1                       # increment

```
> 1 votes

# Answer
# Stax, 16 bytes

```
ù3l╛CrΣ╝▀↕┘╣óétº

```

Run and debug it
> 1 votes

# Answer
# Go, 209 bytes

```
import."strings"
func f(C,c string)string{L,Q,S:=Split(C,"|"),[]string{},0
for _,l:=range L{q:=len(l)
if q<1{continue}
Q=append(Q,Repeat(" ",S)+l+Repeat(" ",len(Join(L,""))-q+1-S)+c)
S+=q}
return Join(Q,"\n")}

```

Attempt This Online!

### Explanation

```
import."strings"
func f(C,c string)string{
// split C into substrings, and init the output slice and space count
L,Q,S:=Split(C,"|"),[]string{},0
// for each substring...
for _,l:=range L{
// if it's empty, skip it
q:=len(l)
if q<1{continue}
// add to the output slice...
Q=append(Q,
    // initial spaces
    Repeat(" ",S)+
    // the substring
    l+
    // the following spaces
    Repeat(" ",len(Join(L,""))-q+1-S)
    // and the comment
    +c)
// increment the space count
S+=q}
// join together with newlines
return Join(Q,"\n")}

```
> 1 votes

# Answer
# JavaScript (Node.js), ~~84~~ 79 bytes

```
c=>s=>s.split`|`.map(l=>z="".padEnd(a=z.length)+l,z="").map(l=>l.padEnd(a+2)+c)

```

Attempt This Online!

Saved 5 bytes by using two iterations instead of 1 but keeping track of the previous string so no number is needed to keep track of the length.
> 1 votes

# Answer
# Japt `-R`, 16 bytes

```
q| åÏiXîÃú m+S+V

```

Try it

The boilerplate is similar to @Shaggy's 17 byte Japt submission.

Explanation:

```
q|                 split on |
   åÏ              cumulatively reduce each X, Y to:
     i               prepend to Y
      Xî             spaces to the length of X
        Ã          end cumulative reduce
         ú         right-pad each to the longest line
           m+      to each, append
             S+V     space (S) and comment char (V)

flag -R            join the final result on newlines

```
> 1 votes

# Answer
# Ruby, ~~80~~ 74 bytes

```
->i,c{a=0;(i=i.split ?|).map{" "*a+_1+" "*(1+i.join.size-(a+=_1.size))+c}}

```

Attempt This Online!

I managed to golf a non-regex based solution to beat the other Ruby. The solution previously tied but I found a slightly different method that is 6 bytes shorter.

Explanation:

`->i,c{…}` Proc (lambda function) taking arguments `i` (code) and `c` (comment)

* `a=0;` Assign variable `a` to zero
* `(i=i.split ?|)` Assign `i` to it split on `|`
* `.map{…}` Map each `_1` in the list to:

+ `" "*a` `a` spaces
    + `+_1` Append the list item
    + `+" "*(…)` Append this many spaces:

    - `1+i.join.size` The size of `i` with `|` removed, plus one for the extra space
        - `-(a+=_1.size)` Add the size of the list item to `a` and subtract `a` from this.
    + `+c` Append the comment character to the end of the line.
> 1 votes

# Answer
# Haskell, 96 bytes

```
f"".lines.map r
r '|'='\n'
r c=c
w=(' '<$)
f l(a:s)c=(w l++a++(w=<<c:s)++c):f(l++a)s c
f l s c=s

```

Attempt This Online!

#### Eplanation

The function `r` is defined to map pipe characters to newlines (`r '|'='\n'`) and every other char to itself (`r c=c`). `lines.map r` thus first replaces all pipes in the input string with new lines (`map r`), and then splits the string at the newlines with the build-in `lines` function. The main function `f` iterates over this list of strings and constructs the output line by line with the expression `w l++a++(w=<<c:s)++c` where

* `a` is the part of the code that appears on the current line
* `c` is the comment character (as a string) that gets put at the end of the line
* `w` is a function that replaces each character of a string by spaces (definde by `w=(' '<$)`)
* `l` is the string of code fragments to the left of `a`, which is put at the beginnig of the line as spaces with `w l`
* `s` is the list of remaining code strings which are also converted to spaces, concatenated, and put after `a` (`c` is added to `s` to get the extra space required before the comment character)
> 1 votes

# Answer
# Uiua, ~~42~~ ~~40~~ 36 bytes

```
≡⊂⬚@ ≡°□\⍚(⊂≡⋅@ )⊕□⍜▽¯⟜\+=,@|:¤⊟@

```

Try it

-2 bytes thanks to chunes :)

This was one of my first Uiua answers, I got so much better in only 2 weeks, and was able to save 10%!
> 1 votes

# Answer
# Perl 5 `-pl`, 50 bytes

```
$f=<>;s%\||$%$"x$'=~y/|//c." $f
".$"x$`=~y/|//c%ge

```

Try it online!
> 1 votes

# Answer
# Scala, 123 bytes

```
def?(i:String,c:String)={var b=0
i.split('|').map{s=>println(" "*b+s+" "*(i.replace("|","").size-b-s.size+1)+c)
b+=s.size}}

```

Test code + Output:

```
?("a|b|c|d|e|f|g", ",")
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

?("abcdefg", ":")
abcdefg :

?("4|8|15|16|23|42", "%")
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

?("E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!")
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

?("This|Code|has||empty||sections", "@")
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @

```
> 0 votes

# Answer
# Jelly, 41 bytes

This looks like it has far to many increments, and probably too many links...

```
ṫø⁹‘‘µFL‘⁶ẋ
‘ị
ḣFL⁶ẋ$;ç@;1ŀ
J’ç@€
ṣ”|Ç;€Y

```

Test it at **TryItOnline**

How?

```
ṫø⁹‘‘µFL‘⁶ẋ  - link 1: get the spaces for after the code, dyadic(split string, index)
 ø           - next chain as a nilad
  ⁹‘‘        - right argument incremented twice (the index we actually want)
ṫ            - tail (get the rest of the split string)
     µ       - next chain as a monad
      FL‘    - flatten, get its length and increment
         ⁶   - a space character " "
          ẋ  - repeat the space character that many times

‘ị           - Link 2: get the code for a line dyadic(index, split string)
‘            - increment the index
 ị           - retrieve the string at that index

ḣFL⁶ẋ$;ç@;1ŀ - Link 3: get the code and join with spaces, dyadic (index, split string)
ḣ            - head: split string[index:]
 FL          - flatten and get its length
     $       - previous two atoms as a monad
   ⁶         - a space character, " "
    ẋ        - repeat the space that many times
      ;      - concatenate with
       ç@    - the result of the previous link (the code) - reverse inputs
         ;   - concatenate with
          1ŀ - the result of Link 1 (the spaces after the code)

J’ç@€        - Link 3: a for loop, monadic(split string)
J’           - [0,...,Len(split string)-1]
  ç@€        - the result of the previous link, with revered inputs, for each

ṣ”|Ç;€Y      - Main Link: dyadic(code string, comment character)
ṣ”|          - split on "|"
   Ç         - the result of the previous link
    ;€       - concatenate each with the comment character
      Y      - join with line feeds
             - implicit print

```
> 0 votes

# Answer
# CJam, 32 bytes

```
l'|/_s,)L@{1$,S*\+}%@f{Se]}lN+f+

```

Explanation

```
l                                  get code string
 '|/                               split into code parts
    _s,)                           length of all the parts +1
        L@{1$,S*\+}%               left pad spaces to every part for the length of the previous parts
                    @f{Se]}        right pad spaces
                           lN+f+   add comment character and newline

```

Try it online
> 0 votes

# Answer
# Thunno 2 `N`, 25 bytes

```
'|/DJl⁺X0Yıyṣs+xðĿnlẏ+ƥ¹+

```

Try it online!

#### Explanation

*(Yes, this is in the exact same format as the outputs for this challenge :P)*

```
'|/DJl⁺X0Yıyṣs+xðĿnlẏ+ƥ¹+  '# Implicit input
'|/                        '# Split the input on "|"
   DJl                      # Duplicate, join, and get length
      ⁺X                    # Increment this and store it in x
        0Y                  # Store 0 in y
          ı                 # Map over the list:
           yṣ               #  Push y spaces
             s+             #  Prepend this to the input
               xðĿ          #  Pad with spaces to length x
                  nlẏ+ƥ     #  Add the length to y
                       ¹+   #  Append the second input
                            # Implicit output, joined on newlines

```
> 0 votes

# Answer
# GolfScript, ~~44~~ 43 bytes

```
~:~;"|"/[""\{\," "*\+.}/,):l;]{l" "*+l<~n}/

```

Try it online!

This was my first GolfScript submission, and I’ve improved quite a lot since I first tried this task.

Explanation:

```
~:~;

```

Eval STDIN as GolfScript. Assign the comment character to the `~` variable, and pop out of the stack, so the code is on top.

Using a symbol instead of a letter as a command name let me remove a whitespace later on.

```
"|"/

```

Split the code on `|`s.

```
[""\{\," "*\+.}/

```

This is equivalent to a scan (reduce, keeping in-between values) by repeating spaces to the length of the previous value, and prepending that to the current value.

GolfScript doesn’t have scan built-in, so this is implemented somewhat cumbersomely, using `/` (each) and duplicating the result each iteration.

```
,):l;]

```

The previous step left an extra copy of the last value. We take its length, increment that, and assign it to `l`.

```
{l" "*+l<~n}/

```

For each line (`{ … }/`): append `l` spaces (`l" "*+`), take the first `l` characters (`l<`), then push `~` (the comment character) and `n` (newline).

The entire stack is printed when the program ends.

Original solution:

## GolfScript, ~~64~~ 63 bytes

```
~n+:c;0:a;."|"/""*,):b;{.124={;b" "*c" "a*}{a):a;b(:b;}if}%" "c

```

Try it online!

Full program, takes input like `"abc|def|g" "#"` on STDIN.

I’ve always thought GolfScript seemed interesting but have never actually tried it. After using quite a few more modern golfing languages with hundreds of built-ins, the terse but very readable syntax of GolfScript is really refreshing. I had a lot of fun trying to get this to work, so I’m glad I could beat the 75 byte solution posted in 2017.

I had a 50-or so byte version that used stack manipulation instead of variables, but couldn’t get it to work.

I hope you like the smileys `):` `(:` `:b` `:c` `={`

## Explanation

Eval the input; this leaves two strings on the stack. Append a newline to the top one, store it in `c` as the comment character, and pop it off the stack. The variable `a` is initialized to 0. The variable `b` is initialized to the length of splitting the input on `|` and joining it back.

The top of the stack is now the `|`-separated string. Map each character of the input string to:

* If the character is `|`, leave `b` spaces, `c`, a newline, and `a` spaces on the stack.
* Otherwise, increment `a`, decrement `b`, and leave the original character in the stack.

Finally, push a space and `c` to the stack. The whole stack is implicitly output at the end.
> 0 votes

# Answer
# Swift 5.9, ~~153~~ 152 bytes

```
let f={var x={{String.init}()(" ",$0)},s=($0+"").split{$0=="|"},i=0
return{s.map{x(i)+$0+x(s.joined().count-(i+=$0.count,i).1+1)}.joined}()($1+"\n")+$1}

```

This is an almost direct port of Kevin Cruijssen's Java answer. Here's an ungolfed version:

```
let function = { (code: String, comment: String) -> String in
  // convenience closure to repeat the space character
  let spaces = { String(repeating: " ", count: $0) }

  // split the code into substrings using the pipe as
  // a separator
  let splitCode = code.split(separator: "|")

  var indentLevel = 0

  let indentedCode = splitCode.map { line in
    // start off with the previous indent level
    let leadingIndent = spaces(indentLevel)

    // update the indent level for the trailing indent
    // and the next leading indent
    indentLevel += line.count

    // gets the total length of the code, subtracts the
    // current indent level, and adds 1 for an extra
    // trailing space
    let trailingIndentAmount = splitCode.joined().count - indentLevel + 1
    let trailingIndent = spaces(trailingIndentAmount)

    return leadingIndent + line + trailingIndent + comment
  }

  // finally, join the code with newlines and return it
  return indentedCode.joined(separator: "\n")
}

```
> 0 votes

# Answer
# Perl 5 \+ `-lF\| -M5.10.0`, 31 bytes

A different approach to both the existing Perl answers.

```
$,=v12;say@F," .[A@{[<>]}.."x@F
```

Try it online!

## Explanation

Sets `$,` (which is the record separator, automatically printed between each item of a list) to `v12` (which is `chr(12)`, or form feed - which moves the cursor down a line), then we `say` `@F` (which is the input, split on `|`), followed by a raw string consisting of space, the ANSI escape sequence for "up one line", the comment char from STDIN (`<>`), which is embedded to the string using `@{[...]}`, and two backspace characters, which is repeated the same number of times as there are items in the input (using the list of input, `@F`, in a scalar context yield the list length).
> 0 votes

---
Tags: code-golf, string, comment
---