# Reconstructing an expression [duplicate]

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?

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

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


or, Fold:

foldF = Fold[#2[#] &, #, {##2}] & @@ Reverse@# &;
foldF@lst
(* Tan[Sin[Cos[x]]] *)

• +1 Why this function is outdated?? :) – ybeltukov Oct 9 '14 at 17:12
• @ybeltukov, good question:) – kglr Oct 9 '14 at 17:13
• Beat me to it. +1 – Mr.Wizard Oct 9 '14 at 17:24
• @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. – Mr.Wizard Oct 9 '14 at 17:26
• @kguler I hurry to accept before this question is (rightfully) closed :) – eldo Oct 9 '14 at 17:44

It is Composition

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

(Composition @@ Most@list)@Last@list
(* Tan[Sin[Cos[x]]] *)

Apply[Apply[Composition, Drop[%, -1]], Take[%, -1]]