2

I have a piece of code like this

def filter(t: String) : Boolean = {
    var found = false;
    for(s <- listofStrings) {
      if ( t.contains(s)) { found = true}
    }
    found
  }

The compiler gives a warning that its not good practise to use a mutable variable. How do I avoid this ?

Disclaimer: I used a variant of this code in an assignment and the submission is done. I would like to know what the right thing to do is

2 Answers 2

8

You could do:

def filter(t:String) = listofStrings.exists(t.contains(_))
Sign up to request clarification or add additional context in comments.

6 Comments

This is wrong. As defined, filter is equivalent to contains(), you don't need the exists.
@Matthew Farwell: No. He wants to check if the String t contains any of the strings in the list of strings, not if the String t is contained in the list of strings.
@MatthewFarwell I disagree (or don't understand your objection). The OP's filter(t) method is true iff one of the elements in listofStrings is a substring of t, NOT if t is contained in listofStrings.
Eduardo, you're right, I misread the original algorithm. Sorry.
@Matthew: say the list of strings was "a"::"b""::Nil and t was "a1": this should return true because t contains "a". Doing list.contains(t) would yield false
|
3

If you what to use as few built-in collection functions as possible, use recursion:

def filter(t: String, xs: List[String]): Boolean = xs match {
  case Nil => false
  case x :: ys => t.contains(x) || filter(t, ys)
}

println(filter("Brave New World", List("few", "screw", "ew"))) // true

println(filter("Fahrenheit 451", List("20", "30", "80"))) // false

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.