1
\$\begingroup\$

I am new to Scala and I have written a function which uses pattern matching to filter words based on some conditions. It seems to work correctly but I am suspect that I haven't used the Scala pattern matching in the best way. I think this because each of my cases contain an if statement. I have not seen any examples where people use if statements in pattern matching functions so I'm thinking there might be a better way of doing this. Or maybe this particular usage does not fit well with pattern matching.

def getImportance(token:String,stopWords:Set[String])={
    token match{
      case t if t.length()==1 => 0
      case t if t.length()>15 => 0
      case t if t.matches("\\p{Punct}+") => 0
      case t if stopWords.contains(t.toLowerCase()) => 0
      case _ => 1
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Zero-length words get assigned an Importance of 1. I'm not sure that is correct. \$\endgroup\$ Commented May 28, 2014 at 21:05
  • \$\begingroup\$ 'token' is actually the output from a tokenizer which would not output zero-length words, so that case would never occur. \$\endgroup\$ Commented May 29, 2014 at 14:31
  • \$\begingroup\$ Hmmm. I've heard that before. \$\endgroup\$ Commented May 29, 2014 at 19:23

1 Answer 1

5
\$\begingroup\$

I don't think that using pattern matching is necessary in this case, you only have a few simple conditions that can be better represented with a simple if. See what you think about this solution:

def getImportance(token: String, stopWords: Set[String]) =
  if (token.length() == 1 || token.length() > 15 ||
    token.matches("\\p{Punct}+") ||
    stopWords.contains(token.toLowerCase()))
      0
  else
      1

I believe it is simpler and easier to read. I think using patter matching for these simple cases only hinders the understanding of the code ;)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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