scala - 在列表中搜索以下以特定方式关联的项目
问题描述
创建以associate(fun, list)
这种方式工作的函数:
例子:
def square(x:Int) = x*x
val list = List(2,4,16,,5,10,100,105)
associate(list,square)
Result: List((2,4),(4,16),(10,100))
解决方案
我建议:
def square(x:Int) = x*x
def associate[A, B](fun: A => B, list: List[A]): List[(A, B)] = {
val distinct: List[A] = list.distinct
distinct.zip(distinct.map(fun).foldLeft(List.empty[Option[B]])((maybeOuts, out) => {
maybeOuts :+ distinct.collectFirst { case `out` => out }
}))
.collect { case (in, Some(out)) => in -> out }
}
println(associate(square, List(2, 4, 16, 5, 10, 100, 105)))
println(associate((_: Double).toInt, List[Double](2, 4, 16, 5, 10, 100, 105)))
println(associate(identity[Int], List(2, 4, 16, 5, 10, 100, 105)))
println(associate[Int, Double](Math.pow(_, 2), List(2, 4, 16, 5, 10, 100, 105)))
哪个打印
列表((2,4),(4,16),(10,100))
列表((2.0,2), (4.0,4), (16.0,16), (5.0,5), (10.0,10), (100.0,100), (105.0,105))
列表((2,2), (4,4), (16,16), (5,5), (10,10), (100,100), (105,105))
列表((2,4.0),(4,16.0),(10,100.0))
希望能帮助到你。
推荐阅读
- html - 我不明白为什么我的高度自动的 div 占用了其父级的全部高度
- reactjs - 在 React 应用程序中导入单个组件
- c - 使用 fgetc() 将文件中的整数值分配给数组
- javascript - 我的代码可以在代码笔中使用,但不能在本地使用
- android - 有没有办法通过 EAP-TTLS 以编程方式连接到 Passpoint/Hotspot2.0 网络?
- python - 使用python扫描文件夹内所有确定的文件
- pip - 如何在 Windows 上为 python 3.3 安装 pip?
- amazon-web-services - 无服务器 - 无法从 S3 读取文件
- java - 如何在 Android 上管理从后台恢复的 Xamarin 表单应用程序?
- hadoop - 在 Web UI 中何处使用 HDFS 数据 - MapR