Search code examples
listelm

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


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.


Solution

  • 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)