0

我正在尝试在列表列表中找到一个元素;特别是,如果可以在一个国家/地区找到特定城市。

我有 states:List[State]和 city: List[City],这意味着国家被表示为List[List[City]]

我写了这段代码,但似乎我遇到了一个问题。这是片段:

case class city (
  name: String, 
  CodePostal: Double, 
  visit: Boolean
)


def belongToCountry(p: city): Boolean =
  countries.flatten.foreach {
    case p => return true 
    case _ => return false
  }

def belongToCountry(p: city): Boolean =
  countries.foreach(s => s.city.contains(p))
4

2 回答 2

0

您应该使用contains而不是foreach

def belongToCountry(p: city): Boolean =
  countries.exists(s => s.contains(p))

这个想法是:city属于countriesif 集合的countries contains country集合containsthis city

或者,您可以从国家集合中获取所有城市,然后检查结果是否包含以下内容city

def belongToCountry(p: city): Boolean =
  countries.view.flatten.exists{_ == p}
于 2013-11-09T12:34:44.340 回答
0

带有for表达式的更详细的解决方案是

def belongToCountry(city: city): Boolean = {

  val checkIterator: Iterator[Boolean] = for {
    country <- countries.toIterator
    cityName <- country
    if (city.name == cityName)
  } yield true

  checkIterator.hasNext match {
    case true => checkIterator.next()
    case false => false
  }
}
于 2016-09-02T13:06:27.960 回答