首页 > 解决方案 > 在列表中搜索以下以特定方式关联的项目

问题描述

创建以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))

标签: scala

解决方案


我建议:

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

希望能帮助到你。


推荐阅读