Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala中具有递增内部索引的double for循环_Scala - Fatal编程技术网

scala中具有递增内部索引的double for循环

scala中具有递增内部索引的double for循环,scala,Scala,我试图创建一个简单的函数来查找列表中最近的两对。因为这个操作涉及比较列表中的两个元素,所以我不确定使用for循环是否真的只是sugarformap和flatmap。到目前为止,我的表达式结构如下: val points: List[(Double, Double)] = List((2.0,3.1),(3.5,2.3),(1.2,0.2),(6.4,2.4)) var minDistance = Double.PositiveInfinity var closestPoints = ((Doub

我试图创建一个简单的函数来查找列表中最近的两对。因为这个操作涉及比较列表中的两个元素,所以我不确定使用for循环是否真的只是sugarformap和flatmap。到目前为止,我的表达式结构如下:

val points: List[(Double, Double)] = List((2.0,3.1),(3.5,2.3),(1.2,0.2),(6.4,2.4))
var minDistance = Double.PositiveInfinity
var closestPoints = ((Double.NaN, Double.NaN), (Double.NaN, Double.NaN))

for {
  point1 <- points
  point2 <- points if (point1 != point2) 
  if (distance(point1, point2) < minDistance): {
    minDistance = distance(point1, point2)
    closestPoints = (point1, point2)
  }
} yield (I guess I don't want a yield here?)

这似乎仍然不令人满意,因为产量?我想有一些foldleft实现可以工作,但我也不知道如何在内部循环中迭代越来越小的子集。与简单的双循环相比,我发现foldLeft在推理上比较混乱。

您可以使用
组合和
foldLeft
实现这一点:

points
  .combinations(2)
  .foldLeft((Double.PositiveInfinity,
    ((Double.NaN, Double.NaN), (Double.NaN, Double.NaN)))) { 
    case (acc, List(firstPoint, secondPoint)) =>
      val dist = distance(firstPoint, secondPoint)
      if (dist < acc._1) (dist, (firstPoint, secondPoint)) else acc
  }

同样有效。

如果没有
{}
而不是
()
围绕
foldLeft
的第二个参数,我将无法编译。另外,
{case(acc,List(firstPoint,secondPoint))=>{
是一种稍微清晰的解包参数的方法吗?@Thearchetypaulpaul我遗漏了括号。但是你的建议绝对更清晰,经过编辑。
points
  .combinations(2)
  .foldLeft((Double.PositiveInfinity,
    ((Double.NaN, Double.NaN), (Double.NaN, Double.NaN)))) { 
    case (acc, List(firstPoint, secondPoint)) =>
      val dist = distance(firstPoint, secondPoint)
      if (dist < acc._1) (dist, (firstPoint, secondPoint)) else acc
  }
points
  .combinations(2)
  .minBy { case List(first, second) => distance(first, second) }
for{
    point1, i <- points.view.zipWithIndex
    point2, j <- points.view.zipWithIndex if( i > j)
    #add whatever you want to do next
}
points.combinations(2).minBy{ pair => distance(pair(0), pair(1)) }