我正在尝试更熟悉函数式编程,我想知道是否有更优雅的方式将列表分组为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)))有没有更好的方法来写这篇文章?
发布于 2012-09-02 07:30:13
val edges = (vertices, vertices.tail :+ vertices.head).zipped map Line另请参阅以下问题:
发布于 2012-09-02 05:33:51
你可以通过这样做来简化一下:
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))
}我做了三件事:
toList to after map的一部分,这样你就可以映射到一个迭代器上,省去了构造两个contains来简单地用谓词调用forall的麻烦。https://stackoverflow.com/questions/12231505
复制相似问题