2

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"]];
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Tom Mozdzen
  • 521
  • 5
  • 16

2 Answers2

5
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.

eyorble
  • 9,383
  • 1
  • 23
  • 37
  • Nice. Thanks. I was just looking at StringMatchQ, but I think MemberQ is a safer choice. – Tom Mozdzen May 04 '18 at 21:05
  • 1
    @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. – eyorble May 04 '18 at 21:09
  • I have a list of 10+ items in my real program. I just mentioned two here to illustrate what was needed. – Tom Mozdzen May 04 '18 at 21:10
  • 1
    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. – eyorble May 04 '18 at 21:11
3

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"}

m_goldberg
  • 107,779
  • 16
  • 103
  • 257