Elm Language Lists and Iteration Getting nth element from the list


List doesn't support "random access", which means it takes more work to get, say, the fifth element from the list than the first element, and as a result there's no List.get nth list function. One has to go all the way from the beginning (1 -> 2 -> 3 -> 4 -> 5).

If you need random access, you might get better results (and performance) with random access data structures, like Array, where taking the first element takes the same amount of work as taking, say, the 1000th. (complexity O(1)).

Nevertheless, it's possible (but discouraged) to get nth element:

get : Int -> List a -> Maybe a
get nth list =
        |> List.drop (nth - 1)
        |> List.head

fifth : Maybe Int
fifth = get 5 [1..10]
--    = Just 5

nonexistent : Maybe Int
nonexistent = get 5 [1..3]
--          = Nothing

Again, this takes significantly more work the bigger the nth argument is.