List

scalus.cardano.onchain.plutus.prelude.List
See theList companion enum
object List

Attributes

Companion
enum
Graph
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
List.type

Members list

Type members

Inherited and Abstract types

type MirroredElemLabels <: Tuple

The names of the product elements

The names of the product elements

Attributes

Inherited from:
Mirror
type MirroredLabel <: String

The name of the type

The name of the type

Attributes

Inherited from:
Mirror

Value members

Concrete methods

def apply[A](args: A*): List[A]

Creates a list from a variable number of arguments.

Creates a list from a variable number of arguments.

This method allows creating a list by simply providing the elements. Works only offchain.

Type parameters

A

The type of elements in the list.

Value parameters

args

The elements to include in the list.

Attributes

Returns

A list containing all provided arguments.

Example
 List("a", "b", "c") === Cons("a", Cons("b", Cons("c", Nil)))
 List() === Nil
inline def empty[A]: List[A]

Returns an empty list.

Returns an empty list.

This is an inline function that creates a new empty list of the specified type.

Type parameters

A

The type of elements this empty list would contain.

Attributes

Returns

An empty list of type List[A].

def fill[A](value: A, times: BigInt): List[A]

Creates a list by repeating a value a specified number of times.

Creates a list by repeating a value a specified number of times.

If times is less than or equal to 0, an empty list is returned.

Type parameters

A

The type of the value to repeat.

Value parameters

times

The number of times to repeat the value.

value

The value to repeat in the list.

Attributes

Returns

A list containing the specified value repeated times times.

Example
 List.fill("a", 3) === Cons("a", Cons("a", Cons("a", Nil)))
 List.fill(true, 0) === Nil
 List.fill("x", -1) === Nil
def from[A](i: IterableOnce[A]): List[A]

Creates a list from any Scala iterable collection.

Creates a list from any Scala iterable collection.

Works only offchain.

Type parameters

A

The type of elements in the list.

Value parameters

i

The iterable collection to convert to a list.

Attributes

Returns

A list containing all elements from the provided iterable.

Example
 List.from(Vector(BigInt(1), BigInt(2), BigInt(3))) === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 List.from(Iterator.empty) === Nil
def from[A](i: Iterable[A]): List[A]

Creates a list from a Java iterable collection.

Creates a list from a Java iterable collection.

Works only offchain.

Type parameters

A

The type of elements in the list.

Value parameters

i

The Java iterable collection to convert to a list.

Attributes

Returns

A list containing all elements from the provided Java iterable.

Example
 import java.util.Arrays
 val javaList = Arrays.asList("a", "b", "c")
 List.from(javaList) === Cons("a", Cons("b", Cons("c", Nil)))
 val emptyJavaList = new java.util.ArrayList[String]()
 List.from(emptyJavaList) === Nil
def map2[A, B, C](a: List[A], b: List[B])(f: (A, B) => C): List[C]

Combines two lists element-wise using the provided function.

Combines two lists element-wise using the provided function.

The resulting list will have the length of the shorter of the two input lists.

Type parameters

A

The element type of the first list.

B

The element type of the second list.

C

The element type of the resulting list.

Value parameters

a

The first list.

b

The second list.

f

A function that takes one element from each list and produces a result.

Attributes

Returns

A list containing the results of applying function f to corresponding elements of lists a and b.

Example
 val list1 = Cons(BigInt(1), Cons(BigInt(2), Nil))
 val list2 = Cons(BigInt(3), Cons(BigInt(4), Nil))
 List.map2(list1, list2)(_ + _) === Cons(BigInt(4), Cons(BigInt(6), Nil))
 List.map2(List.empty[BigInt], list1)(_ + _) === Nil
def range(from: BigInt, to: BigInt): List[BigInt]

Creates a list containing a range of BigInt values, inclusive of both endpoints.

Creates a list containing a range of BigInt values, inclusive of both endpoints.

This method creates a list containing all integers from from up to and including to. If from is greater than to, an empty list is returned.

Value parameters

from

The starting value of the range (inclusive).

to

The ending value of the range (inclusive).

Attributes

Returns

A list containing all BigInt values from from to to, inclusive.

Example
 List.range(1, 3) === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 List.range(5, 3) === Nil
 List.range(0, 0) === Cons(BigInt(0), Nil)
def rangeUntil(from: BigInt, to: BigInt): List[BigInt]

Creates a list containing a range of BigInt values, inclusive of the start but exclusive of the end.

Creates a list containing a range of BigInt values, inclusive of the start but exclusive of the end.

This method creates a list containing all integers from from up to but not including to. If from is greater than or equal to to, an empty list is returned.

Value parameters

from

The starting value of the range (inclusive).

to

The ending value of the range (exclusive).

Attributes

Returns

A list containing all BigInt values from from to to-1, inclusive.

Example
 List.rangeUntil(1, 4) === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 List.rangeUntil(5, 5) === Nil
 List.rangeUntil(5, 3) === Nil
inline def singleton[A](a: A): List[A]

Creates a list with a single element.

Creates a list with a single element.

Attributes

Example
 List.singleton(BigInt(1)) === Cons(BigInt(1), Nil)
def unboxedNil[A]: List[A]

Creates an empty list that opts A into its native UPLC element representation.

Creates an empty list that opts A into its native UPLC element representation.

