10
$\begingroup$

I have an association

<| a->f, b->g |> 

where f and g are pure functions. Is there a nice way to apply arguments to both f and g? E.g.

<| a->f, b->g |>[x] --> <| a->f[x], b->g[x] |> 
$\endgroup$
0

4 Answers 4

11
$\begingroup$

As Kuba provided in a comment we can Map a Function that applies its argument to a specific expression, e.g. x:

#[x] & /@ <|a -> f, b -> g|> 
<|a -> f[x], b -> g[x]|> 
$\endgroup$
3
  • $\begingroup$ Still, as did OP, I'd expect Through to work (does it?) $\endgroup$ Commented Sep 26, 2017 at 8:16
  • $\begingroup$ @LLlAMnYP you mean like Through[<|a -> f, b -> g|>[x]] ? No, it does not; the body evaluates to Missing["KeyAbsent", x]. Through[Unevaluated[<|a -> f, b -> g|>[x]]] gives Association[(a -> f)[x], (b -> g)[x]] but I don't find that helpful. With[{asc = <|a -> f, b -> g|>}, Through[Unevaluated[asc[x]]]] just kicks back Through[Unevaluated[<|a -> f, b -> g|>[x]]]. $\endgroup$ Commented Sep 26, 2017 at 8:37
  • $\begingroup$ Thanks, I do not mind a non cw answer next time :) $\endgroup$ Commented Sep 26, 2017 at 9:42
6
$\begingroup$

Using Comap (new in 14.0)

Comap[<|a -> f, b -> g|>, x] 

<|a -> f[x], b -> g[x]|>

$\endgroup$
4
$\begingroup$

If your version of WL doesn't have Comap (version version 14), you could also use Query:

Query[<|a -> f, b -> g|>][x] 

<|a -> f[x], b -> g[x]|>

$\endgroup$
3
$\begingroup$

From @Gustavo Delfino's answer and Query[<|a -> f, b -> g|>] // Normal,

GeneralUtilities`ApplyThrough[<|a -> f, b -> g|>][x] (* <|a -> f[x], b -> g[x]|> *) 

(Community wiki)

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.