2
$\begingroup$

I have a nested expression like this one

expr = Tan[Sin[Cos[x]]];

I can deconstruct it with

sym = Cases[Level[expr, -1, Heads -> True], _Symbol]

{Tan, Sin, Cos, x}

How can I put it together again? The only way I found is

ToExpression @ StringJoin @ Most @ Flatten @
  Transpose[{ToString /@ sym, Table["@", {Length @ sym}]}]

Tan[Sin[Cos[x]]]

Is there a way to do this without using String - functions?

$\endgroup$
5
$\begingroup$

Obsolete since 1991 but ... still working and useful:)

lst = {Tan, Sin, Cos, x};
Compose @@ lst
(* Tan[Sin[Cos[x]]] *)

enter image description here

or, Fold:

foldF = Fold[#2[#] &, #, {##2}] & @@ Reverse@# &;
foldF@lst
(* Tan[Sin[Cos[x]]] *)
$\endgroup$
  • $\begingroup$ +1 Why this function is outdated?? :) $\endgroup$ – ybeltukov Oct 9 '14 at 17:12
  • $\begingroup$ @ybeltukov, good question:) $\endgroup$ – kglr Oct 9 '14 at 17:13
  • $\begingroup$ Beat me to it. +1 $\endgroup$ – Mr.Wizard Oct 9 '14 at 17:24
  • $\begingroup$ @ybeltukov Apparently because someone thinks we are supposed to use Composition instead. That doesn't stop me from using these "retired" functions when I learn about them. I am also a fan of ToHeldExpression. $\endgroup$ – Mr.Wizard Oct 9 '14 at 17:26
  • $\begingroup$ @kguler I hurry to accept before this question is (rightfully) closed :) $\endgroup$ – eldo Oct 9 '14 at 17:44
3
$\begingroup$

It is Composition

list = {Tan, Sin, Cos, x};

(Composition @@ Most@list)@Last@list
(* Tan[Sin[Cos[x]]] *)
$\endgroup$
1
$\begingroup$
Apply[Apply[Composition, Drop[%, -1]], Take[%, -1]]
$\endgroup$

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