Haskell - function that sorts list with strings by integer value

Viewed 67

Below is my current code that sorts a list in acesending order:

qsort::[Int]->[Int]
qsort[]=[]
qsort(x:xs)
 =qsort[y|y<-xs, y<=x]++[x]++qsort[y|y<-xs,y>x]

How would i modify/create a function that sorts a list such as:

[("Bob",22),("Peter",38),("Charlie",19)]

by the int value

3 Answers

You can unpack the items in 2-tuples:

qsort::[Int] -> [Int]
qsort [] = []
qsort(x@(_,vx):xs) = qsort [ y | y@(_, vy) <-xs, … ] ++ [x] ++ qsort [ y | y@(_, vy) <- xs, … ]

Here you still need to fill in the parts. The vx is the value of x, and vy is the value of the elements y. You thus will need to make comparisons between vx and vy.

Here's a possible strategy. First, define a custom "less than or equal to" operator

lte :: (String, Int) -> (String, Int) -> Bool
lte (str1, int1) (str2, int2) = ...

Then, adapt your qsort implementation replacing each use of <= with a call to lte, and each use of > with the negation of a call to lte.

for ascending

test = sortBy (compare `on` snd) [("Bob",22),("Peter",38),("Charlie",19)]

for descending

test = sortBy (flip compare `on` snd) [("Bob",22),("Peter",38),("Charlie",19)]

alternatively descending,

import Data.Function (on)
import Data.Ord (Down(Down))

test = sortOn Down [("Bob",22),("Peter",38),("Charlie",19)]
Related