[英]Haskell List of Data Type Sorting
I got a custom Data type named Student which has marks for 2 subjects. 我有一个名为Student的自定义数据类型,它有2个主题的标记。 I have created a function named average that calculates the average of two. 我创建了一个名为average的函数来计算两个函数的平均值。 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. PS我是Haskell的初学者,不知道它是否具有内置的平均功能但是我更喜欢如果我能以类似的方式对我的列表进行排序而不使用内置的平均功能(如果它在那里)作为这个小的测试解决方案使用用不同类型的函数代替平均值。
import Data.Function (on)
import Data.List (sortBy)
studentsSortedByAverage = sortBy (compare `on` average) students
Note that those are backticks around on
, not single quotes. 请注意,这些都是反引号周围on
,而不是单引号。
Here are links to docs for sortBy
and on
. 以下是sortBy
和on
文档的链接。
If you are using an old compiler that doesn't come with Data.Function
, here is the definition of on
: 如果您使用的是未附带Data.Function
的旧编译器,则以下是on
的定义:
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(.*.) `on` f = \x y -> f x .*. f y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.