简体   繁体   中英

Converting Imperative Expressions to Functional style paradigm

I have the following Scala snippet from my code. I am not able to convert it into functional style. I could do it at other places in my code but not able to change the below one to functional. Issue is once the code exhausts all pattern matching options, then only it should send back "NA". Following code is doing that, but it's not in functional style (for-yield)

var matches = new ListBuffer[List[String]]()
      for (line <- caselist){
        var count = 0
        for (pat <- pattern if (!pat.findAllIn(line).isEmpty)){
          count += 1
          matches += pat.findAllIn(line).toList
        }
        if (count == 0){
          matches += List("NA")
        }
       }
      return matches.toList
     }

Your question is not entirely complete, so I can't be sure, but I believe the following will do the job:

  for {
    line <- caselist
    matches = pattern.map(_.findAllIn(line).toList)
  } yield matches.flatten match {
    case Nil => List("NA")
    case ms => ms
  }

This should do the job. Using foreach and filter to generate the matches and checking to make sure there is a match for each line will work.

caseList.foreach{ line =>
  val results = pattern.foreach ( pat => pat.findAllIn(line).toList )
  val filteredResults = results.filter( ! _.isEmpty )
  if ( filteredResults.isEmpty ) List("NA")
  else filteredResults
}

Functional doesn't mean you can't have intermediate named values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM