2012-09-01 86 views
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)) 
} 

我已經做了三件事情:

回答

0

那麼你可以這樣做簡化了一下

  1. 拉到最後/頭線路輸出,使其不部分map
  2. toList移動到map之後,以便映射到迭代器上,從而避免構建兩個列表。
  3. 簡化contains簡單地用謂詞調用forall