5
$\begingroup$

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?

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

1 Answer 1

6
$\begingroup$

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:

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.