For primitive/pair elements (BigInt, ByteString, BuiltinPair, …) this avoids iData/unIData wrapping: the list is a list/list/… constant rather than a list. For case-class elements annotated @UplcRepr(UplcConstr) — which aren't representable as UPLC constants — it falls back to a Constr-encoded list.

Requires A to be a concrete type — fails at lowering time if A is a TypeVar, because the element representation can't be determined for unknown types.

Type parameters

A

Must be a concrete type (BigInt, ByteString, a case class, etc.)

Attributes

Returns

An empty list with the native element representation for A.

Deprecated methods

inline def single[A](a: A): List[A]

Creates a list with a single element. Alias for singleton.

Creates a list with a single element. Alias for singleton.

Attributes

Deprecated
[Since version 1.1.1] use singleton

Concrete fields

lazy val sirDeps: List[SIRModuleWithDeps]
lazy val sirModule: Module

Givens

Givens

given listEq[A : Eq]: Eq[List[A]]

Provides an Eq instance for List[A] where value type is instances of Eq.

Provides an Eq instance for List[A] where value type is instances of Eq.

Attributes

Provides a FromData instance for List[A] where value type is instances of FromData.

Provides a FromData instance for List[A] where value type is instances of FromData.

Attributes

given listOrd[A : Ord]: Ord[List[A]]

Provides an Ord instance for List[A] where value type is instances of Ord.

Provides an Ord instance for List[A] where value type is instances of Ord.

Attributes

given listPairToData[A : ToData, B : ToData]: ToData[List[BuiltinPair[A, B]]]
given listToData[A : ToData]: ToData[List[A]]

Provides a ToData instance for List[A] where value type is instances of ToData.

Provides a ToData instance for List[A] where value type is instances of ToData.

Attributes

given showList[T : Show]: Show[List[T]]

Extensions

Extensions

extension [A](elem: A)
inline def +:[B >: A](list: List[B]): List[B]

Alias on prepended

Alias on prepended

Attributes

extension [A](self: List[A])

Sorts by insertion. Cheaper than sort for very short lists, O(n^2) for everything else.

Sorts by insertion. Cheaper than sort for very short lists, O(n^2) for everything else.

'''Use this only when the length is bounded by construction and at most 8.''' Bounded by construction means a fixed-size window — say the last 11 block timestamps — not "usually short". If an adversary chooses the length, they choose your execution cost, and this is the sort that lets them: at n=64 it costs 5.3x what sort does.

Measured worst-case fee against sort, in lovelace:

n:            0     1     2     4     6      8      9     16      64
insertionSort 229   444  1032  3329  7120  12405  15608  48485  766945
sort          464   909  2255  5137  8047  12575  13429  25322  143847
             \_ up to 2.1x cheaper _/  tie ^      \_ rapidly worse _/

It is also markedly smaller: 106 bytes against 290 for sort, and script size is paid on every transaction carrying the script. For a contract sorting three elements that is a saving on both axes.

Stable, like sort: an element is inserted after any it compares equal to.

Attributes

Example
 List(BigInt(3), BigInt(1), BigInt(2)).insertionSort === List(BigInt(1), BigInt(2), BigInt(3))
def isSorted: Boolean

True when every element is less than or equal to its successor.

True when every element is less than or equal to its successor.

One pass and n - 1 comparisons, with no allocation — far cheaper than sorting. If the caller can supply the list already ordered (from a redeemer, say) then verifying that claim is usually the right move: at n=64 this costs about a seventh of what sort does, and about a fortieth of the quicksort it replaced.

This is what the ecosystem does instead of sorting. Plutarch ships no sort at all, only its equivalent pcheckSorted; of eight production Cardano codebases surveyed, six verify an off-chain-supplied order and exactly one sorts on-chain.

There is deliberately no isSortedOrFail: require(xs.isSorted, "not sorted") says the same thing at the same cost.

Attributes

Example
 List(BigInt(1), BigInt(2), BigInt(2)).isSorted === true
 List(BigInt(2), BigInt(1)).isSorted === false
 List.empty[BigInt].isSorted === true
def isStrictlyAscending: Boolean

True when every element is '''strictly''' less than its successor, i.e. the list is sorted and free of duplicates.

True when every element is '''strictly''' less than its successor, i.e. the list is sorted and free of duplicates.

The strict form is usually the one you want for keys and indices, where a duplicate is a defect rather than a tie: it is the cheap way to reject a redeemer that repeats an index to process the same input twice.

Attributes

Example
 List(BigInt(1), BigInt(2)).isStrictlyAscending === true
 List(BigInt(1), BigInt(1)).isStrictlyAscending === false
inline def quicksort: List[A]

Alias for sort. Retained for backward compatibility — new code should prefer sort.

Alias for sort. Retained for backward compatibility — new code should prefer sort.

The name no longer describes the implementation: sort has been a merge sort since the head-pivot quicksort was removed for being quadratic on ledger-shaped input.

Attributes

def sort: List[A]

Sorts the list in ascending order using the provided Ord[A] instance.

Sorts the list in ascending order using the provided Ord[A] instance.

Stable natural merge sort, close to PlutusTx.List.sortBy and GHC's Data.List.sortBy. runs splits the input into maximal ASCENDING runs and mergeAll merges them in a binary tree of pairwise merges. Theta(n log n) on every input and O(n) when the list is already sorted.

