Números comenzando con un dígito dado
Definir la función
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,
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
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