# Composition with Apply

Composition is sometimes useful for clarity of a code. For the same purpose I try to Apply(@@) functions as often as it is possible.

My question is how to combine Composition with Apply, or, to be more precise, is there any simpler way than one I'm going to show (there is no Composition :)):

Fold[#2@@#1&, arg, {f1, f2,...}]


alternatively:

Fold[Apply[#2,#1]&, arg, {f1, f2,...}]


So for example:

Fold[#2 @@ #1 &, {1, 2}, {{##} &, {#2, #1} &, {#1, 0, #2} &}]

{2, 0, 1}

-
Not as compact as your version using Fold[], so I'm not posting this as an answer: (Composition @@ Function[f, Apply[f, #] &] /@ {{#1, 0, #2} &, {#2, #1} &, {##1} &})[{1, 2}]. – J. M. Jun 20 '13 at 10:04
@0x4A4D I think the following would be useful functionality: Composition[f1,f2..., Method->k][__] where k can be Apply, Map, MapIndexed etc. – Kuba Jun 20 '13 at 10:15
It is hardly simpler, but you can use something like Composition[Apply @@ # &, Reverse, List]. – Leonid Shifrin Jun 20 '13 at 10:45

I don't think there can be something syntactically simpler than Fold[#2@@#1, ..., but if you often find yourself doing something more complicated with the Heads of expressions (in this case, replacing them), you might want to look at Operate, which hasn't showed up much on this site.

You can adapt it to your specific example with Fold as follows:

Fold[Function[{arg, f}, Operate[f &, arg]], {1, 2}, {{##} &, {#2, #1} &, {#1, 0, #2} &}]
(* {2, 0, 1} *)


What we're doing here is to "operate" on the head of the input expression by discarding it and replacing it with the next element fed to Fold. (Note the use of nested pure functions.)

-
this is educational, thanks. – Kuba Jun 20 '13 at 13:15
I don't think there can be something syntactically simpler than Fold[#2@@#1, ..., :)) +1 – Stefan Jun 20 '13 at 15:56
hmm, a bit of the core language (i.e. v1, core!) I've never seen. Weird. +1 – rcollyer Jul 8 '13 at 19:03