Unlike GHC's version this does NOT detect descending runs, so an exactly-reversed list costs Theta(n log n) rather than O(n) — it simply becomes n singleton runs, which is ordinary bottom-up merge sort. Detecting them was tried and reverted: it needs a mutual recursion between local defs that the lowering cannot express, cost 384 extra bytes of script, and measured no better from n=16 up.

This replaced a head-pivot quicksort, which was Theta(n^2) on already-sorted, reverse-sorted and all-equal input. On Cardano those are ordinary inputs rather than corner cases: the ledger guarantees tx.inputs arrives ordered by TxOutRef, and SortedMap contents are key-ordered. A validator must be provisioned for the worst input an adversary can supply, so a sort whose worst case coincides with its most common input is a budget hazard. Measurements: docs/internal/SORT_ALGORITHM_FINDINGS.md.

'''This is not cheaper at every size.''' Merge sort has a larger body than the quicksort it replaced, and that is fixed overhead a script pays even when the list is tiny. Measured worst-case fee against the old head-pivot quicksort, in lovelace:

n:          0     1     2     4     5      8      16      32       64
old:      277   816  1780  4988  7232  16519   60041  228924   894051
new:      464   909  2248  5096  6490  12471   24865   65812   141105
         \_ worse below n=5 _/       \_ 1.3x at n=8, 6.3x at n=64 _/

So sorting four or fewer elements now costs up to ~1.3x more, and the compiled body grew from 169 to 277 bytes. That is the price of removing a quadratic worst case that an adversary could trigger with ordinary ledger-shaped input. If a call site provably sorts a tiny fixed-size list of values nobody else controls, the old shape was cheaper.

Note that sorting is often avoidable. If the caller can supply the list already ordered, checking that order costs one pass instead of n log n — see isSorted and isStrictlyAscending.

Attributes

Returns

A new list containing the elements of the original list sorted in ascending order.

Example
 List(BigInt(3), BigInt(1), BigInt(2)).sort === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 List.empty[BigInt].sort === Nil
extension [A](self: List[List[A]])
def flatten: List[A]

Flattens a list of lists into a single list.

Flattens a list of lists into a single list.

This method concatenates all inner lists into a single list.

Attributes

Returns

A new list containing all elements from the inner lists.

Example
 val list = Cons(Cons(BigInt(1), Cons(BigInt(2), Nil)), Cons(Cons(BigInt(3), Cons(BigInt(4), Nil)), Nil))
 list.flatten === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Cons(BigInt(4), Nil))))
 List.empty[List[BigInt]].flatten === Nil
extension [A](self: List[A])
inline def !!(idx: BigInt): A

Alias for at

Alias for at

Attributes

inline def ++[B >: A](other: List[B]): List[B]

Alias for appendedAll.

Alias for appendedAll.

Attributes

inline def :+[B >: A](elem: B): List[B]

Alias for appended.

Alias for appended.

Attributes

inline def :++[B >: A](other: List[B]): List[B]

Alias for appendedAll.

Alias for appendedAll.

Attributes

def appended[B >: A](elem: B): List[B]

Appends an element to the end of the list.

Appends an element to the end of the list.

Type parameters

B

The type of the element, which must be a supertype of A.

Value parameters

elem

The element to append.

Attributes

Returns

A new list with the element appended.

Example
 List.empty[BigInt].appended(BigInt(1)) === Cons(BigInt(1), Nil)
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Nil))
 list.appended(BigInt(3)) === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
def appendedAll[B >: A](other: List[B]): List[B]

Appends all elements of another list to this list.

Appends all elements of another list to this list.

Type parameters

B

The type of the elements in the other list, which must be a supertype of A.

Value parameters

other

The list whose elements will be appended.

Attributes

Returns

A new list with all elements of other appended to this list.

Example
 List.empty[BigInt].appendedAll(List(BigInt(1), BigInt(2))) === Cons(BigInt(1), Cons(BigInt(2), Nil))
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Nil))
 list.appendedAll(List(BigInt(3), BigInt(4))) === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Cons(BigInt(4), Nil))))
def asScala: Seq[A]

Converts the list to a Scala sequence (scala.Seq).

Converts the list to a Scala sequence (scala.Seq).

This method is only available offchain.

Attributes

Returns

A scala.Seq[A] containing all the elements from this list in the same order.

Example
 List.empty[BigInt].asScala === scala.Seq.empty[BigInt]
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.asScala === scala.Seq(BigInt(1), BigInt(2), BigInt(3))
def at(index: BigInt): A

Retrieves the element at the specified index in the list.

Retrieves the element at the specified index in the list.

Value parameters

index

The zero-based BigInt index of the element to retrieve.

Attributes

Returns

The element at the specified index.

Throws
NoSuchElementException

if the index is out of bounds.

Example
 List.empty[BigInt].at(BigInt(0)) // throws NoSuchElementException
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.at(BigInt(1)) === BigInt(2)
 list.at(BigInt(3)) // throws NoSuchElementException
 list.at(BigInt(-1)) // throws NoSuchElementException
inline def concat[B >: A](other: List[B]): List[B]

Alias for appendedAll.

Alias for appendedAll.

Attributes

def contains[B >: A](elem: B)(using eq: Eq[B]): Boolean

Checks if the list contains the specified element.

Checks if the list contains the specified element.

Type parameters

B

The type of the element, which must be a supertype of A.

Value parameters

elem

The element to check for in the list.

Attributes

Returns

true if the list contains the element, false otherwise.

