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$
3
  • $\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$ Commented Jun 20, 2013 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
    Commented Jun 20, 2013 at 10:15
  • $\begingroup$ It is hardly simpler, but you can use something like Composition[Apply @@ # &, Reverse, List]. $\endgroup$ Commented Jun 20, 2013 at 10:45

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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