List of Haskell Data Types

I have a custom datatype named Student that has labels for 2 items. I have created a function called average that calculates the average of the two. Everyone works great.

My question is, how can I sort the student list by average?

data Student = Student
    {studentName :: String,
     subject1 :: Double,
     subject2 :: Double} deriving (Show)

average :: Student -> Double
average (Student _ sub1 sub2) = (sub1 + sub2) / 2

students :: [Student]
students = [Student "Dave"  50.0  40.0,
            Student "Joe"   65.0  90.0,
            Student "Ann"   75.0  82.0]

      

PS I'm new to Haskell and don't know if the built-in middle function worked out, but I prefer if I can sort my list into similar ones without using the built-in middle function (if any), since this is a small test solution to use with another type of function instead it is average.

+3


source to share


1 answer


import Data.Function (on)
import Data.List (sortBy)

studentsSortedByAverage = sortBy (compare `on` average) students

      

Note that these are backticks around on

, not single quotes.

Here are links to docs for sortBy

and on

.




If you are using an old compiler that does not come with Data.Function

, here is the definition on

:

on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(.*.) `on` f = \x y -> f x .*. f y

      

+6


source







All Articles