Sumas y restas alternativas
Definir la función
1 |
sumasYrestas :: Num a => [a] -> a |
tal que (sumasYrestas xs) es el resultado de alternativamente los elementos de xs. Por ejemplo,
1 2 |
sumasYrestas [3,2,4,1,7] = 3 - 2 + 4 - 1 + 7 = 11 |
Otros ejemplos,
1 2 3 4 |
sumasYrestas [3,2,4] == 5 sumasYrestas [3,2,4,1] == 4 sumasYrestas [3,2,4,1,7] == 11 sumasYrestas (replicate (10^6) 1) == 0 |
Soluciones
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
-- 1ª definición sumasYrestas1 :: Num a => [a] -> a sumasYrestas1 [] = 0 sumasYrestas1 [x] = x sumasYrestas1 (x:y:xs) = x - y + sumasYrestas1 xs -- 2ª definición sumasYrestas2 :: Num a => [a] -> a sumasYrestas2 xs = aux 1 xs where aux _ [] = 0 aux n (y:ys) = n * y + aux (-n) ys -- 3ª definición sumasYrestas3 :: Num a => [a] -> a sumasYrestas3 xs = auxS 0 xs where auxS v [] = v auxS v [x] = v + x auxS v (x:y:xs) = auxS (v+x-y) xs -- 4ª definición sumasYrestas4 :: Num a => [a] -> a sumasYrestas4 xs = sum (zipWith (*) xs [(-1)^n | n <- [0..]]) -- 5ª definición sumasYrestas5 :: Num a => [a] -> a sumasYrestas5 = sum . zipWith (*) (cycle [1,-1]) -- 6ª definición sumasYrestas6 :: Num a => [a] -> a sumasYrestas6 = foldr (-) 0 -- Comparación de eficiencia -- λ> sumasYrestas1 (replicate (10^6) 1) -- 0 -- (1.50 secs, 171,623,648 bytes) -- λ> sumasYrestas2 (replicate (10^6) 1) -- 0 -- (3.78 secs, 382,691,856 bytes) -- λ> sumasYrestas3 (replicate (10^6) 1) -- 0 -- (1.39 secs, 204,404,024 bytes) -- λ> sumasYrestas4 (replicate (10^6) 1) -- 0 -- (16.04 secs, 5,727,351,024 bytes) -- λ> sumasYrestas5 (replicate (10^6) 1) -- 0 -- (1.39 secs, 235,770,344 bytes) -- λ> sumasYrestas6 (replicate (10^6) 1) -- 0 -- (0.53 secs, 142,802,656 bytes) |
8 Comentarios