I am trying to sort my list of tuples based on the 4th element in each of the tuples. The fourth element contains a string that is a person's name. I want to put tuples that contain the same name next to each other. An example of the lists of tuples before it is sorted is:[("A",100,"Q",3,"Todd",2.0), ("B",203,"R",3,"Rachel",1.66), ("B",273,"F",1,"Mike",2.66), ("A",200,"P",1,"Rachel",0.0), ("A",549,"D",3,"Todd",2.0), ("B",220,"S",3,"Todd",4.0), ("B",101,"M",3,"Jon",3.33), ("A",999,"N",3,"Rachel",1.33)]I want it too look like:[("A",100,"Q",3,"Todd",2.0), ("A",549,"D",3,"Todd",2.0), ("B",220,"S",3,"Todd",4.0), ("B",203,"R",3,"Rachel",1.66), ("A",200,"P",1,"Rachel",0.0), ("A",999,"N",3,"Rachel",1.33), ("B",273,"F",1,"Mike",2.66), ("B",101,"M",3,"Jon",3.33)]What I need is for all the tuples that contain Todd to be next to each other and so on for each name. The order the names show up doesn't matter, just that they are next to each other.sortedList= show . sortBy byName . (map stringToTuple) . (map words) . linesThis is the line of code I am calling sort by in. I understand I need to make a function byName that will somehow figure out if the tuples share a common name.Any help to steer me into the right direction for writing the byName method would be appreciated.Thank you 解决方案 Start with the type of sortBy:> :t sortBysortBy :: (a -> a -> Ordering) -> [a] -> [a]This means byName needs to have type a -> a -> Ordering. In this case, a is a tuple whose fifth element as type String; byName will ignore the other fields. So you'll need to define a function liketype MyType = (String, Int, String, Int, String, Double)byName :: MyType -> MyType -> OrderingbyName (_, _, _, _, a, _) (_, _, _, _, b, _) = ...I leave replacing the ... with the correct expression as an exercise.(Recall that Ordering is a type with three values, LT, EQ, and GT, where byName a b == LT if a < b, byName a b == EQ if a == b, and byName a b == GT if a > b. In your case, two tuples will compare as equal as long as they have the same name. It sounds like you don't actually care whether byName returns LT or GT otherwise.) 这篇关于使用sortBy对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-06 06:42