您可能想要尝试的一件事(取决于应用程序,例如您是否经常更新某个点等...)是使用“拉链”,见下文。您可能想要添加一个“moveTo”方法或类似方法。如果处理不可变列表,您可能会有更少的更新。我认为上面的简单解决方案可能最适合小型列表。
编辑:如果你知道你正在追逐彼此靠近的元素等,可能可以进行调整。
case class Zipper[A](focus: A, left: List[A], right: List[A]) {
def fromZipper: List[A] = left ::: List(focus) ::: right
/** Will throw NoSuchElementException if try to move beyond start. */
/** directions are forward and backward across the list. */
def moveForward: Zipper[A] = Zipper(right.head,left :+ focus,right.tail)
def moveBackward: Zipper[A] = Zipper(left.last,left.init,focus :: right)
/** Update the focus element. */
def update(a: A): Zipper[A] = Zipper(a,left,right)
}
def apply[A](left: List[A], focus: A, right: List[A]): Zipper[A]
= Zipper(focus,left,right)
def apply[A](xs: List[A]): Zipper[A]
= Zipper(xs.head,List.empty[A],xs.tail)