Grav v1.14.0

List

import "std/collections" (included in import "std") · namespace std.collections

List<T> is an ordered list with collection-style method names (add, insert, removeAt, filter returning a List). It is built on Array<T> and behaves the same way; use whichever reads better in your code.

grav
import "std"

fn main() {
    let todo = new List<string>()
    todo.add("write")
    todo.add("test")
    todo.insert(0, "plan")
    print(todo)
    print("${todo[1]} ${todo.first()} ${todo.size()}")
    todo.remove("test")
    print(todo.contains("test"))
    let long = todo.filter(fn(t) => t.length > 4)
    print(long)
}
Output
["plan", "write", "test"]
write plan 3
false
["write"]

API

class List<T>

Constructors

  • new List()

Methods

  • fn add(item: T) — Appends an element at the end.
  • fn addAll(other: List<T>) — Appends every element of another list.
  • fn insert(index: int, item: T) — Inserts an element before index.
  • fn get(index: int) -> T — The element at index (IndexError when out of range).
  • fn set(index: int, item: T) — Replaces the element at index.
  • fn operator[](index: int) -> T — list[i]: the element at index i.
  • fn operator[]=(index: int, item: T) — list[i] = v: replaces the element at index i.
  • fn first() -> T — The first element (IndexError when empty).
  • fn last() -> T — The last element (IndexError when empty).
  • fn removeAt(index: int) -> T — Removes and returns the element at index.
  • fn remove(item: T) -> bool — Removes the first element equal to item; whether one was found.
  • fn removeWhere(pred: fn(T) -> bool) -> int — Removes every element pred holds for; how many were removed.
  • fn indexOf(item: T) -> int — The index of the first element equal to item, or -1.
  • fn contains(item: T) -> bool — Whether some element equals item.
  • fn size() -> int — The number of elements.
  • fn length() -> int — The number of elements (same as size()).
  • fn isEmpty() -> bool — Whether the list has no elements.
  • fn clear() — Removes every element.
  • fn reverse() — Reverses the order of the elements in place.
  • fn forEach(f: fn(T)) — Calls f on each element, in order.
  • fn filter(keep: fn(T) -> bool) -> List<T> — A new list of the elements keep returns true for.
  • fn any(pred: fn(T) -> bool) -> bool — Whether pred holds for at least one element.
  • fn all(pred: fn(T) -> bool) -> bool — Whether pred holds for every element (true when empty).
  • fn countWhere(pred: fn(T) -> bool) -> int — How many elements pred holds for.
  • fn sortBy(cmp: fn(T, T) -> int) — Sorts in place (stable): cmp(a, b) < 0 puts a first.
  • fn toString() -> string — As text: [1, 2, 3] (strings in quotes).
  • fn toArray() -> Array<T> — The elements as a new Array.

Edit this page on GitHub