Home > Blockchain >  Finding max of a list of Maybe values in Haskell using Higher Order Functions
Finding max of a list of Maybe values in Haskell using Higher Order Functions

Time:02-28

I am trying to use higher level order functions to take a list of Maybe values and return a max of type int but for some reason I can only return a Maybe value. For example this works:

max' iL = foldl maxMaybe Nothing iL
maxMaybe Nothing  y = Just y 
maxMaybe (Just x) y = Just (max x y)

However this doesn't as it says it still expects a Maybe value but it is generating an int for a result:

max' iL = foldl maxMaybe (minBound::Int) iL
maxMaybe Nothing  y = y 
maxMaybe (Just x) y = (max x y) 

CodePudding user response:

For the second implementation you use wrong type for accumulator, because the foldl's accumulator is the first argument of its function - here is maxMaybe function-, we have to swap arguments in maxMaybe:

max' :: Foldable t => t (Maybe Int) -> Int
max' = foldl maxMaybe (minBound::Int)

maxMaybe :: Ord a => a -> Maybe a -> a
maxMaybe y Nothing = y
maxMaybe y (Just x) = max x y

this function now works, but I think this method is not good way for finding the max value and I prefer the first implementation, because you can do pattern matching on result of it.

I suggest to change the first implementation to this one, becauseas foldlr is preferable for haskell foldr and Just (Just a) is redundant and ugly:

maxWithFoldlr = (Foldable t, Ord a) => t (Maybe a) -> Maybe a
maxWithFoldlr = foldlr maxMaybe Nothing

maxWithFoldl :: (Foldable t, Ord a) => t (Maybe a) -> Maybe a
maxWithFoldl = foldl maxMaybe Nothing

maxMaybe :: Ord a => Maybe a -> Maybe a -> Maybe a
maxMaybe Nothing  y = y 
maxMaybe x Nothing  = x
maxMaybe (Just x) (Just y) = Just $ max x y
  • Related