How do I get a list item by index in elm?

There is no equivalent of this in Elm. You could of course implement it yourself.

(Note: This is not a "total" function, so it creates an exception when the index is out of range).

infixl 9 !!
(!!) : [a] -> Int -> a
xs !! n  = head (drop n xs)

A better way would be to define a total function, using the Maybe data type.

infixl 9 !!
(!!) : [a] -> Int -> Maybe a
xs !! n  = 
  if | n < 0     -> Nothing
     | otherwise -> case (xs,n) of
         ([],_)    -> Nothing
         (x::xs,0) -> Just x
         (_::xs,n) -> xs !! (n-1)

Elm added arrays in 0.12.1, and the implementation was massively overhauled in 0.19 to improve correctness and performance.

import Array

myArray = Array.fromList [1..5]

myItem = Array.get 2 myArray

Arrays are zero-indexed. Negative indices are not supported currently (bummer, I know).

Note that myItem : Maybe Int. Elm does everything it can to avoid runtime errors, so out of bounds access returns an explicit Nothing.

If you find yourself looking to index into a list rather than take the head and tail, you should consider using an array.

Array documentation

Tags:

List

Elm