query
On this page

elemAt

lib.strings.elemAt

Primop
Docs pulled from | This Revision | 18 days ago


Nix manual

Takes 2 arguments

xs, n

Return element n from the list xs. Elements are counted starting from 0. A fatal error occurs if the index is out of bounds.

Noogle detected

Aliases

Detected Type
elemAt :: [a] -> Int -> a

Implementation

This function is implemented in c++ and is part of the native nix runtime.

src/libexpr/primops.cc:3771

static void prim_elemAt(EvalState & state, CallSite callSite, Value * const * args, Value & v)
{
    NixInt::Inner n =
        state.forceInt(*args[1], noPos, "while evaluating the second argument passed to 'builtins.elemAt'").value;
    state.forceList(*args[0], noPos, "while evaluating the first argument passed to 'builtins.elemAt'");
    if (n < 0 || std::make_unsigned_t<NixInt::Inner>(n) >= args[0]->listSize())
        state.error<EvalError>("'builtins.elemAt' called with index %d on a list of size %d", n, args[0]->listSize())
            .atPos(noPos)
            .debugThrow();
    auto ptr = args[0]->listView()[n];
    state.forceValue(*ptr, noPos);
    v = *ptr;
}

Implementation

The following is the current implementation of this function.

elemAt