Example
 List.empty[BigInt].contains(BigInt(2)) === false
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.contains(BigInt(2)) === true
 list.contains(BigInt(4)) === false
 list.contains(BigInt(-1)) === false
def count(p: A => Boolean): BigInt

Counts the number of elements in the list that satisfy the given predicate.

Counts the number of elements in the list that satisfy the given predicate.

Value parameters

p

A function that takes an element of type A and returns true if the element matches the condition.

Attributes

Returns

The number of elements in the list that satisfy the predicate as a BigInt.

Example
 List.empty[BigInt].count(_ > 1) === BigInt(0)
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.count(_ > 1) === BigInt(2)
def deleteFirst[B >: A](elem: B)(using eq: Eq[B]): List[A]

Deletes the first occurrence of the specified element from the list.

Deletes the first occurrence of the specified element from the list.

Type parameters

B

The type of the element being deleted, which must be a supertype of A

Value parameters

elem

The element to delete from the list

eq

An instance of Eq[B] used to compare elements for equality

Attributes

Returns

A new list with the first occurrence of the specified element removed, or the original list if the element is not found

Example
 List.empty[BigInt].deleteFirst(BigInt(2)) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(2), Nil)))
 list.deleteFirst(BigInt(2)) === Cons(BigInt(1), Cons(BigInt(2), Nil))
 list.deleteFirst(BigInt(3)) === list
def diff[B >: A](other: List[B])(using eq: Eq[B]): List[A]

Returns a new list containing elements from this list that do not appear in the other list.

Returns a new list containing elements from this list that do not appear in the other list.

Type parameters

B

The type of elements in the other list, which must be a supertype of A

Value parameters

eq

An instance of Eq[B] used to compare elements for equality

other

The list whose elements should be removed from this list

Attributes

Returns

A new list containing elements from this list that do not appear in the other list

Example
 List.empty[BigInt].diff(List(BigInt(1), BigInt(2))) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.diff(List(BigInt(2))) === Cons(BigInt(1), Cons(BigInt(3), Nil))
 list.diff(Nil) === list
 list.diff(list) === Nil
def distinct[B >: A](using eq: Eq[B]): List[A]

Returns a new list with duplicate elements removed, keeping only the first occurrence of each element.

Returns a new list with duplicate elements removed, keeping only the first occurrence of each element.

Type parameters

B

The type of elements being compared, which must be a supertype of A

Value parameters

eq

An instance of Eq[B] used to compare elements for equality

Attributes

Returns

A new list containing only distinct elements in their original order

Example
 List.empty[BigInt].distinct === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(1), Cons(BigInt(3), Nil))))
 list.distinct === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
def drop(skip: BigInt): List[A]

Returns a list consisting of all elements except the first skip elements of this list.

Returns a list consisting of all elements except the first skip elements of this list.

Value parameters

skip

The number of elements to drop from the beginning of the list

Attributes

Returns

A new list with the first skip elements removed, or an empty list if skip is greater than or equal to the list's length

Example
 List.empty[BigInt].drop(2) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.drop(2) === Cons(BigInt(3), Nil)
 list.drop(0) === list
 list.drop(4) === Nil
def dropRight(skip: BigInt): List[A]

Returns a list consisting of all elements except the last skip elements of this list.

Returns a list consisting of all elements except the last skip elements of this list.

Value parameters

skip

The number of elements to drop from the end of the list

Attributes

Returns

A new list with the last skip elements removed, or an empty list if skip is greater than or equal to the list's length

Example
 List.empty[BigInt].dropRight(2) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.dropRight(2) === Cons(BigInt(1), Nil)
 list.dropRight(0) === list
 list.dropRight(4) === Nil
def dropWhile(predicate: A => Boolean): List[A]

Drops elements from the beginning of the list as long as they satisfy the predicate.

Drops elements from the beginning of the list as long as they satisfy the predicate.

Value parameters

predicate

A function that takes an element and returns true if it should be dropped from the result

Attributes

Returns

A new list containing all elements from the first element that does not satisfy the predicate until the end of the list

Example
 List.empty[BigInt].dropWhile(_ &lt; 3) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.dropWhile(_ &lt; 3) === Cons(BigInt(3), Nil)
 list.dropWhile(_ &lt; 1) === list
 list.dropWhile(_ &lt; 4) === Nil
def exists(predicate: A => Boolean): Boolean

Checks if the list contains an element that satisfies the given predicate.

Checks if the list contains an element that satisfies the given predicate.

Value parameters

predicate

A function that takes an element of type A and returns true if the element matches the condition.

Attributes

Returns

true if there is at least one element in the list that satisfies the predicate, false otherwise.

Example
 List.empty[BigInt].exists(_ > 1) === false
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.exists(_ > 1) === true
 list.exists(_ > 3) === false
def filter(predicate: A => Boolean): List[A]

Filters the elements of the list based on a predicate.

Filters the elements of the list based on a predicate.

Value parameters

predicate

A function that takes an element of type A and returns true if the element should be included in the resulting list, or false otherwise.

Attributes

Returns

A new list containing only the elements that satisfy the predicate.

Example
 List.empty[BigInt].filter(_ % 2 == 1) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 val filtered = list.filter(_ % 2 == 1)
 filtered === Cons(BigInt(1), Cons(BigInt(3), Nil))
def filterMap[B](predicate: A => Option[B]): List[B]

Filters the elements of the list based on a predicate that returns an Option[B].

