In-class-4

Class: CSCE-314

-- 1) Remove duplicates while preserving order
uniqueScores :: [Int] -> [Int]
uniqueScores [] = []    -- Base case
uniqueScores (x:xs) = x : uniqueScores (filter(/=x) xs)
    -- Filtering x out when recursing
    -- '/=x' means "different to x"
    -- ':' is the list cons operator
        -- in this case: prepends a single element to an existing list

-- 2) Average score (return 0 for empty list)
average :: [Int] -> Double
average [] = 0          -- Base case (return 0 if no elements remain)
average xs = fromIntegral (sum xs) / fromIntegral (length xs)
    -- 'length' gets the number of elements of list 'xs'
    -- 'sum' gets the total sum of the list 'xs'
    -- 'fromIntegral' converts both to Double

-- 3) Filter passing scores (>= 70)
passing :: [Int] -> [Int]
passing = filter (>= 70)

-- 4) Grade distribution (uses the previous code toGrade)
toGrade :: Int  -> Char   -- done in class
toGrade n
    | n > 90 = 'A'
    | n > 80 = 'B'
    | n > 70 = 'C'
    | n > 60 = 'D'
    | otherwise = 'F'

gradeDist :: [Int] -> [Char]
gradeDist = map toGrade

-- Data
scores :: [Int]
scores = [95, 82, 100, 67, 82, 95, 74, 88, 100, 67]

-- Main function to test all functions
main :: IO ()
main = do
    -- Print requested output
    putStrLn $ "average scores      == " ++ show (average scores)
    putStrLn $ "average []          == " ++ show (average [])
    putStrLn $ "passing scores      == " ++ show (passing scores)
    putStrLn $ "gradeDist [95,82,67] == " ++ show (gradeDist [95,82,67])