我正在尝试更熟悉函数式编程,我想知道是否有更优雅的方法将列表分组为2对并将函数应用于这些对。
case class Line(start: Vector, end: Vector) {
def isLeftOf(v: Vector) = (end - start).cross(v - start) < 0
}
case class Polygon(vertices: List[Vector]) {
def edges = (vertices.sliding(2).toList :+ List(vertices.last,vertices.head)).map(l => Line(l(0), l(1)))
def contains(v: Vector) = {
edges.map(_.isLeftOf(v)).forall(_ == true)
}
}
我在谈论这一行
def edges = (vertices.sliding(2).toList :+ List(vertices.last,vertices.head)).map(l => Line(l(0), l(1)))
有没有更好的方法来写这个?
答案 0 :(得分:2)
val edges = (vertices, vertices.tail :+ vertices.head).zipped map Line
另见这些问题:
答案 1 :(得分:0)
这样做可以简化:
case class Polygon(vertices: List[Vector]) {
def edges = Line(vertices.last, vertices.head) :: vertices.sliding(2).map(l => Line(l(0), l(1))).toList
def contains(v: Vector) = edges.forall(_.isLeftOf(v))
}
我做了三件事:
map
toList
移至map
之后,以便映射到迭代器,从而避免构建两个列表。contains
,只需使用谓词调用forall
。