A classic implementation of the Huet Zipper for singly-linked lists in MoonBit.
- Immutable, functional list (
MList) - Zipper structure for efficient navigation and modification
- Move focus left/right, update, insert, and delete at focus
- Convert between list and zipper
- Move focus to start or end
pub enum MList[T] {
Nil
Cons(T, MList[T])
}
pub struct Zipper[T] {
left : MList[T] // elements left of focus, reversed
focus : T // current element in focus
right : MList[T] // elements right of focus
}MList::from_array(arr: Array[T]) -> MList[T]MList::reverse(self: MList[T]) -> MList[T]Zipper::from_list(list: MList[T]) -> Zipper[T]?to_list(self: Zipper[T]) -> MList[T]current(self: Zipper[T]) -> Tmove_left(self: Zipper[T]) -> Zipper[T]?move_right(self: Zipper[T]) -> Zipper[T]?update(self: Zipper[T], new_focus: T) -> Zipper[T]insert_left(self: Zipper[T], value: T) -> Zipper[T]insert_right(self: Zipper[T], value: T) -> Zipper[T]delete(self: Zipper[T]) -> Zipper[T]?move_to_start(self: Zipper[T]) -> Zipper[T]move_to_end(self: Zipper[T]) -> Zipper[T]
let list = MList::from_array([1, 2, 3, 4])
let zipper = from_list(list).unwrap().move_right().unwrap() // focus on 2
let at_end = zipper.move_to_end() // focus on 4
let at_start = at_end.move_to_start() // focus on 1
let result = at_start.to_list() // [1, 2, 3, 4]Apache-2.0