Filters the elements of the list based on a predicate that returns an Option[B].

If the predicate returns None, the element is excluded from the resulting list. If it returns Some(value), the value is included in the resulting list.

Type parameters

B

The type of the values to be included in the resulting list.

Value parameters

predicate

A function that takes an element of type A and returns an Option[B].

Attributes

Returns

A new list containing only the elements for which the predicate returned Some(value).

Example
 List.empty[BigInt].filterMap(x => if x % 2 == 1 then Some(x) else None) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 val filtered = list.filterMap(x => if x % 2 == 1 then Some(x) else None)
 filtered === Cons(BigInt(1), Cons(BigInt(3), Nil))
def filterNot(predicate: A => Boolean): List[A]

Filters the elements of the list based on a predicate that returns false for elements to be excluded.

Filters the elements of the list based on a predicate that returns false for elements to be excluded.

Value parameters

predicate

A function that takes an element of type A and returns true if the element should be excluded from the resulting list, or false otherwise.

Attributes

Returns

A new list containing only the elements that do not satisfy the predicate.

Example
 List.empty[BigInt].filterNot(_ % 2 == 1) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 val filtered = list.filterNot(_ % 2 == 1)
 filtered === Cons(BigInt(2), Nil)
def find(predicate: A => Boolean): Option[A]

Finds the first element in the list that satisfies the given predicate.

Finds the first element in the list that satisfies the given predicate.

Value parameters

predicate

A function that takes an element of type A and returns true if the element matches the condition.

Attributes

Returns

An Option containing the first element that satisfies the predicate, or None if no such element exists.

Example
 List.empty[BigInt].find(_ > 1) === None
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.find(_ > 1) === Some(BigInt(2))
 list.find(_ > 3) === None
def findMap[B](mapper: A => Option[B]): Option[B]

Finds the first element in the list that, when passed to the provided mapper function returns non-None or None otherwise.

Finds the first element in the list that, when passed to the provided mapper function returns non-None or None otherwise.

Value parameters

mapper

A function that takes an element of type A and returns an Option[B].

Attributes

Returns

An Option[B] containing the first non-None result from applying the mapper to the elements of the list, or None if no such element exists.

Example
 List.empty[String].findMap(str => if str.length >= 3 then Some(BigInt(str.length)) else None) === None
 val list: List[String] = Cons("a", Cons("bb", Cons("ccc", Nil)))
 list.findMap(str => if str.length >= 2 then Some(BigInt(str.length)) else None) === Some(BigInt(2))
 list.findMap(str => if str.length >= 4 then Some(BigInt(str.length)) else None) === None
def findUniqueOrElse(predicate: A => Boolean, orElse: Unit => A): A

Returns the unique element that satisfies the predicate, or orElse(()) when no element or more than one element satisfies it.

Returns the unique element that satisfies the predicate, or orElse(()) when no element or more than one element satisfies it.

This is the non-inline body behind findUniqueOrFail: the scan is compiled once as a module function and each call site contributes only its predicate and its orElse closure. Passing the failure as a continuation rather than as a String parameter costs the same in a release build and about 10% less with error traces on, because the message is not threaded through every recursive step. Measured against inlining the scan at every call site: 88 B for one site, +18 B per further site, versus 79 B and +64 B.

Attributes

Example
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.findUniqueOrElse(_ > 2, _ => BigInt(0)) === BigInt(3)
 list.findUniqueOrElse(_ > 1, _ => BigInt(0)) === BigInt(0)
inline def findUniqueOrFail(predicate: A => Boolean, inline message: String): A

Returns the unique element that satisfies the predicate, or fails with message when no element or more than one element satisfies it.

Returns the unique element that satisfies the predicate, or fails with message when no element or more than one element satisfies it.

Unlike find, which stops at the first match, this keeps scanning after the first match to prove there is no second one. It is a single pass with no intermediate list; filter(predicate).length === 1 walks the list twice and allocates the filtered copy.

Value parameters

message

The failure message when zero or several elements match.

predicate

A function that takes an element of type A and returns true if the element matches the condition.

Attributes

Returns

The only element that satisfies the predicate.

Example
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.findUniqueOrFail(_ > 2, "expected one") === BigInt(3)
 list.findUniqueOrFail(_ > 1, "expected one") // fails: two elements match
 list.findUniqueOrFail(_ > 3, "expected one") // fails: no element matches
def flatMap[B](mapper: A => List[B]): List[B]

Applies a function to each element of the list, producing a new list with the results.

Applies a function to each element of the list, producing a new list with the results.

This method is similar to map, but it allows the function to return a list for each element, effectively flattening the result.

Value parameters

mapper

A function that takes an element of type A and returns a list of type List[B].

Attributes

Returns

A new list containing all elements produced by applying mapper to each element of the original list and flattening the results.

Example
 List.empty[BigInt].flatMap(x => List(x, x + 1)) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Nil))
 val result = list.flatMap(x => List(x, x + 1))
 result === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(2), Cons(BigInt(3), Nil))))
def foldLeft[B](init: B)(combiner: (B, A) => B): B

Performs a left fold on the list.

Performs a left fold on the list.

Type parameters

B

The type of the accumulated value.

Value parameters

combiner

A function that combines the accumulated value and the current element.

init

The initial value to start the fold with.

Attributes

Returns

The result of applying the combiner function to all elements of the list, starting with the initial value.

