2

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?

eldo
  • 67,911
  • 5
  • 60
  • 168

3 Answers3

5

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]]] *)
kglr
  • 394,356
  • 18
  • 477
  • 896
3

It is Composition

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

(Composition @@ Most@list)@Last@list
(* Tan[Sin[Cos[x]]] *)
ybeltukov
  • 43,673
  • 5
  • 108
  • 212
1
Apply[Apply[Composition, Drop[%, -1]], Take[%, -1]]
Igor Rivin
  • 5,094
  • 20
  • 19