Haskell Project: Gradebook
A gradebook project stores each student name with a score and reports facts about the class. This project builds the report from the list helpers learned so far.
A report sorted by score
sortOn snd orders the student pairs by score. Fay with 25 comes first, and Ana with 100 comes last.
import Data.List (sortOn)
students :: [(String, Double)]
students = [("Ana", 100), ("Ben", 96), ("Cid", 94), ("Dee", 90), ("Eli", 84), ("Fay", 25)]
main :: IO ()
main = print (sortOn snd students)The class average
map pulls out the scores and foldl adds them up. The total divided by 6 students gives the average.
students :: [(String, Double)]
students = [("Ana", 100), ("Ben", 96), ("Cid", 94), ("Dee", 90), ("Eli", 84), ("Fay", 25)]
main :: IO ()
main = print ((foldl (+) 0 (map snd students)) / 6)Pass count and top student
The filter keeps students with a score of 50 or more, and five pass. The last pair in the sorted list is the top student.
import Data.List (sortOn)
students :: [(String, Double)]
students = [("Ana", 100), ("Ben", 96), ("Cid", 94), ("Dee", 90), ("Eli", 84), ("Fay", 25)]
main :: IO ()
main = do
print (length (filter (\s -> snd s >= 50) students))
print (last (sortOn snd students))Example
import Data.List (sortOn)
students :: [(String, Double)]
students = [("Ana", 100), ("Ben", 96), ("Cid", 94), ("Dee", 90), ("Eli", 84), ("Fay", 25)]
main :: IO ()
main = do
print (sortOn snd students)
print ((foldl (+) 0 (map snd students)) / 6)
print (last (sortOn snd students))
print (length (filter (\s -> snd s >= 50) students))Key points
- Data pairs: each student is stored as a pair of a name and a score.
- sortOn snd: sorting the pairs by score puts the lowest score first and the highest last.
- map snd: mapping snd over the pairs pulls out just the scores.
- foldl: folding the scores with + and a start of 0 gives the class total.
- filter: a filter on the pairs keeps only the students at the pass mark or above.
- Average: the total divided by the number of students gives the class average.
In this example, the first action prints the pairs sorted by score, from Fay at 25 up to Ana at 100. The second prints the average, where map takes the scores, foldl adds them to 489, and the sum divided by 6 gives 81.5. The last two actions print the top student and the pass count of 5.
Note
the scores are Double values, so the average can hold a decimal part.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
In this project, what is the class average of the six scores?