Un Dict en Elm es un diccionario inmutable de cero o más pares clave-valor.
Los dicts se manipulan con funciones y operadores definidos en el módulo Dict.
Las anotaciones de tipo de los dicts se escriben así
Dict String (List Int) --> a dict with String keys and List Int values
Dict Int String --> a dict with Int keys and String values
Los dicts se pueden crear así:
empty : Dict Int String
empty = Dict.empty
singleValue = Dict.singleton 5 "Value for key 5" --> Dict Int String
twoValues = Dict.fromList [ ( "Alice", 0 ), ( "Bob", 1 ) ] --> Dict String Int
Los elementos se pueden obtener con get.
Como puede que una clave esté presente o no en el dict, el resultado vendrá envuelto en un Maybe.
alice = Dict.fromList [ ( 0, "Alice" ) ]
keyExists = Dict.get 0 alice --> Just "Alice"
keyNotPresent = Dict.get 1 alice --> Nothing
Los elementos se pueden añadir con insert.
Los elementos de claves que ya están en el dict se reemplazan.
alice = Dict.fromList [ ( "Alice", 0 ) ]
aliceAndBob = Dict.insert "Bob" 1 alice --> Dict.fromList [ ( "Alice", 0 ), ( "Bob", 1 ) ]
aliceAndAlice = Dict.insert "Alice" 1 alice --> Dict.fromList [ ( "Alice", 1 ) ]
Los elementos se pueden actualizar con update.
Si la clave no existe, se llamará a la función de actualización con Nothing.
alice = Dict.fromList [ ( 0, "Alice" ) ]
aliceUpperCase = Dict.update 0 (Maybe.map String.toUpper) alice --> Dict.fromList [ ( 0, "ALICE" ) ]
aliceNoCase = Dict.update 0 (\_ -> Nothing) alice --> Dict.empty
bobUpperCase = Dict.update 1 (\_ -> Just "BOB") alice --> Dict.fromList [ ( 0, "Alice" ), ( 1, "BOB" ) ]
bobNoCase = Dict.update 1 (\_ -> Nothing) alice --> Dict.fromList [ ( 0, "Alice" ) ]
Los elementos se pueden eliminar con remove.
Si la clave no existe, no se produce ningún cambio.
alice = Dict.fromList [ ( 0, "Alice" ) ]
stillAlice = Dict.remove 1 --> ( 0, "Alice" )
empty = Dict.remove 0 alice --> Dict.empty
Una lista de pares clave-valor se puede convertir en un dict con fromList.
alice = Dict.fromList [ ( 0, "Bob" ), ( 0, "Alice" ) ]
--> True Dict.fromList [ ( 0, "Alice" ) ]
Los elementos se pueden convertir en una lista con toList.
La lista está ordenada por las claves.
aliceAndBob = Dict.fromList [ ( 1, "Alice" ), ( 0, "Bob" ) ]
bobAndAlice = Dict.toList aliceAndBob
--> [ ( 0, "Bob" ), ( 1, "Alice" ) ]
Se pueden eliminar varios elementos con filter.
aliceAndBob = Dict.fromList [ ( "Alice", 1 ), ( "Bob", 0 ) ]
bob = Dict.filter (\name count -> name == "Bob") aliceAndBob --> Dict.fromList [ ( "Bob", 0 ) ]
Los elementos se pueden transformar con map.
alice = Dict.fromList [ ( "Alice", 0 ) ]
empty = Dict.map (\player count -> count + 1) alice --> Dict.fromList [ ( "Alice", 1 ) ]
Los dicts se pueden combinar o transformar con merge.
aliceAndBob = Dict.fromList [ ( "Alice", 1 ), ( "Bob", 1 ) ]
bobAndCedd = Dict.fromList [ ( "Bob", 1 ), ( "Cedd", 1 ) ]
firstDictCountsDouble = Dict.merge
-- when only in aliceAndBob
(\name count mergedCounts -> Dict.insert name (2 * count) mergedCounts)
-- when in aliceAndBob and bobAndCedd
(\name aliceAndBobCount bobAndCeddCount mergedCounts -> Dict.insert name (2 * aliceAndBobCount + bobAndCeddCount) mergedCounts)
-- when only in bobAndCedd
(\name count mergedCounts -> Dict.insert name count mergedCounts)
-- the two dicts to merge
aliceAndBob
bobAndCedd
-- the initial state of the merge
Dict.empty
--> Dict.fromList [ ( "Alice", 2 ), ( "Bob", 3 ), ( "Cedd", 1 ) ]
Cualquier función u operador que parezca modificar un dict (como añadir un elemento) en realidad devolverá un dict nuevo. El rendimiento normalmente no es un problema, ya que la implementación evita asignaciones y copias innecesarias.
En Elm, por lo general es mejor usar abstracciones de más alto nivel, como Dict.map, Dict.filter y Dict.merge, en lugar de abstracciones de más bajo nivel como Dict.get y Dict.remove, aunque, por supuesto, depende del contexto.
Tu tarea consiste en tomar un array de goleadores de un partido y contar cuántos goles ha marcado cada jugador.
PlayerName es un alias de tipo para String, para que el código sea más fácil de leer y para distinguir este uso de String de otros usos de String.
Primero implementa updateGoalCountForPlayer para inicializar o incrementar el recuento de goles de un jugador.
Después implementa la función aggregateScorers para contar cuántos goles ha marcado cada jugador, usando updateGoalCountForPlayer.
Esta función toma un List PlayerName (los nombres de los jugadores que marcaron los goles, que puede contener nombres de jugador duplicados) y devuelve un Dict PlayerName Int que contiene todos los jugadores del array junto con cuántos goles han marcado.
aggregateScorers [ "Betty", "Cedd", "Betty" ]
--> Dict.fromList [ ( "Betty", 2 ), ( "Cedd", 1 ) ]
Implementa la función removeInsignificantPlayers para descartar a los jugadores que hayan marcado menos goles que el umbral.
removeInsignificantPlayers 2 (Dict.fromList [ ( "Betty", 2 ), ( "Cedd", 1 ) ] )
--> Dict.fromList [ ( "Betty", 2 ) ]
Implementa la función resetPlayerGoalCount para restablecer a cero los goles marcados por un jugador.
resetPlayerGoalCount "Cedd" (Dict.fromList [ ( "Betty", 2 ), ( "Cedd", 1 ) ] )
--> Dict.fromList [ ( "Betty", 2 ), ( "Cedd", 0 ) ]
Implementa la función formatPlayer para dar formato al recuento de goles de un solo jugador como un string. Si el jugador no existe en el diccionario, asume que su recuento de goles es cero.
formatPlayer "Betty" (Dict.fromList [ ( "Betty", 2 ), ( "Cedd", 1 ) ] )
--> "Betty: 2"
Implementa la función formatPlayers para dar formato al recuento de goles de todos los jugadores como un string. Los jugadores deben estar ordenados por nombre de jugador.
formatPlayers (Dict.fromList [ ( "Betty", 2 ), ( "Cedd", 1 ) ] )
--> "Betty: 2, Cedd: 1"
Implementa la función combineGames, contando el número total de goles que ha marcado cada jugador en ambos partidos.
combine Games
(Dict.fromList [ ( "Betty", 2 ), ( "Cedd", 1 ) ] )
(Dict.fromList [ ( "Betty", 2 ), ( "Mario", 3 ) ] )
--> Dict.fromList [ ( "Betty", 4 ), ( "Cedd", 1 ), ( "Mario", 3 ) ]
Regístrate en Exercism para aprender y dominar Elm con 28 conceptos110 ejercicios y mentoría humana real, todo gratis.