Home > Blockchain >  Alternative for using groupBy in sorting function in haskell
Alternative for using groupBy in sorting function in haskell

Time:11-23

I want to implement a sorting function that will sort the elements in a list of strings and will remove all duplicates.

I've already wrote a function that works perfectly:

import Data.List(sortBy, sort, groupBy)

cData :: [String]
cData = ["Blue", "Red", "Yellow",
           "Blue", "Yellow", "Blue",
           "Yellow", "Red", "Blue"]

uniqueColours :: (Ord a) => [a] -> [a]
uniqueColours xs = map head (groupBy (==)(sort xs))


uniqueColours cData = ["Blue","Red","Yellow"]

Now my question. How do I implement the same functionality without "groupBy" and using only "sort" and "sortBy" that will also give me the same output? Is it possible? It's not about efficiency here, I want to understand "sortBy" which I don't seem to implement right.

CodePudding user response:

Recursion on lists lets you easily consider the first two elements of a list and the tail. You then just need to figure out what to do in each case. In the event of an empty list or a list with a single element, the answer is obvious: that list already is "unique."

If the list has at least two elements, what do you do if the first two elements are the same? What do you do if they're not?

unique :: Eq a => [a] -> [a]
unique [] = []
unique [x] = [x]
unique (a:tl@(b:_)) 
  | a == b = ...
  | otherwise = ...
  • Related