1
我想更熟悉函數式編程,我想知道是否有更優雅的方式將列表分組爲2對,並將函數應用於這些對。替代List.sliding?
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)))
有沒有更好的方式來寫這個?
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))
}
我已經做了三件事情: