typestar

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

  1. markers encadena tres nombres con (:) y luego le pega ["summit"] al final con (++).
  2. firstMarker cubre [] y (m : _) en vez de llamar a head, que revienta con una lista vacía.
  3. describe nombra las dos mitades de una vez con (m : rest), y main reporta null markers y length markers.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 1 de 3 en Listas; paso 10 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →