I need to know the value of the medium in a tuple (Haskell)

0

Hi, I'm doing logic exercises with haskell and I have to extract the value from the middle of a tuple of 3 using the "maximum" and "minimum" functions developed below.

maximo :: (Int,Int)->Int
maximo (x,y) = if x > y then x else y

minimo :: (Int,Int)->Int
minimo (x,y) = if x < y then x else y

med :: (Int,Int,Int)->Int
med (x,y,z) = // funcion med

main = do
print(med(4,3,5))

I've been testing several combinations but there's always at least one case where it fails.

Could someone help me?

Thank you very much

    
asked by Fcr 17.12.2018 в 14:38
source

2 answers

1

I solved it in the following way:

med :: (Int,Int,Int)->Int
med (x,y,z) = maximo(minimo(maximo(x,y), z), minimo(maximo(x,z), y))
    
answered by 17.12.2018 в 16:32
0

First, I would implement the functions maximo and minimo in a way more in keeping with the haskell style:

maximo :: Int -> Int -> Int
maximo x y | x > y     = x
           | otherwise = y

minimo :: Int -> Int -> Int
minimo x y | x < y     = x
           | otherwise = y

To obtain the function med based on these two, we can use the stratagem to calculate the minimum of the possible combinations of pairs and then obtain the maximum of the three minimums, which will be the number of the medium we are looking for:

med :: Int -> Int -> Int -> Int
med x y z = maximo (maximo (minimo x y) (minimo x z)) (minimo y z)

To make it clearer, we can create an auxiliary function that calculates the maximum of three numbers:

max3 :: Int -> Int -> Int -> Int
max3 x y z = maximo (maximo x y) z

med :: Int -> Int -> Int -> Int
med x y z = max3 (minimo x y) (minimo x z) (minimo y z)
    
answered by 19.12.2018 в 03:02