【问题标题】:Which Scala function to replace this procedural statement?哪个 Scala 函数可以替换这个程序语句?
【发布时间】:2012-01-19 09:18:06
【问题描述】:

这里是思维障碍,但我不知道如何使它不那么难看:

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,返回一个双精度值。

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

【问题讨论】:

  • 我知道这很容易。在电脑上 12 小时就可以做到这一点。

标签: scala functional-programming procedural


【解决方案1】:

你可以这样做:

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

风格提示,顺便说一句:

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

【讨论】:

  • 我现在肯定会使用合格的导入。我在 Programming in Scala 中读过,但完全忘记了
【解决方案2】:
spheres.minBy(_.intersectRay(ray))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多