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
totalRainfall = foldr (+) 0mete(+)entre los elementos, empezando por el extremo derecho.runningProduct = foldl' (*) 1va de izquierda a derecha y fuerza cada paso, así no se acumula trabajo sin evaluar.matchesPreludelos contrasta consum xsyproduct xs, mientrassummarizepliega la misma[Int]en unString.
Palabras clave y builtins usados aquí
BoolIntStringmodulewhere
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.
Paso 2 de 3 en Orden superior; paso 14 de 27 en Fundamentos del lenguaje.