Example
 List.empty[BigInt].foldLeft(BigInt(0))(_ + _) === BigInt(0)
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 val sum = list.foldLeft(BigInt(0))(_ + _)
 sum === BigInt(6)
def foldRight[B](init: B)(combiner: (A, B) => B): B

Performs a right fold on the list.

Performs a right fold on the list.

Value parameters

B

The type of the accumulated value.

combiner

A function that combines the current element and the accumulated value.

init

The initial value to start the fold with.

Attributes

Returns

The result of applying the combiner function to all elements of the list, starting with the initial value.

Example
 List.empty[BigInt].foldRight(BigInt(0))(_ + _) === BigInt(0)
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 val sum = list.foldRight(BigInt(0))(_ + _)
 sum === BigInt(6)
def forall(predicate: A => Boolean): Boolean

Checks if all elements in the list satisfy the given predicate.

Checks if all elements in the list satisfy the given predicate.

Value parameters

predicate

A function that takes an element of type A and returns true if the element matches the condition.

Attributes

Returns

true if all elements in the list satisfy the predicate, false otherwise.

Example
 List.empty[BigInt].forall(_ > 1) === true
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.forall(_ > 0) === true
 list.forall(_ > 2) === false
def foreach(f: A => Unit): Unit

Applies the given function to each element of the list.

Applies the given function to each element of the list.

Value parameters

f

The function to apply to each element.

Attributes

Example

def get(index: BigInt): Option[A]

Retrieves the element at the specified index in the list.

Retrieves the element at the specified index in the list.

Value parameters

index

The zero-based index of the element to retrieve.

Attributes

Returns

An Option containing the element at the specified index, or None if the index is out of bounds.

Example
 List.empty[BigInt].get(0) === None
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.get(1) === Some(BigInt(2))
 list.get(3) === None
 list.get(-1) === None
def groupBy[K : Ord](keyExtractor: A => K): SortedMap[K, List[A]]

Groups the elements of this list by the keys returned by the specified function.

Groups the elements of this list by the keys returned by the specified function.

Type parameters

K

The type of the keys.

Value parameters

keyExtractor

A function that extracts the key from each element.

Attributes

Returns

An SortedMap mapping each key to a list of elements that have that key.

Example
 List.empty[BigInt].groupBy(_ % 2) === SortedMap.empty
 val list: List[BigInt] = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
 list.groupBy(_ % 2) === SortedMap.fromList((BigInt(0), Cons(2, Cons(4, Nil))), (BigInt(1), Cons(1, Cons(3, Nil))))
def groupMap[K : Ord, B](keyExtractor: A => K)(valueExtractor: A => B): SortedMap[K, List[B]]

Groups the elements of this list by the keys returned by the key extractor function and transforms each element using the value extractor function.

Groups the elements of this list by the keys returned by the key extractor function and transforms each element using the value extractor function.

Type parameters

B

The type of the transformed elements.

K

The type of the keys.

Value parameters

keyExtractor

A function that extracts the key from each element.

valueExtractor

A function that transforms each element before collecting into groups.

Attributes

Returns

An SortedMap mapping each key to a list of transformed elements that have that key.

Example
 List.empty[BigInt].groupMap(_ % 2)(_ * 2) === SortedMap.empty
 val list: List[BigInt] = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
 list.groupMap(_ % 2)(_ * 2) === SortedMap.fromList((BigInt(0), Cons(4, Cons(8, Nil))), (BigInt(1), Cons(2, Cons(6, Nil))))
def groupMapReduce[K : Ord, B](keyExtractor: A => K)(valueExtractor: A => B)(reducer: (B, B) => B): SortedMap[K, B]

Groups elements by the keys returned by the key extractor function, transforms each element using the value extractor function, and combines values with the same key using the reducer function.

Groups elements by the keys returned by the key extractor function, transforms each element using the value extractor function, and combines values with the same key using the reducer function.

Type parameters

B

The type of the transformed elements.

K

The type of the keys.

Value parameters

keyExtractor

A function that extracts the key from each element.

reducer

A function that combines two values with the same key.

valueExtractor

A function that transforms each element before reduction.

Attributes

Returns

An SortedMap mapping each key to the reduced value of all elements with that key.

Example
 List.empty[BigInt].groupMapReduce(_ % 2)(identity)(_ + _) === SortedMap.empty
 val list: List[BigInt] = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
 list.groupMapReduce(_ % 2)(identity)(_ + _) === SortedMap.fromList((BigInt(0), BigInt(6)), (BigInt(1), BigInt(4)))
def head: A

Returns the first element of the list or throws an exception if the list is empty.

Returns the first element of the list or throws an exception if the list is empty.

Attributes

Returns

The first element of the list.

Throws
NoSuchElementException

If the list is empty.

Example
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.head === BigInt(1)
 List.empty[BigInt].head // throw NoSuchElementException
def headOption: Option[A]

Returns the first element of the list as an Option.

Returns the first element of the list as an Option.

Attributes

Returns

An Option containing the first element of the list, or None if the list is empty.

Example
 List.empty[BigInt].headOption === None
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.headOption === Some(1)
 List.empty[BigInt].headOption === None
def indexOf[B >: A](elem: B)(using eq: Eq[B]): BigInt

Finds the index of the first occurrence of the specified element in the list.

Finds the index of the first occurrence of the specified element in the list.

Type parameters

B

The type of the element being searched for, which must be a supertype of A.

Value parameters

elem

The element to search for in the list.

