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

11684 picture 11684 · Apr 21, 2014 · Viewed 16.2k times · Source

I got a list, and now I want the nth item. In Haskell I would use !!, but I can't find an elm variant of that.

Answer

mgold picture mgold · Oct 7, 2014

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