0

你能帮我处理这段代码吗?我想提取每个元组中最后一个元素的导师,并用它来对整个列表进行排序。

import Data.List

type CourseData = [(String,String,String,String,String)]
l :: CourseData

--list contains name of student, year, programme and personal tutor
l = [("fondi","201202378","2012","Bsc280"," tautology"),
     ("fondi","201202378","2012","Bsc280"," tautology"),
     ("Sylvee","200801245","2008","Bsc209","puma"),
     ("dijeje","201307845","2013","Bsc205","tautology"),
     ("heron","201002567","2010","Bsc280","setlhako"),
     ("slow","201198746","2011","Bsc205"," mampu"),
     ("Sylvee","201198746","2008","bsc209"," puma"),
     ("Sylvee","201198746","2008","bsc209"," puma")]




sortByTutor :: CourseData ->String -> [String]
sortByTutor list  =sort[tutor|(name,id,year,prog,tutor)<-list ]

当我使用上述方法时,它只返回排序的导师列表。我可以改变什么以便它返回根据导师姓名排序的整个列表?

4

2 回答 2

1

Ankur 所说的,使用sortBy. 这是一种稍微不同的编写方式:

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

sortByTutor xs = sortBy (compare `on` \(_,_,_,_,t) -> t) xs

如果您有从元组中提取字段的访问器函数,这很有用,例如,对于导师:

tutor (_,_,_,_,t) = t

然后你可以简单地重用它们:

sortByTutor xs = sortBy (compare `on` tutor) xs

这是非常可读的。

于 2013-11-15T11:26:55.507 回答
1

您可以尝试sortByData.List

sortBy (\(_,_,_,_,t1) (_,_,_,_,t) -> compare t1 t) l
于 2013-11-15T07:57:20.657 回答