dabean
dabean

Reputation: 45

Find the max in a list of lists of type Numbers in Haskell

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

Upvotes: 1

Views: 129

Answers (1)

j1-lee
j1-lee

Reputation: 13939

The following is my attempt:

data Numbers
  = StrNumber String
  | IntNumber Int

nestedMax :: [[Numbers]] -> Int
nestedMax = maximum . map toInt . concat
  where toInt (StrNumber x) = read x
        toInt (IntNumber x) = x

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

I hope the code is straightforward...

Upvotes: 2

Related Questions