I find myself recently writting, more often than not, code that makes heavy use of RightComposition eg.
expr//f/*g/*h
It is relatively straightforward to first operate on expr with f then apply g on the result and so on with operators like h etc.
It gets cumbersome, however, to operate on complicated expressions eg. head1[expr1,head2[expr2]]; also, performing contrived operations gets progressively hard to handle.
I find that the major drawback of writing one-liners like that, hits hardest when subsequent operations need input consumed by operators applied earlier on.
To tackle this problem I find myself making heavy use of Through eg.
expr//(Through[{Identity,f}[#]]&)/*Apply[g]
In the code snippet, g needs both expr and f[expr] as input and this is where Through comes in handy.
Carrying intermediate results to subsequent operators, in that fashion, proves equally cumbersome esp. when the chain of operations is long.
Trying to find a compromise that allows me to keep writting one-liners that are relatively easy to maintain, debug and help mitigate their downsides I came up with chainList:
chainList[expr_, fs__] := Fold[Join[#1,{#2@@#1}]&, {expr}, {fs}]
chainList resembles FoldList in that it returns a list of intermediate results eg.
chainList[x,f,g,h]
evaluates to
{x,f[x],g[x,f[x]],h[x,f[x],g[x,f[x]]]}
I have experimented with different implementations of chainList but I can't seem to find an implementation that performs faster than the one presented above.
It is true that speed is not so much of an issue for most of my practical needs as I rarely chain more than 5-7 operators in a line and operations are mostly structural modifications of the expressions involved; however I would like to find out if there's a better approach to handling one-liners and also if chainList can be improved.
ComposeListlooks promising, also I didn't knowReverseAppliedwas a thing – joka Jan 02 '22 at 18:42expr//f//g//h? – userrandrand Nov 27 '22 at 01:05g[x,f[x]]I would dox// g[#,f@#]&which is easier to understand and read in my opinion. Readability is important for the me in 2 years that has to read the code again. – userrandrand Nov 27 '22 at 01:39x // {Identity, f} // Through //Apply[g]but that is more adapted to writing the code in a column using the code cell style – userrandrand Nov 27 '22 at 01:40