Randi Ratnayake
Randi Ratnayake

Reputation: 684

Haskell List of Data Type Sorting

I got a custom Data type named Student which has marks for 2 subjects. I have created a function named average that calculates the average of two. All work fine.

My question is how can I sort list of students by their 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]

P.S. I am a beginner in Haskell and don't know whether its got a inbuilt average function but I prefer if I can sort my list in similar way without using inbuilt average function (if it is there) as this small test solution to be use with a different type of function instead average.

Upvotes: 3

Views: 1661

Answers (1)

dave4420
dave4420

Reputation: 47052

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

studentsSortedByAverage = sortBy (compare `on` average) students

Note that those are backticks around on, not single quotes.

Here are links to docs for sortBy and on.


If you are using an old compiler that doesn't come with Data.Function, here is the definition of on:

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

Upvotes: 6

Related Questions