Scala 在列表中搜索以下项以特定方式关联的项

Scala 在列表中搜索以下项以特定方式关联的项,scala,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])

创建功能
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)、(10100))

列表((2.0,2)、(4.0,4)、(16.0,16)、(5.0,5)、(10.0,10)、(100.0100)、(105.0105))

列表((2,2)、(4,4)、(16,16)、(5,5)、(10,10)、(100100)、(105105))

列表((2,4.0)、(4,16.0)、(10100.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)、(10100))

列表((2.0,2)、(4.0,4)、(16.0,16)、(5.0,5)、(10.0,10)、(100.0100)、(105.0105))

列表((2,2)、(4,4)、(16,16)、(5,5)、(10,10)、(100100)、(105105))

列表((2,4.0)、(4,16.0)、(10100.0))


希望有帮助。

@LuisMiguelMejíaSuárez不。他们不需要
地图
,他们需要
滑动
收集
。但在此之前,他们需要阅读,特别是关于“首先自己真诚地尝试解决问题”的部分。@LuisMiguelMejíaSuárez不。他们不需要
map
,他们需要
slide
collect
。但在此之前,他们需要阅读,特别是关于“首先自己真诚地尝试解决问题”的部分。