你可以帮我解决这个问题。我想提取导师,这是导演的最后一个元素 每个元组并使用它来对整个列表进行排序。
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 ]
当我使用上面的方法时,它只返回排序的导师列表。我可以改变什么,以便它返回根据导师姓名排序的整个列表?
答案 0 :(得分:1)
您可以尝试sortBy
中的Data.List
:
sortBy (\(_,_,_,_,t1) (_,_,_,_,t) -> compare t1 t) l
答案 1 :(得分: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
非常易读。