4

Mindblock here,但我不知道如何使它不那么难看:

def getClosestSphere(ray: Ray, spheres: List[Sphere]): Sphere = {
    val map = new HashMap[Double, Sphere]
    for (sphere <- spheres) {
      val intersectPoint = sphere.intersectRay(ray)
      map.put(intersectPoint, sphere)
    }    
    map.minBy(_._1)._2  
  }

你能看到我在做什么吗?我有一个球体列表,其中每个球体都有一个方法 intersectRay,返回一个双精度值。

我想采用该函数的最小结果的球体。我知道有一个很好的功能结构可以让我在一行中做到这一点,我只是看不到它:(

4

2 回答 2

14

你可以这样做:

def getClosestSphere(ray: Ray, spheres: List[Sphere]): Sphere = {
  spheres.minBy(_ intersectRay ray)
}

顺便说一句,风格提示:

使用可变集合时,请使用合格的导入。对于java.util.SomeCollection,首先import java.{util => ju},然后使用名称ju.SomeCollection。对于scala.collection.mutable.SomeCollection, 先import collection.mutable用名字再用mutable.SomeCollection

于 2012-01-19T09:39:38.097 回答
5
spheres.minBy(_.intersectRay(ray))
于 2012-01-19T09:37:43.290 回答