# KeyValuePattern specificity in DownValues

Bug introduced in 10.4.0 and persisting through 11.3.0

CASE:3824590

[...] Developers are discussing this behavior. [...] I will let you know when I have definite information on this. [...]

Edit: one year later, no followup feedback, issue persists

I was surprised to find out:

ClearAll[f, g];

f[KeyValuePattern[{_}]] := 1;
f[KeyValuePattern[{"test" -> _}]] := 2;

g[k[{_}]] := 1;
g[k[{"test" -> _}]] := 2;


DownValues@f

{
HoldPattern[f[KeyValuePattern[{_}]]] :> 1,
HoldPattern[f[KeyValuePattern[{"test" -> _}]]] :> 2
}

DownValues@g

{
HoldPattern[g[k[{"test" -> _}]]] :> 2,
HoldPattern[g[k[{_}]]] :> 1
}


that KeyValuePattern[{_}] is considered more specific than KeyValuePattern[{"test" -> _}].

Which makes f[<|"test" -> 1|>] evaluate to 1 :(

### The question

Is this expected?

### Workaround notes

No, defining f in reverse order is not an option for me because the functionality is split between many independent packages.

No, manually prepending to DownValues[f] is not an option as I need automatic specificity for additional cases of f.

So the only solution I see is:

f[ass:KeyValuePattern[{}]]:=f[Lookup[ass, "test", "NA"], ass];
f["NA", _]:=1;
f[_, _]:=2;


or something. Not perfect but can live with this.

### Further questions

Is there a better way to make KeyValuePattern to behave more consistently with the rest of the system?

• I think this is worth reporting. InternalComparePatterns[z[{"x" -> 1}], z[{_}]] yields Specific yet if we replace z with KeyValuePattern we get Disjoint`. Surely this is incorrect. – WReach Jan 23 '17 at 15:33
• @WReach Do you agree to add bugs tag? It is still the case in 11.3 -.- – Kuba Apr 20 '18 at 10:50
• I am in two minds about it. On the one hand, it sure feels like a bug to me. On the other hand, pattern specificity is a complex subject and detailed analysis may reveal some underlying reason for this behaviour. On balance, I suppose that adding the bugs tag may bring some welcome attention to the issue. So, I agree. – WReach Apr 20 '18 at 14:27