It looks like the very young feature of pattern matching (/replacing) within Associations (https://mathematica.stackexchange.com/a/119542/6804), with or without KeyValuePattern, still has quite some flaws.
Let's define
g[KeyValuePattern["x" -> x_?NumericQ]] := x^2; This is ok:
g[<|"x" -> x[1]|>] g[<|"x" -> x[1]|>] /. x[1] -> 0 (*==>*) g[<|"x" -> x[1]|>] 0 But using g with Associations in numerical functions does not work:
FindMinimum[g@<|"x" -> x[1]|>, {{x[1], 0}}] NIntegrate[g@<|"x" -> x[1]|>, {x[1], 0, 1}] (*==>*) FindMinimum::nrnum: The function value g[<|x->x[1]|>] is not a real number at {x[1]} = {0.}. >> NIntegrate::inumr: The integrand g[<|x->x[1]|>] has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >> Using Lists of rules, whether right away or via Normal works:
NIntegrate[g@Normal@<|"x" -> x[1]|>, {x[1], 0, 1}] NIntegrate[g@{"x" -> x[1]}, {x[1], 0, 1}] FindMinimum[g@{"x" -> x[1]}, {{x[1], 0}}] FindMinimum[g@Normal@<|"x" -> x[1]|>, {{x[1], 0}}] (*==>*) 0.333333 {0., {x[1] -> 0.}} Am I missing something obvious or can this be considered a bug?
These things are quite important to have fixed if we want to use Associations for some object-oriented programming...
Edit
Thanks to Alexey Popkov I now know that everything I described here behaves as is to be expected. Since Association has HoldAllComplete, the expression g[<|"x" -> x[1]|>], created when x[1] is undefined, will always stay g[<|"x" -> x[1]|>], even when x[1] is assigned some value later.
I find this a bit confusing, Associations really don't behave like a markup-style Head that you might define yourself:
A plain
person["age" -> x, "height" -> 2]
does in general not behave like
Association["age" -> x, "size" -> 2]
You might even argue that the first variant is more readable for object-oriented programming, because the head gives information about the type of object.
_?NumericQisn't the answer here. The only way (i see) is to put toNIntegratewhat you want to integrate, don't use fancy syntax/evaluation features there. $\endgroup$