Menu Close

Operación sobre todos los pares

Definir la función

   todosPares :: (a -> b -> c) -> [a] -> [b] -> [c]

tal que (todosPares f xs ys) es el resultado de aplicar la operación f a todos los pares de xs e ys. Por ejemplo,

   todosPares (*) [2,3,5] [7,11]            == [14,22,21,33,35,55]
   todosPares (\x y -> x:show y) "ab" [7,5] == ["a7","a5","b7","b5"]

Soluciones

-- 1ª definición (por comprensión)
todosPares1 :: (a -> b -> c) -> [a] -> [b] -> [c]
todosPares1 f xs ys = [f x y | x <- xs, y <- ys] 
 
-- 2ª definición (por recursión)
todosPares2 :: (a -> b -> c) -> [a] -> [b] -> [c]
todosPares2 _ []     _  = []
todosPares2 f (x:xs) ys = map (f x) ys ++ todosPares2 f xs ys
 
-- 3ª definición (recursión con auxiliar)
todosPares3 :: (a -> b -> c) -> [a] -> [b] -> [c]
todosPares3 f xs ys = aux xs where
   aux []     = []
   aux (x:xs) = map (f x) ys ++ aux xs
 
-- 4ª definición (recursión con auxiliar)
todosPares4 :: (a -> b -> c) -> [a] -> [b] -> [c]
todosPares4 f xs ys = 
    (foldr (\x zs -> map (f x) ys ++ zs) []) xs
Inicial

2 soluciones de “Operación sobre todos los pares

  1. carruirui3
    todosPares :: (a -> b -> c) -> [a] -> [b] -> [c]
    todosPares f xs ys = map ((x,y) -> f x y) $ cartesiano xs ys
     
    cartesiano :: [a] -> [b] -> [(a,b)]
    cartesiano xs ys = [(x,y) | x <- xs, y <- ys]
  2. fracruzam
    todosPares :: (a -> b -> c) -> [a] -> [b] -> [c]
    todosPares f xs ys = [f x y | x <- xs, y <- ys]

Escribe tu solución

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.