【问题标题】:Finding an element in list of list, in Scala在 Scala 中查找列表列表中的元素
【发布时间】:2013-11-21 10:57:47
【问题描述】:

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

我有州:List[State] 和城市:List[City],这意味着国家/地区表示为List[List[City]]

我写了这段代码,但似乎我遇到了问题。这是sn-p:

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))

【问题讨论】:

  • 应该是country 而不是countries
  • 我认为函数的签名应该是def belongToCountry(country: List[List[City]], p: City): Boolean

标签: algorithm scala functional-programming


【解决方案1】:

您应该使用contains 而不是foreach

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

这个想法是:city 属于countries 的集合如果countries contains country 的集合contains 这个city

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

def belongToCountry(p: city): Boolean =
  countries.view.flatten.exists{_ == p}

【讨论】:

    【解决方案2】:

    使用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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-27
      • 2013-07-26
      • 2011-04-08
      • 2016-07-18
      • 2018-12-11
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2019-03-25
      相关资源
      最近更新 更多