简单Scala编码问题

简单Scala编码问题,scala,Scala,假设我有类型为list[String]的listcountry和类型为map[String,String]的mapcapitals。现在我想编写一个函数pairs(countries:List[String],capitals:Map[String,String]):Seq[(String,String)],返回成对的序列(country,capital),如果找不到某个国家的首都,则打印一个错误。最好的方法是什么?首先,您的映射[String,String]已经是一个Seq[(String,S

假设我有类型为
list[String]
的list
country
和类型为
map[String,String]
的map
capitals
。现在我想编写一个函数pairs(countries:List[String],capitals:Map[String,String]):Seq[(String,String)],返回成对的序列
(country,capital)
,如果找不到某个国家的首都,则打印一个错误。最好的方法是什么?

首先,您的
映射[String,String]
已经是一个
Seq[(String,String)]
,如果您愿意,可以通过调用
toSeq将其正式化:

pairs(countries:List[String], capitals:Map[String, String]):Seq[(String, String)]
countries.map(x=>(x, capitals(x)))
val xs = Map("UK" -> "London", "France" -> "Paris")
xs.toSeq
// yields a Seq[(String, String)]
所以问题就归结为找到地图上没有的国家。有两种方法可以获得代表这些国家的集合

keys
方法将返回一个
Iterator[String]
,而
keySet
将返回一个
Set[String]
。让我们支持后者:

val countriesWithCapitals = xs.keySet
val allCountries = List("France", "UK", "Italy")
val countriesWithoutCapitals = allCountries.toSet -- countriesWithCapitals
//yields Set("Italy")

以您认为合适的任何方式将其转换为错误。

首先,您的
映射[String,String]
已经是一个
Seq[(String,String)]
,如果您愿意,您可以通过调用
toSeq将其正式化:

val xs = Map("UK" -> "London", "France" -> "Paris")
xs.toSeq
// yields a Seq[(String, String)]
所以问题就归结为找到地图上没有的国家。有两种方法可以获得代表这些国家的集合

keys
方法将返回一个
Iterator[String]
,而
keySet
将返回一个
Set[String]
。让我们支持后者:

val countriesWithCapitals = xs.keySet
val allCountries = List("France", "UK", "Italy")
val countriesWithoutCapitals = allCountries.toSet -- countriesWithCapitals
//yields Set("Italy")

以您认为合适的任何方式将其转换为错误。

您是否假设国家列表是地图键的超集?主要目标可能是列出一小部分国家的首都,而不是在地图上找到失踪的国家。然而,这个问题并不完全清楚。@Ben-我是根据描述来工作的:“如果找不到某个国家的首都,请打印一个错误”您是否假设国家列表是地图键的超集?主要目标可能是列出一小部分国家的首都,而不是在地图上找到失踪的国家。不过,这个问题并不完全清楚。@Ben-我是根据描述工作的:“如果找不到某个国家的首都,请打印一个错误”