Home > OS >  maxTwo Implementation Haskell
maxTwo Implementation Haskell

Time:03-03

Given a list of integers xs, find the two largest values and return them in a pair (largest first). Largest duplicates should be preserved (included) in the output. Do not modify the original list.

This is what I came up with but it did not quite give the correct answer. Here is the code and the second section is the terminal run:

minInt = minBound :: Int

maxTwoHelper1 :: [Int] -> (Int, Int)
maxTwoHelper1 (x : xs) = maxTwoHelper2 minInt minInt xs

maxTwoHelper2 :: Int -> Int -> [Int] -> (Int, Int)
maxTwoHelper2 first second [] = (first, second)
maxTwoHelper2 first second (x : xs)
  | x >= first = maxTwoHelper2 x second xs
  | x >= second = maxTwoHelper2 first x xs
  | otherwise = maxTwoHelper2 first second xs
*Main> maxTwoHelper1 [1,0,-1]
(0,-1)

CodePudding user response:

Your maxTwoHelper1 is dropping the x, it should consider all elements, so:

maxTwoHelper1 :: [Int] -> (Int, Int)
maxTwoHelper1 xs = maxTwoHelper2 minBound minBound xs

Your maxTwoHelper2 also contains an error: in case x >= first, x is the largest, and first the second largest, so:

maxTwoHelper2 :: Int -> Int -> [Int] -> (Int, Int)
maxTwoHelper2 first second [] = (first, second)
maxTwoHelper2 first second (x : xs)
  | x >= first = maxTwoHelper2 x first xs  --            
  • Related