Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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!

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

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.

share|improve this answer
    
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. –  Software Engineer Jan 27 at 3:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.