Attributes

Returns

The index of the first occurrence of the element, or BigInt(-1) if the element is not found.

Example
 List.empty[BigInt].indexOf(BigInt(2)) === BigInt(-1)
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.indexOf(BigInt(2)) === BigInt(1)
 list.indexOf(BigInt(4)) === BigInt(-1)
 list.indexOf(BigInt(-1)) === BigInt(-1)
def indexOfOption[B >: A](elem: B)(using eq: Eq[B]): Option[BigInt]

Finds the index of the first occurrence of the specified element in the list.

Finds the index of the first occurrence of the specified element in the list.

Type parameters

B

The type of the element being searched for, which must be a supertype of A.

Value parameters

elem

The element to search for in the list.

Attributes

Returns

An Option containing the index of the first occurrence of the element, or None if the element is not found.

Example
 List.empty[BigInt].indexOfOption(BigInt(2)) === None
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.indexOfOption(BigInt(2)) === Some(BigInt(1))
 list.indexOfOption(BigInt(4)) === None
 list.indexOfOption(BigInt(-1)) === None
inline def init: List[A]

Returns a new list containing all elements except the last element of this list or throws an exception if the list is empty.

Returns a new list containing all elements except the last element of this list or throws an exception if the list is empty.

Attributes

Returns

A new list containing all elements except the last.

Throws
NoSuchElementException

If the list is empty.

Example
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.init === Cons(BigInt(1), Cons(BigInt(2), Nil))
 List.empty[BigInt].init // throw NoSuchElementException
def isDefinedAt(index: BigInt): Boolean

Checks if the list contains an element at the specified index.

Checks if the list contains an element at the specified index.

Value parameters

index

The zero-based BigInt index to check.

Attributes

Returns

true if the list contains an element at the specified index, false otherwise.

Example
 List.empty[BigInt].isDefinedAt(BigInt(0)) === false
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.isDefinedAt(BigInt(1)) === true
 list.isDefinedAt(BigInt(3)) === false
 list.isDefinedAt(BigInt(-1)) === false
def isEmpty: Boolean

Checks if the list is empty.

Checks if the list is empty.

Attributes

Returns

true if the list is empty, false otherwise.

Example
 List.empty[BigInt].isEmpty   === true
 Cons(BigInt(1), Nil).isEmpty === false
def isSortedWith(lt: (A, A) => Boolean): Boolean

True when every element is less than or equal to its successor under lt.

True when every element is less than or equal to its successor under lt.

The explicit-comparator twin of isSorted, for the same reason sortWith exists: it skips the Order allocation Ord forces on every comparison.

Value parameters

lt

true when the first argument sorts strictly before the second

Attributes

def last: A

Returns the last element of the list or throws an exception if the list is empty.

Returns the last element of the list or throws an exception if the list is empty.

Attributes

Returns

The last element of the list.

Throws
NoSuchElementException

If the list is empty.

Example
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.last === BigInt(3)
 List.empty[BigInt].last // throw NoSuchElementException
def lastOption: Option[A]

Returns the last element of the list as an Option.

Returns the last element of the list as an Option.

Attributes

Returns

An Option containing the last element of the list, or None if the list is empty.

Example
 List.empty[BigInt].lastOption === None
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.lastOption === Some(BigInt(3))
 List.empty[BigInt].lastOption === None
def length: BigInt

Returns the number of elements in the list.

Returns the number of elements in the list.

Attributes

Returns

The number of elements in the list as a BigInt.

Example
 List.empty[BigInt].length === BigInt(0)
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.length === BigInt(3)
def map[B](mapper: A => B): List[B]

Applies a function to each element of the list, producing a new list with the results.

Applies a function to each element of the list, producing a new list with the results.

Value parameters

mapper

A function that takes an element of type A and returns a value of type B.

Attributes

Returns

A new list where each element is the result of applying mapper to the corresponding element of the original list.

Example
 List.empty[BigInt].map(_ * 2) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 val result = list.map(_ * 2)
 result === Cons(BigInt(2), Cons(BigInt(4), .Cons(BigInt(6), Nil)))
inline def nonEmpty: Boolean

Checks if the list is not empty.

Checks if the list is not empty.

Attributes

Returns

true if the list contains at least one element, false otherwise.

Example
 List.empty[BigInt].nonEmpty    === false
 Cons(BigInt(1), Nil).nonEmpty  === true
inline def prepended[B >: A](elem: B): List[B]

Prepends an element to the list.

Prepends an element to the list.

Type parameters

B

The type of the element, which must be a supertype of A.

Value parameters

elem

The element to prepend.

Attributes

Returns

A new list with the element prepended.

Example
 List.empty[BigInt].prepended(BigInt(1)) === Cons(BigInt(1), Nil)
 val list: List[BigInt] = Cons(BigInt(2), Cons(BigInt(3), Nil))
 list.prepended(BigInt(1)) === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
inline def prependedAll[B >: A](other: List[B]): List[B]

Prepends all elements of another list to this list.

Prepends all elements of another list to this list.

Type parameters

B

The type of the elements in the other list, which must be a supertype of A.

Value parameters

other

The list whose elements will be prepended.

Attributes

Returns

A new list with all elements of other prepended to this list.

Example
 List.empty[BigInt].prependedAll(List(BigInt(1), BigInt(2))) === Cons(BigInt(1), Cons(BigInt(2), Nil))
 val list: List[BigInt] = Cons(BigInt(3), Nil)
 list.prependedAll(List(BigInt(1), BigInt(2))) === Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
