typestar

Tuplas y pares en Haskell

Empareja filas de asientos con conteos de boletos y después saca la fila más ocupada.

-- A tuple pattern takes a pair apart in one step.
module SeatChart where

rows :: [String]
rows = ["A", "B", "C"]

-- zip pairs the lists element by element, stopping at the shorter.
chart :: [(String, Int)]
chart = zip rows [12, 4, 9]

totalSold :: Int
totalSold = sum (map snd chart)

-- The lambda matches its pair instead of reaching for fst and snd.
busiest :: (Int, String)
busiest = maximum (map (\(row, n) -> (n, row)) chart)

banner :: String
banner = bestRow ++ ": " ++ show bestCount ++ " of " ++ show totalSold
  where (bestCount, bestRow) = busiest

Cómo funciona

  1. zip rows [12, 4, 9] arma una lista de pares (String, Int) a partir de dos listas.
  2. map snd chart extrae los conteos, mientras la lambda \(row, n) -> (n, row) da vuelta cada par.
  3. where (bestCount, bestRow) = busiest desestructura al ganador en dos nombres.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
560
Tokens
113
Ritmo de tres estrellas
75 tpm

Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 90 segundos.

Escribe este fragmento

Paso 3 de 3 en Coincidencia de patrones; paso 9 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →