简体   繁体   中英

Sort a list of tuples by their second element without higher order functions or recursion

I have a list of (String, Int) pairs and am struggling to figure out how to sort the list by the snd field ( Int ). I am not allowed to use higher order functions or recursion which makes it more difficult.

For example, I have

[("aaaaa", 5),("bghdfe", 6),("dddr",4)] 

and would like to sort it into

 [("dddr",4),("aaaaa", 5),("bghdfe", 6)].

Edit: I understand that the sort may not be possible without higher order functions, what I really need is to find the element with the minimum length (the snd field), so is there a way to find the minimum number and then take the fst field of the list's element at that index? If that way works better I am unsure about how to find the index of that minimum number however.

The task seems to be impossible, since you can't write a sort without recursion in Haskell. This means, you must use sort , which is usually something like sortBy compare and thus you have it.

But if you are allowed to use sort you can do it by first reversing all tuples, sorting the resulting list and reversing the tuples in the result again. This should be possible to do in a few nested list comprehension, so technically no higher order functions are needed.


After you have given more details, I'd do

homework list = snd (minimum [ (s,f) | (f,s) <- list ])

Without higher order functions or recursion all you have left, technically, is list comprehensions. Thus we define

-- sortBy (comparing snd) >>> take 1 >>> listToMaybe >>> fmap fst
--  ~= minimumBy (comparing snd) >>> fst
foo :: Ord b => [(a,b)] -> Maybe a
foo xs = case [ a | (a,b) <- xs
                  , null [ () | (_c,d) <- xs, d < b]]
         of (a:_) -> Just a
            []    -> Nothing

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