简体   繁体   中英

Sorting tuples in haskell lists

I'd like to sort a list of tuples by the third or fourth element (say c or d) in the list of type:

myList = [(a,b,c,d,e)]

I know if the tuple is of type (a,b) I can use the following approach:

mySort xmyList = sortBy (compare `on` snd) x

But the type of sortBy will not work on tuples with length greater than two (so obviously there is no point writing an accessor function for thd or fth ) :

(a -> a -> Ordering) -> [a] -> [a]

But the type of sortBy will not work on tuples with length greater than two

No, it actually works for any list. For instance, if you want to sort on c , just do:

mySort xmyList = sortBy (compare `on` (\(a,b,c,d,e) -> c)) x

or

mySort xmyList = sortBy (comparing thirdOf5) x
   where thirdOf5 (_,_,c,_,_) = c

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