yusuf
yusuf

Reputation: 3781

minBound and MaxBound in haskell

I have the following code:

minmax1, minmax2, minmax3 :: [Int] -> (Int, Int)
minBound :: Int = -9223372036854775808
maxBound :: Int = 9223372036854775807
minmax1 arr = (minimum(arr), maximum(arr))

main = do
    let list1 = [1, 2, 3]
    let list2 = [1, 9, 3]
    let list3 = [3, 2, 1, 0]
    let list4 = [100]
    let list5 = []
    putStrLn $ show list1 ++ " -> " ++ show (minmax1 list1)
    putStrLn $ show list2 ++ " -> " ++ show (minmax1 list2)
    putStrLn $ show list3 ++ " -> " ++ show (minmax1 list3)
    putStrLn $ show list4 ++ " -> " ++ show (minmax1 list4)
    putStrLn $ show list5 ++ " -> " ++ show (minmax1 list5)

in order to obtain the following results:

--   minmax1 [1,2,3] = (1,3)
--   minmax1 [1,9,3] = (1,9)
--   minmax1 [3,2,1,0] = (0,3)
--   minmax1 [100]   = (100,100)
--   minmax1 [] = (9223372036854775807,-9223372036854775808)

If the array is not empty, it is easy to get the values above. But when the input to minmax1 is an empty array, how should I modify my code to obtain the value above?

Upvotes: 3

Views: 3719

Answers (3)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

As an alternative, consider a single fold over the list instead of two separate passes:

minmax1 = foldl' (\(a,b) c -> (min a c,max b c)) (maxBound,minBound)

And as an example use:

> minmax1 [1,5893549,192,55] :: (Int,Int)
(1,5893549)

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476604

You can simply use a check for an empty list:

minmax1 [] = (maxBound,minBound)
minmax1 arr = (minimum arr, maximum arr)

Note that you do not have to define minBound and maxBound yourself: Int is an instance of Bounded and thus has such bounds:

Prelude> maxBound :: Int
9223372036854775807
Prelude> minBound :: Int
-9223372036854775808

Upvotes: 7

bwroga
bwroga

Reputation: 5459

You can pattern match on the list to see if it is empty or not:

minmax1 :: [Int] -> (Int, Int)
minmax1 [] = (maxBound,minBound)
minmax1 arr = (minimum(arr), maximum(arr))

If the list is empty, the first equation will be used. If the list is not empty, the first equation is ignored and the second one will be used.

Upvotes: 3

Related Questions