Using Fold
to build ApplyFunctionIfKeyContains
:
ApplyFunctionIfKeyContains[expr_List | expr_Association, fun_, keyPattern_] := Module[
{isAssociation, normalExpr, result},
isAssociation = AssociationQ[expr];
normalExpr = If[isAssociation, Normal @ expr, expr];
result = Fold[
Function[
If[StringContainsQ[ToString[Part[#2, 1]], keyPattern],
Append[#, Part[#2, 1] -> fun[Part[#2, 2]]],
Append[#, #2]
]
],
If[isAssociation, <||>, {}],
normalExpr
];
If[isAssociation, Association @ result, result]
];
Testing ApplyFunctionIfKeyContains
:
ApplyFunctionIfKeyContains[{Aa -> 1/2, Av -> 2/5, Bx -> 3/7, Ce -> 4/9}, q, "A" | "a"]
{Aa -> q[1/2], Av -> q[2/5], Bx -> 3/7, Ce -> 4/9}
ApplyFunctionIfKeyContains[<|Aa -> 1/2, Av -> 2/5, Bx -> 3/7, Ce -> 4/9|>, q, "B"]
<|Aa -> 1/2, Av -> 2/5, Bx -> q[3/7], Ce -> 4/9|>
Aa
.., related: 75294 $\endgroup$