Reputation: 11
I am looking for the way to sort [(String,String)]
with regard to the small part of first element of tuple
This problem is similar to Sort list of strings by a part of the string, but in Haskell.
sortBy (compare `on` fst) list
works fine but I need to refine search so the string of format "aa bb cc" would be sorted only with respect to cc part
I tried to do this:
sortBy (compare `on` ((!!2)(splitOn " " (fst)))
Unfortunately it does not work, probably due to my lack of understanding how to nest functions.
Upvotes: 0
Views: 539
Reputation: 2625
Because you have to query the last value in each list for each combination, this solution isn't very efficient at all. But here's at least one way of doing it (feel free to suggest better options, readers!)
import Data.List.Split
import Data.List
sortStrTuples :: [(String,String)] -> [(String,String)]
sortStrTuples = sortBy (compare `on` f)
where f (x,_) = last $ (splitOn " ") x
Basically, we sort the provided list in terms of a processed version of that list. For each pair, we split the string contained in the first value of the tuple on its spaces and select the last element. So given a tuple ("blah1 blah2","blah blah")
, our local function f
returns "blah2". We then rely on built-in string comparison behavior (which matches what we want).
Testing this, we can see it behaves as expected:
ghci>> sortStrTuples [("aa bb cc","blah"),("aa bbb","blah")]
[("aa bbb","blah"),("aa bb cc","blah")]
Upvotes: 1