def reverse: List[A]

Returns a new list with elements in reverse order.

Returns a new list with elements in reverse order.

Attributes

Returns

A new list containing the same elements but in reverse order.

Example
 List.empty[BigInt].reverse === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.reverse === Cons(BigInt(3), Cons(BigInt(2), Cons(BigInt(1), Nil)))
inline def singleOrFail(inline message: String): A

Returns the only element of this list, or fails with message when the list is empty or has more than one element. Unlike head, a second element is a failure.

Returns the only element of this list, or fails with message when the list is empty or has more than one element. Unlike head, a second element is a failure.

Value parameters

message

The failure message when the list is not of size one.

Attributes

Returns

The only element of the list.

Example
 List.singleton(BigInt(1)).singleOrFail("expected one") === BigInt(1)
 List.empty[BigInt].singleOrFail("expected one") // fails
 Cons(BigInt(1), Cons(BigInt(2), Nil)).singleOrFail("expected one") // fails
inline def size: BigInt

Alias for length.

Alias for length.

Attributes

def sortWith(lt: (A, A) => Boolean): List[A]

Sorts using an explicit "strictly less than" test instead of an Ord instance.

Sorts using an explicit "strictly less than" test instead of an Ord instance.

Same stable natural merge sort as sort, but around '''20% cheaper''' whenever the caller has a direct boolean comparison. Ord[A] is (A, A) => Order, so every single comparison through sort allocates an Order constructor and immediately matches it back down to a boolean. Passing the boolean test skips both, and at concrete types like BigInt it also takes the monomorphic fast path straight to lessThanInteger:

xs.sortWith((a, b) => a &lt; b)     // BigInt: lowers to lessThanInteger

The compiled body is smaller too — 252 bytes against 290 for sort.

lt must be a strict order: irreflexive (lt(a, a) false) and transitive. Supplying ` a < b) === List(BigInt(1), BigInt(3)) }}}

Attributes

def tail: List[A]

Returns a list consisting of all elements except the first element of this list or throws an exception if the list is empty.

Returns a list consisting of all elements except the first element of this list or throws an exception if the list is empty.

Attributes

Returns

A list containing all elements except the first.

Throws
NoSuchElementException

If the list is empty.

Example
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.tail === Cons(BigInt(2), Cons(BigInt(3), Nil))
 List.empty[BigInt].tail // throw NoSuchElementException
def take(count: BigInt): List[A]

Takes the first count elements from the list.

Takes the first count elements from the list.

Value parameters

count

The number of elements to take from the beginning of the list

Attributes

Returns

A new list containing the first count elements, or an empty list if count is less than or equal to 0

Example
 List.empty[BigInt].take(2) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.take(2) === Cons(BigInt(1), Cons(BigInt(2), Nil))
 list.take(0) === Nil
 list.take(4) === list
def takeRight(count: BigInt): List[A]

Takes the last count elements from the list.

Takes the last count elements from the list.

Value parameters

count

The number of elements to take from the end of the list

Attributes

Returns

A new list containing the last count elements, or an empty list if count is less than or equal to 0

Example
 List.empty[BigInt].takeRight(2) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.takeRight(2) === Cons(BigInt(2), Cons(BigInt(3), Nil))
 list.takeRight(0) === Nil
 list.takeRight(4) === list
def takeWhile(predicate: A => Boolean): List[A]

Takes elements from the beginning of the list as long as they satisfy the predicate.

Takes elements from the beginning of the list as long as they satisfy the predicate.

Value parameters

predicate

A function that takes an element and returns true if it should be included in the result

Attributes

Returns

A new list containing elements from the beginning of the list until an element is found that does not satisfy the predicate

Example
 List.empty[BigInt].takeWhile(_ &lt; 3) === Nil
 val list: List[BigInt] = Cons(BigInt(1), Cons(BigInt(2), Cons(BigInt(3), Nil)))
 list.takeWhile(_ &lt; 3) === Cons(BigInt(1), Cons(BigInt(2), Nil))
 list.takeWhile(_ &lt; 1) === Nil
 list.takeWhile(_ &lt; 4) === list
def toScalaList: List[A]

Converts this list to a scala.collection.immutable.List.

Converts this list to a scala.collection.immutable.List.

This method allows you to convert a List[A] to a Scala standard library scala.collection.immutable.List[A]. This is an offchain-only operation.

Attributes

Returns

A scala.collection.immutable.List[A] containing all the elements from this list in the same order.

def zip[B](other: List[B]): List[(A, B)]

Zips this list with another list, producing a list of pairs.

Zips this list with another list, producing a list of pairs.

The resulting list will have the length of the shorter of the two lists.

Type parameters

B

The type of elements in the other list.

Value parameters

other

The other list to zip with.

Attributes

Returns

A list of pairs, where each pair contains an element from this list and an element from the other list at the same index.

Example
 List(BigInt(1), BigInt(2)).zip(List(BigInt(3), BigInt(4))) === Cons((BigInt(1), BigInt(3)), Cons((BigInt(2), BigInt(4)), Nil))
 List.empty[BigInt].zip(List(BigInt(1), BigInt(2))) === Nil
extension [A](self: List[A])
inline def ++:[B >: A](other: List[B]): List[B]

Alias on prependedAll

Alias on prependedAll

Attributes