# Elegant way to match a list with only certain types of elements

I'm working on learning Mathematica programming for personal edification and am trying to find a more elegant way to do a matching expression which will match only a list containing elements that are three types, in this case a (sub)list (of any type), integer or string. (It is similar to a problem from chapter 4 of Wellin.)

I came up with this answer, using a helper function, but it doesn't seem very elegant. I couldn't figure out a way to do this without a helper function after trying a bunch of syntactical variants.

exp2 = {4, {a, b}, "g"}

integerListStringQ[x_] := IntegerQ[x] || ListQ[x] || StringQ[x]

MatchQ[exp2, {__?integerListStringQ}]
MatchQ[{a, 1, "a"}, {__?integerListStringQ}]
MatchQ[{}, {__?integerListStringQ}]


Expected results: True, False, False. In any event, what I would like is something that looks more like this, perhaps? (Expecting a "True" answer.)

MatchQ[exp2, {__?IntegerQ|ListQ|StringQ}]
MatchQ[exp2, {__?Integer|List|String}]


Anyway, I don't know, but these construction I did above don't work, and the solution I did that does work seems inelegant. I feel that I shouldn't need a helper function for something this basic in a functional language.

Thanks!

You don't need a helper function, since you can directly use the patterns and Repeated inside MatchQ:

MatchQ[exp2, {(_List | _Integer | _String) ..}]
(* True *)


Along the same lines, I would write your integerListStringQ using patterns as well, which is more idiomatic:

integerListStringQ[_List | _Integer | _String] := True
integerListStringQ[_] := False


This also gives True with MatchQ:

MatchQ[exp2, {__?integerListStringQ}]
(* True *)


However, there is no harm in using "helper functions". It has nothing to do with a language being functional or not. In fact, I would actually advocate creating helper functions for anything that isn't trivial. You will find them handy in larger pieces of code when you want to do similar comparisons in multiple places.

• Many thanks! I am indeed trying to learn idiomatic Mathematica, although my vernacular wasn't up to the task of saying that earlier, apparently. :) I appreciate the quick response and will try various permuatations of this. Jan 27, 2014 at 3:33