MoonBit Language Tour MoonBit

Immutable List

The immutable list resides in the package @list.

It is either:

  • Empty : an empty list
  • More : an element and the rest of the list.

You can construct @list.List using @list.empty() and @list.cons(..). You can also use xs.prepend(x) to prepend an element to the front of the list.

fn[A] count(list : @list.List[A]) -> UInt {
  match list {
    Empty => 0
    More(_, tail~) => count(tail) + 1
  }
}

///|
fn main {
  let empty_list = @list.empty()
  let list_1 = @list.cons(1, empty_list)
  let list_2 = list_1.prepend(2)
  let list_3 = empty_list.prepend(3)
  let reversed_1 = list_1.rev()
  let n = count(reversed_1)
}