Sorting By Functions in Haskell

Occasionally, we might want to sort a collection by something other than its natural order. For instance, if we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Haskell.

import Data.List (sortBy)
import Data.Ord (comparing)

main :: IO ()
main = do
    let fruits = ["peach", "banana", "kiwi"]

    -- We implement a comparison function for string lengths.
    let lenCmp a b = compare (length a) (length b)

    -- Now we can use sortBy with this custom comparison function
    -- to sort fruits by name length.
    let sortedFruits = sortBy lenCmp fruits
    print sortedFruits

    -- We can use the same technique to sort a list of
    -- values that aren't built-in types.
    data Person = Person { name :: String, age :: Int } deriving (Show)

    let people = [ Person "Jax" 37
                 , Person "TJ" 25
                 , Person "Alex" 72
                 ]

    -- Sort people by age using sortBy.
    let sortedPeople = sortBy (comparing age) people
    print sortedPeople

In this Haskell version:

  1. We use Data.List.sortBy to perform custom sorts. This function takes a comparison function and a list as arguments.

  2. For sorting strings by length, we define lenCmp which compares the lengths of two strings.

  3. For sorting custom types like Person, we use Data.Ord.comparing which creates a comparison function based on a key function (in this case, age).

  4. Haskell’s type system ensures that our sorting functions are type-safe at compile time.

To run the program, save it as sorting_by_functions.hs and use runhaskell:

$ runhaskell sorting_by_functions.hs
["kiwi","peach","banana"]
[Person {name = "TJ", age = 25},Person {name = "Jax", age = 37},Person {name = "Alex", age = 72}]

This example demonstrates how Haskell’s powerful type system and functional programming features make it easy to implement custom sorting logic for various data types.