typestar

Folds en Haskell

foldr y foldl' colapsan una lista en un solo valor; difieren en la dirección y en cuándo ocurre el trabajo.

module Folds where

-- foldr slots (+) between the elements, starting from the right end
totalRainfall :: [Int] -> Int
totalRainfall = foldr (+) 0

-- foldl' walks left to right and forces each step, so nothing piles up
-- as unevaluated work; base 4.20 exports it straight from the Prelude
runningProduct :: [Int] -> Int
runningProduct = foldl' (*) 1

-- sum and product are these same two folds under friendlier names
matchesPrelude :: [Int] -> Bool
matchesPrelude xs =
  sum xs == totalRainfall xs && product xs == runningProduct xs

-- the result type is free to differ from the element type
summarize :: [Int] -> String
summarize = foldr (\mm acc -> show mm ++ " mm; " ++ acc) "end"

Cómo funciona

  1. totalRainfall = foldr (+) 0 mete (+) entre los elementos, empezando por el extremo derecho.
  2. runningProduct = foldl' (*) 1 va de izquierda a derecha y fuerza cada paso, así no se acumula trabajo sin evaluar.
  3. matchesPrelude los contrasta con sum xs y product xs, mientras summarize pliega la misma [Int] en un String.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
685
Tokens
84
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 72 segundos.

Escribe este fragmento

Paso 2 de 3 en Orden superior; paso 14 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →

Folds en otros lenguajes