tonto
tonto

Reputation: 33

Extract an element from a list and use it to sort the entire list

Can u help me with this code .i want to extract the tutor which is the last element in the each tuple and use it to sort the entire list.

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 ]

when i use the above method ,it only returns the sorted list of tutors .what can i change so that it returns the whole list sorted according to the tutor name?

Upvotes: 0

Views: 95

Answers (2)

R&#252;diger Hanke
R&#252;diger Hanke

Reputation: 6255

What Ankur said, use sortBy. Here is a slightly different way of writing this sort:

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

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

This is useful if you have accessor functions that extract the fields from the tuples, e.g. for tutor:

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

Then you can simply reuse them:

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

which is very readable.

Upvotes: 1

Ankur
Ankur

Reputation: 33637

You can try sortBy from Data.List:

sortBy (\(_,_,_,_,t1) (_,_,_,_,t) -> compare t1 t) l

Upvotes: 1

Related Questions