Scala - 如何定义映射,其中值取决于键?

标签 scala dictionary

有没有办法定义一个 Map,其中 Map 值取决于它的键,比如

Map(key -> f(key), key2 -> f(key2), ...).

最佳答案

你看错了...

一个 Map[K,V]也是 Partialfunction[K,V] 的一个实例.因此,在您使用 Map 的任何地方进行更改类型(vals、方法参数等)为 PartialFunction .

然后你就可以使用 f直接,或提供 Map[K,V]作为您在键和值之间没有简单代数关系的实例。

例如

def methodUsingMapping(x: PartialFunction[Int,Boolean]) = ...

//then
val myMap = Map(1->true, 2->true, 3->false)
methodUsingMapping(myMap)


//or
val isEven = PartialFunction(n: Int => n % 2 == 0)
methodUsingMapping(isEven)

//or
//note: case statements in a block is the smart way
//      to define a partial function
//      In this version, the result isn't even defined for odd numbers
val isEven: PartialFunction[Int,Boolean] = {
  case n: Int if n % 2 == 0 => true
}
methodUsingMapping(isEven)

您可能还想考虑使用 (K) => Option[V] ,在这种情况下,您可以通过 lift 提供该类型的实例方法,映射继承自 PartialFunction
例如
def methodUsingMapping(x: (Int)=>Option[Boolean]) = ...

//then
val myMap = Map(1->true, 2->true, 3->false)
methodUsingMapping(myMap.lift)

//or
def isEven(n: Int) = Some(n % 2 == 0)
methodUsingMapping(isEven)

//or
def isEven(n: Int) = n % 2 == 0
methodUsingMapping(x => Some(isEven(x)))

关于Scala - 如何定义映射,其中值取决于键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583594/

相关文章:

scala - 如何解析喷雾路由中的获取请求参数?

scala - 从数据湖导出到 Azure SQL Server DB 时遇到问题

dictionary - 如何以 map 作为参数调用Freemarker宏?

python - 创建字典 Python 的字典

python - 在 Flask 中使用 Jinja2 获取嵌套的字典项

scala - 标记方法调用它总是返回非空结果

sql - 将嵌套连接和 groupby 查询转换为 Slick 3.0

python - 将列表设置为具有未知数量的列表元素的字典中的键

sql - 如何选择每组的第一行?

java - Java 中的 Hashmap 与 Map