就您命名事物的方式而言,您似乎来自Python背景。
我建议你先学习一点Scala,因为我们非常不同。
不仅在样式方面(例如驼峰式与破折号式),而且在更基本的方面,例如:
- 一个强大的静态类型系统。因此,诸如此类
Any
的事情通常是代码异味,对于 99.99% 的情况,完全没有必要。
- OOP 和 FP 的混合体。因此,您不必成为 FP 专家,但即使在Scala的 OOP 方面,也有一些惯用的东西,例如不变性和常见操作(高阶函数) ,如
map
, flatMap
, filter
& reduce
。
- 我们的List与Python非常不同,通过索引访问元素是
O(n)
(在Python中是O(1)
)。Python列表更像是一个可以调整大小的数组。
- 此外,我们并没有真正的
for
循环。我们有一些需要理解的东西,在某些情况下,它只不过是调用,和 & 的语法糖map
flatMap
filter
foreach
。
清单可以继续,但我认为我的观点很明确。
Scala不仅是新的语法,还是一种不同的编程方式。
无论如何,这是解决您问题的惯用方法。
(没必要这是最好的方法,可以做很多变化)
// First lets create some custom types / classes to represent your data.
final case class Point(x: Double, y: Double)
final case class ClassifiedPoint(point: Point, clazz: String)
// Lets define the Euclidean distance function.
def euclideanDistance(p1: Point, p2: Point): Double =
math.sqrt(
math.pow((p1.x - p2.x), 2) +
math.pow((p1.y - p2.y), 2)
)
}
// This is what you need.
// Note that I made it somewhat more generic that is has to be.
// For example, instead of using the euclidean distance function directly on the body,
// we receive the distance function to use.
// Also, I use a technique called currying to split the arguments in different lists,
// This allows the caller to partially apply them.
def computeDistance(distanceFun: (Point, Point) => Double)
(trainingList: List[ClassifiedPoint])
(referencePoint: Point): List[(ClassifiedPoint, Double)] =
trainingList.map { classifiedPoint =>
val distance = distanceFun(classifiedPoint.point, referencePoint)
classifiedPoint -> distance
}
你可以像这样使用它。
val trainingList = List(
ClassifiedPoint(Point(x = 4.3d, y = 3.0d), clazz = "Iris-setosa"),
ClassifiedPoint(Point(x = 4.4d, y = 3.0d), clazz = "Iris-setosa")
)
// Partial application to create a new function.
val computeEuclideanDistance = computeDistance(euclideanDistance) _
computeEuclideanDistance(trainingList, Point(x = 3.0d, y = 0.0d))
// res: List[(ClassifiedPoint, Double)] =
// List(
// (ClassifiedPoint(Point(4.3, 3.0), "Iris-setosa"), 3.269556544854363),
// (ClassifiedPoint(Point(4.4, 3.0), "Iris-setosa"), 3.3105890714493698)
// )