¿Cómo obtengo un elemento de lista por índice en elm?


Tengo una lista, y ahora quiero el enésimo elemento. En Haskell usaría !!, pero no puedo encontrar una variante de elm.

Author: Misha Moroshko, 2014-04-21

3 answers

No hay equivalente de esto en Elm. Por supuesto, podría implementarlo usted mismo.

(Nota: Esta no es una función "total", por lo que crea una excepción cuando el índice está fuera de rango).

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

Una mejor manera sería definir una función total, usando el tipo de datos Maybe.

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)
 13
Author: Daniël Heres,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-02 15:14:37

Elm agregó matrices en 0.12.1.

import Array

myArray = Array.fromList [1..5]

myItem = Array.get 2 myArray

Los arrays están indexados a cero. Los índices negativos no están soportados actualmente (bummer, lo sé).

Tenga en cuenta que myItem : Maybe Int. Elm hace todo lo posible para evitar errores de tiempo de ejecución, por lo que out of bounds access devuelve un Nothing explícito.

Si se encuentra buscando indexar en una lista en lugar de tomar la cabeza y la cola, debe considerar el uso de una matriz.

Documentación del array Importante: El la implementación de la matriz central está rota; use este en su lugar!

 28
Author: mgold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-03 05:50:37

He usado esto:

(!!): Int -> List a -> Maybe a

(!!) index list =                          -- 3 [ 1, 2, 3, 4, 5, 6 ]

   if  (List.length list) >= index then

        List.take index list               -- [ 1, 2, 3 ]
        |> List.reverse                    -- [ 3, 2, 1 ]
        |> List.head                       -- Just 3
   else 
      Nothing

Por supuesto, se obtiene un Tal vez y es necesario desenvolverlo cuando se utiliza esta función. No hay garantía de que su lista no esté vacía, o que solicite un índice imposible (como 1000), por lo que es por eso que el compilador elm lo obliga a dar cuenta de ese caso.

main = 
let 
  fifthElement = 
    case 5 !! [1,2,3,4,255,6] of  // not sure how would you use it in Haskell?! But look's nice as infix function. (inspired by @Daniël Heres)
      Just a ->
        a
      Nothing ->
        -1
in
    div [] 
        [ text <| toString fifthElement ]         // 255
 1
Author: AIon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-10 19:22:37