Skip to main content

Pattern matching list of elements with different heads


I have a function, which I want to accept only a list of kind of elements belonging to a group. The task comes down to finding an elegant pattern suitable for easy to read function prototype.


As an example I have a pattern, which works:


pattern = {__?(Head[#] === foo || Head[#] === bar &)}

but I am sure, that it can be in a more elegant way.


Here are some cases were I expect the pattern to match the parameter:


MatchQ[{foo[a1], bar[b1, b2], foo[c1], bar[b1, b2]}, pattern]
MatchQ[{foo[a1]}, pattern]


And here I expect to get false:


MatchQ[{foo[a1], bar[b1, b2], cha[c1, c2]}, pattern]
MatchQ[{}, pattern]
MatchQ[{foo}, pattern]
MatchQ[{1}, pattern]
MatchQ[foo, pattern]

Weakly related to "Pattern matching to head with holdfirst".



Answer



You can use the syntax for matching a head _Head, along with the alternative | symbol, and repeated .. to do pattern = {(_foo|_bar)..}. Which should match any list containing only expressions with the heads foo, and bar in any order.



Comments