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.
In this Haskell version:
We use
Data.List.sortBy
to perform custom sorts. This function takes a comparison function and a list as arguments.For sorting strings by length, we define
lenCmp
which compares the lengths of two strings.For sorting custom types like
Person
, we useData.Ord.comparing
which creates a comparison function based on a key function (in this case,age
).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
:
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.