简体   繁体   中英

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]

PS 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM