4
$\begingroup$

In one dimension, pure functions work as usual:

f = Function[{x}, 2 x]
f[a]

However, with a list of pure functions / a vector pure function this does not work with the same syntax:

g = {Function[{x}, 2 x], Function[{x}, 3 x]}
g[a]

does not give {2a,3a}, but {Function[{x}, 2 x], Function[{x}, 3 x]}[a] instead. So far, I worked aroud this by using h[y_] = {g[[1]][y], g[[2]][y]}, but that seems a bit awkward.

$\endgroup$
3
  • 2
    $\begingroup$ Through, Comap $\endgroup$
    – xzczd
    Feb 22 at 7:08
  • $\begingroup$ This is the elegant alternative for my h[y_]=..., but is there a also a way to resolve this at the defintion of g? $\endgroup$
    – faber
    Feb 22 at 7:16
  • 3
    $\begingroup$ Of course, the last syntax of Comap: g = Comap@{Function[{x}, 2 x], Function[{x}, 3 x]} Through can be used, too: g = Through[{Function[{x}, 2 x], Function[{x}, 3 x]}@#] &; $\endgroup$
    – xzczd
    Feb 22 at 7:17

2 Answers 2

3
$\begingroup$
g = {Function[{x}, 2 x], Function[{x}, 3 x]}

Using Query

Query[g] @ a

{2 a, 3 a}

Query[g] @ {2, 3}

{{4, 6}, {6, 9}}

As already commented by xzczd you can also use Comap (introduced with Version 14.0)

Comap[g] @ a

{2 a, 3 a}

$\endgroup$
3
$\begingroup$
g = {Function[{x}, 2  x], Function[{x}, 3  x]};

Using Thread:

#1@#2 & @@@ Thread[{g, a}]

(*{2 a, 3 a}*)
$\endgroup$

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