10

I need to use:

Composition[G][x]

in the elements of the following list:

j = {{a, b, c}, {c, b, a}};

That is, I could do:

Table[Composition[j[[n]]][x], {n, 1, 2}]

which produces:

{{a, b, c}[x], {c, b, a}[x]}

but Composition doesn't seem to work with lists. I can't evaluate Composition[{a,b,c}][x]; it accepts only Composition[a,b,c][x].

Is there a simple way to convert Composition[{a,b,c}] to Composition[a,b,c]?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Red Banana
  • 5,329
  • 2
  • 29
  • 47

4 Answers4

17

Apply is designed for this purpose:

Apply[Composition][{a, b, c}][x]
(*  a[b[c[x]]]  *)

Or

Apply[Composition, {a, b, c}][x]
Michael E2
  • 235,386
  • 17
  • 334
  • 747
  • 2
    Shorthand for Apply is @@. E.g. (Composition @@ {a,b,c})[x] or x // Composition @@ {a,b,c}. – Džuris Nov 20 '21 at 11:52
  • 1
    @Džuris Yep, I usually use @@. Except, a personal preference, I dislike parentheses, which led me to avoid @@ in these situations. With command completion, the length of typing is about the same, and no parentheses feels easier to type & read for me. – Michael E2 Nov 20 '21 at 21:24
13
lis = {a, b, c}
Composition[Sequence @@ lis][x]

Mathematica graphics

Nasser
  • 143,286
  • 11
  • 154
  • 359
13

With:

alist = {a, b, c}

A variant using Fold could be:

Fold[Composition, alist][x]

a[b[c[x]]]

Another variant using ComposeList could be:

ComposeList[Reverse@alist, x]

{x, c[x], b[c[x]], a[b[c[x]]]}

from which the last item can be extracted.

Syed
  • 52,495
  • 4
  • 30
  • 85
  • 4
    x // Fold[Composition] /@ {{a, b, c}, {c, b, a}} // Through shows how naturally Fold and Composition can express the solution to OP's problem. Or myFuncList = Fold[Composition] /@ {{a, b, c}, {c, b, a}}; which can be used later, either as individual functions or in Through[myFuncList[x]] – Michael E2 Nov 20 '21 at 15:52
  • 1
    A variation of this solution is Fold[ReverseApplied[Construct], x, Reverse@{a, b, c}]. – J. M.'s missing motivation Dec 09 '21 at 20:36
5

Since no one seems to have answered how to Apply Composition to a List like j given by OP, here it is:

Composition[##][x]&@@#&/@j

{a[b[c[x]]],c[b[a[x]]]}

CA Trevillian
  • 3,342
  • 2
  • 8
  • 26