创建以这种方式工作的函数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))
答案 0 :(得分:0)
我建议:
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))
希望有帮助。