MatchQ-ing Associations (MMA 10)
Association
is atomic:
<|x -> 1|> // AtomQ
True
Therefore standard pattern matching inside the structure will not work.
You can still match on the implicit head using:
MatchQ[<|x -> 1|>, _Association]
True
There is also AssociationQ
:
<|x -> 1|> // AssociationQ
True
MatchQ[<|x -> 1|>, _?AssociationQ]
True
I used the term atomic in a general way meaning an object that does not conform to the standard expression syntax and traversal rules. Taliesin Beynon explains why this is conflating two different concepts in this chat transcript.
In Mathematica 10.4, Association
can now be used in pattern matching. Here is the result of the OP's example:
MatchQ[<|x -> 1|>, Association[___Rule]]
True
and
MatchQ[<|x->1|>, Association[___]]
True
There's now also KeyValuePattern
which is a pattern object specifically to match elements of an Association
or list of rules. Here are some examples:
<|a -> 1, b -> 2, c -> 3|> /. KeyValuePattern[x_ -> 1] :> x
a
Cases[{
<|"PartOfSpeech" -> "Noun", "Number" -> "Singular"|>,
<|"PartOfSpeech" -> "Verb"|>},
KeyValuePattern[{x : "PartOfSpeech" -> y : "Noun"}] :>
Association[x -> y]]
{<|"PartOfSpeech" -> "Noun"|>}