2
$\begingroup$

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}
$\endgroup$
  • $\begingroup$ 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}]. $\endgroup$ – J. M. will be back soon Jun 20 '13 at 10:04
  • 1
    $\begingroup$ @0x4A4D I think the following would be useful functionality: Composition[f1,f2..., Method->k][__] where k can be Apply, Map, MapIndexed etc. $\endgroup$ – Kuba Jun 20 '13 at 10:15
  • $\begingroup$ It is hardly simpler, but you can use something like Composition[Apply @@ # &, Reverse, List]. $\endgroup$ – Leonid Shifrin Jun 20 '13 at 10:45
6
$\begingroup$

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.)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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