Home > Mobile >  Find the max in a list of lists of type Numbers in Haskell
Find the max in a list of lists of type Numbers in Haskell

Time:03-02

I'm pretty new to Haskell and am trying to find the max value in a list of lists that contain type Numbers. Numbers is defined as:

data Numbers = StrNumber String | IntNumber Int
                deriving (Show, Read, Eq)

I already have a function that finds the max int value in a list of lists of type int.

nested_max :: [[Int]] -> Int
nested_max [] = minBound::Int
nested_max list = maxL (map maxL list)
     where
          maxL xs = foldr gt (minBound::Int) xs
          gt x y = if x < y then y else x

And can use getInt to convert Numbers to ints.

getInt x = read x::Int

I've been trying to map getInt to every value in the list being passed in and then applying nested_max on that list, but keep getting errors.
This is what I've been trying:

getInt x = read x::Int
to_int :: [[Numbers]] -> [[Int]]
to_int list = map (\x-> getInt x) list

An example of what the program should do is...
Input: find_max_number [[StrNumber "9",IntNumber 2,IntNumber 8],[StrNumber "4",IntNumber 5],[IntNumber 6,StrNumber "7"],[],[StrNumber "8"]]
Output: 9

CodePudding user response:

The following is my attempt:

data Numbers
  = StrNumber String
  | IntNumber Int

nestedMax :: [[Numbers]] -> Int
nestedMax = maximum' . map maxL
  where maxL = maximum' . map toInt

toInt :: Numbers -> Int
toInt (StrNumber x) = read x
toInt (IntNumber x) = x

maximum' :: (Bounded a, Ord a) => [a] -> a
maximum' l -- maximum but output minBound when []
  | null l    = minBound
  | otherwise = maximum l

main = do
  print $ nestedMax [[StrNumber "9",IntNumber 2,IntNumber 8],[StrNumber "4",IntNumber 5],[IntNumber 6,StrNumber "7"],[],[StrNumber "8"]] -- 9
  print $ nestedMax [] -- -9223372036854775808

I hope the code is straightforward...

  • Related