2
$\begingroup$

How can I shorten these two If expressions into one

 variable="hello";
 If[variable=="hi", Print["hi there"]];
 If[variable=="hello", Print["hi there"]];

Longhand shortening:

 If[variable=="hello" || variable=="hi", Print["hi there"]];

to something like this:

 If[variable=={"hello","hi"}, Print["hi there"]];
$\endgroup$
  • 4
    $\begingroup$ Use MemberQ[{"hello","hi"}, variable] $\endgroup$ – Coolwater May 4 '18 at 21:02
  • 2
    $\begingroup$ And if you have to test against many different conditions, Which and Switch might be helpful. $\endgroup$ – Henrik Schumacher May 5 '18 at 6:49
5
$\begingroup$
If[MemberQ[{"hi", "hello"}, variable], Print["hi there"]];

Should do the trick. List membership is usually the same as equivalence, and it should always be the same with strings.

Since it was mentioned in the comments, StringMatchQ would work quite well if your strings had more in common with each other. As it stands, it's just a binary pattern:

If[StringMatchQ["hello", "hello" | "hi"], Print["hi there"]];

Which works, but clearly isn't leveraging the full potential of a pattern matching functions. It'd be more applicable if you were matching to a much larger set of fairly similar strings.

$\endgroup$
  • $\begingroup$ Nice. Thanks. I was just looking at StringMatchQ, but I think MemberQ is a safer choice. $\endgroup$ – Tom Mozdzen May 4 '18 at 21:05
  • $\begingroup$ @TomMozden It's perfectly applicable here, but it seems like a waste to me for this problem. If you were comparing a much larger set of very similar strings, I think it'd be much more useful. $\endgroup$ – eyorble May 4 '18 at 21:09
  • $\begingroup$ I have a list of 10+ items in my real program. I just mentioned two here to illustrate what was needed. $\endgroup$ – Tom Mozdzen May 4 '18 at 21:10
  • 1
    $\begingroup$ If they have sufficient similarity to be amenable to pattern matching, go for it. I'd think it's more applicable when you have enough items that you start resorting to combinatorics to count them though. $\endgroup$ – eyorble May 4 '18 at 21:11
3
$\begingroup$

You can also do it with MathchQ and Alternative ( ] ).

If[MatchQ[#, "hello" | "hi"], "hi there", "no match"] & /@ {"hello", "hi", "g'day"}

{"hi there", "hi there", "no match"}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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