# How to create an equivalent of Clojure's threading macro in Mathematica?

Clojure, a Lisp type of language, has a so called Thread macro which converts nested function calls into a linear flow of function calls, thus improving readability, testability and inviting pure functional (reactive) programming.

I suppose that an equivalent in Mathematica would work as follows:

Let

 listany = {{1, 2}, {3, 4}};
listopr = {Flatten, Map[f], Map[g]};


and assume that t is the equivalent of Clojure's -> ( thread macro ), and $f$ and $g$ are functions transforming elements of listany. Then:

 t[listany, listopr]


would be translated to

 Map[g]@Map[f]@Flatten@listany


Similarly,

 t[5, {f, g, h}]


would be translated to

 h@g@f@5


Do you have a suggestion on how to implement t in Mathematica?

• – Carl Woll Feb 16 '17 at 18:52
• I knew it had to be somewhere in Mma. Suppose this works. – nilo de roock Feb 16 '17 at 19:16
• @niloderoock Would you consider penning a self-answer, perhaps exploring the use of those two newly discovered functions? – MarcoB Feb 16 '17 at 21:05
• Be careful with Composition: try x = 1; SymbolName@Unevaluated@x vs Composition[SymbolName, Unevaluated][x] more in closely related: 54762 – Kuba Feb 16 '17 at 21:14

Inefficiently your operation is performed by ComposeList:

ComposeList[listopr, listany] // Last

{g[f[1]], g[f[2]], g[f[3]], g[f[4]]}


Composition

(Composition @@ Reverse @ listopr) @ listany


New-in-v10 RightComposition

(RightComposition @@ listopr) @ listany


The deprecated but reliable function Compose can also be applied with work:

Compose @@ Append[Reverse @ listopr, listany]


As Kuba comments these forms do not evaluate in the same way as the literal form. If you wish to create the complete expression before evaluation consider comp from my self-answer to: