Construir listas en Haskell
(:) agrega un elemento al frente, (++) une dos listas enteras y un patrón cubre el caso vacío.
-- (:) prepends one element; (++) joins two whole lists end to end
markers :: [String]
markers = "trailhead" : ("cairn" : ["footbridge"]) ++ ["summit"]
-- head and tail would grab the ends, but they crash on an empty list,
-- and GHC now rejects both under -Wall; match the two cases instead
firstMarker :: [String] -> String
firstMarker [] = "no markers logged yet"
firstMarker (m : _) = m
-- matching (m : rest) names the head and the rest in one pattern
describe :: [String] -> String
describe [] = "nothing to walk yet"
describe (m : rest) = m ++ ", then " ++ show (length rest) ++ " more"
main :: IO ()
main = do
putStrLn (describe markers)
putStrLn (firstMarker markers ++ " -> " ++ unwords (drop 1 markers))
print (null markers, length markers)
Cómo funciona
markersencadena tres nombres con(:)y luego le pega["summit"]al final con(++).firstMarkercubre[]y(m : _)en vez de llamar ahead, que revienta con una lista vacía.describenombra las dos mitades de una vez con(m : rest), ymainreportanull markersylength markers.
Palabras clave y builtins usados aquí
IOString_do
El intento, en números
- Líneas
- 20
- Caracteres a escribir
- 754
- Tokens
- 124
- Ritmo de tres estrellas
- 75 tpm
Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 99 segundos.
Paso 1 de 3 en Listas; paso 10 de 27 en Fundamentos del lenguaje.