Haskell Language Lists Accessing elements in lists

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Access the nth element of a list (zero-based):

list = [1 .. 10]

firstElement = list !! 0           -- 1

Note that !! is a partial function, so certain inputs produce errors:

list !! (-1)     -- *** Exception: Prelude.!!: negative index  

list !! 1000     -- *** Exception: Prelude.!!: index too large

There's also Data.List.genericIndex, an overloaded version of !!, which accepts any Integral value as the index.

import Data.List (genericIndex)

list `genericIndex` 4              -- 5

When implemented as singly-linked lists, these operations take O(n) time. If you frequently access elements by index, it's probably better to use Data.Vector (from the vector package) or other data structures.



Got any Haskell Language Question?