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 c
Start with the type of sortBy
:
> :t sortBy
sortBy :: (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 like
type MyType = (String, Int, String, Int, String, Double)
byName :: MyType -> MyType -> Ordering
byName (_, _, _, _, 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.)