Números comenzando con un dígito dado
Definir la función
1 |
comienzanCon :: [Int] -> Int -> [Int] |
tal que (comienzanCon xs d) es la lista de los elementos de xs que empiezan por el dígito d. Por ejemplo,
1 2 3 |
comienzanCon [123,51,11,711,52] 1 == [123,11] comienzanCon [123,51,11,711,52] 5 == [51,52] comienzanCon [123,51,11,711,52] 6 == [] |
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 |
import Data.Char (intToDigit) -- 1ª definición (por comprensión) comienzanCon :: [Int]-> Int -> [Int] comienzanCon xs d = [x | x <- xs, head (show x) == d'] where d' = head (show d) -- 2ª definición (por recursión) comienzanCon2 :: [Int]-> Int -> [Int] comienzanCon2 xs d = aux xs where aux [] = [] aux (x:xs) | head (show x) == d' = x : aux xs | otherwise = aux xs d' = head (show d) -- 3ª definición (por filtrado) comienzanCon3 :: [Int]-> Int -> [Int] comienzanCon3 xs d = filter (\x -> head (show x) == d') xs where d' = head (show d) -- 4ª definición (por plegado) comienzanCon4 :: [Int]-> Int -> [Int] comienzanCon4 xs d = foldr f [] xs where f x ys | head (show x) == d' = x : ys | otherwise = ys d' = head (show d) -- En las definiciones anteriores se puede usa intToDigit en lugar de -- read. comienzanCon' :: [Int]-> Int -> [Int] comienzanCon' xs d = [x | x <- xs, head (show x) == intToDigit d] comienzanCon2' :: [Int]-> Int -> [Int] comienzanCon2' xs d = aux xs where aux [] = [] aux (x:xs) | head (show x) == intToDigit d = x : aux xs | otherwise = aux xs comienzanCon3' :: [Int]-> Int -> [Int] comienzanCon3' xs d = filter ((==intToDigit d) . head . show) xs comienzanCon4' :: [Int]-> Int -> [Int] comienzanCon4' xs d = foldr f [] xs where f x ys | head (show x) == intToDigit d = x : ys | otherwise = ys |
2 Comentarios