Máximo de una función
Enunciado
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
-- Se considera la siguiente función -- g :: Integer -> Integer -- g n = if n < 10 then n*n else n -- -- Definir la función -- max_g :: Integer -> Integer -- tal que (max_g n) es el punto i del intervalo [0,n] donde g alcanza -- el máximo de sus valores, si n es positivo y 0 en caso contrario. Por -- ejemplo, -- max_g (-7) == 0 -- max_g 7 == 7 -- max_g 14 == 9 -- max_g 84 == 84 -- -- Comprobar con QuickCheck que la función max_g es equivalente a la -- función f definida por -- f :: Integer -> Integer -- f n | n < 0 = 0 -- | n >= 10 && n < 81 = 9 -- | otherwise = n -- -- Nota: Se piden dos definiciones de max_g, una por comprensión y otra -- por recursión. |
Soluciones
Haskell
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 |
import Test.QuickCheck g :: Integer -> Integer g n = if n < 10 then n*n else n -- 1ª definición (por comprensión): max_gC :: Integer -> Integer max_gC n | n < 0 = 0 | otherwise = snd (maximum [(g i,i) | i <- [0..n]]) -- 2ª definición (por recursión): max_gR :: Integer -> Integer max_gR n | n < 0 = 0 | g m > g n = m | otherwise = n where m = max_gR (n - 1) f :: Integer -> Integer f n | n < 0 = 0 | n >= 10 && n < 81 = 9 | otherwise = n -- La propiedad con max_gR es prop_max_gR n = max_gR n == f n -- La comprobación es -- ghci> quickCheck prop_max_gR -- +++ OK, passed 100 tests. -- La propiedad con max_gC es prop_max_gC n = max_gC n == f n -- La comprobación es -- ghci> quickCheck prop_max_gC -- +++ OK, passed 100 tests. |