一件事(根據不同的應用,例如你更新點往往等)是使用「拉鍊」,見下文。您可能需要添加「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)
這裏的關鍵位,正如你提到的,是該名單是不可改變的,所以你不能交換項目。 – Sean