8

is there any way to use the Apply[] function to a sum of objects? By this I mean the following. We know that using Apply[] (@@) to an objects gives:

f@@{a}
f[a]

I'm wondering if there's a way of doing something like

(f+g)@@{a}
f[a]+g[a]

Does anyone knows anything about it? Thanks!

bmf
  • 15,157
  • 2
  • 26
  • 63
Einj
  • 167
  • 4

2 Answers2

5

As of version 14.0, ComapApply is introduced:

ComapApply[f + g, {a}]
(* f[a] + g[a] *)

ComapApply[f + g]@{a} (* f[a] + g[a] *)

enter image description here

BTW, if the object isn't a List {}, you can directly use Comap (also new in v14):

Comap[f + g, a]
(* f[a] + g[a] *)

Comap[f + g]@a (* f[a] + g[a] *)

xzczd
  • 65,995
  • 9
  • 163
  • 468
4

This is another way and an active effort to advertise the ThroughOperator that was developed by @Sjoerd Smit. This is rather new and I find it convenient.

To the extend of my knowledge it was first suggested in this answer.

fnctns = {f, g};
oprtr = ResourceFunction["ThroughOperator"][fnctns, Plus];

and then

oprtr /@ {a} /. List -> (# &)

res

bmf
  • 15,157
  • 2
  • 26
  • 63
  • Does this accomplish anything that Though[(f+g)[a]] doesn't? Why should we rely on an external solution when an internal one exists? – Najib Idrissi Jan 17 '23 at 08:22
  • @NajibIdrissi did you visit any of the links I provided? I am asking out of curiosity – bmf Jan 17 '23 at 08:25
  • Yes, I visited the links. – Najib Idrissi Jan 17 '23 at 08:36
  • 1
    @NajibIdrissi in the second link there's this explanation in a comment Through[{f1, f2, f3}[5]] is annoying to map over lists, which is one of the main motivations I made ThroughOperator. Another reason is that Through[h[f1, f2][x]] sometimes suffers from order-of-evaluation issues that are difficult to circumvent which for me at least was enough to give it a go. Also, I just suggested this an alternative. I realize what the easiest way is. – bmf Jan 17 '23 at 08:39
  • @NajibIdrissi Finally, there's a wealth of very helpful undocumented commands in Mathematica. And finally, I believe that just because there's a simple way of doing things does not mean we should disregard other options. I find it pedagogical. – bmf Jan 17 '23 at 08:39
  • 3
    Glad to see my function is being used :) – Sjoerd Smit Jan 17 '23 at 12:57
  • @SjoerdSmit I am still in the process of learning how to use it properly, so the above answer was a good small exercise. Congrats. It's very nice! – bmf Jan 17 '23 at 13:02