Sorting By Functions in Idris
Our example demonstrates how to implement custom sorting in Idris. We’ll sort strings by their length and a custom data type by one of its fields.
In this Idris code:
We import necessary modules:
Data.List
for sorting functions andData.String
for string operations.We define a custom
Person
data type with a name (String) and an age (Int).We implement
lenCmp
, a comparison function for string lengths. This uses the built-incompare
function.We implement
ageCmp
, a comparison function forPerson
objects based on their age.In the
main
function:- We create a list of fruits and sort it using
sortBy lenCmp
. - We create a list of
Person
objects and sort it usingsortBy ageCmp
.
- We create a list of fruits and sort it using
We use
putStrLn $ show ...
to print the sorted lists.
Note that Idris uses sortBy
from Data.List
instead of slices.SortFunc
. The sortBy
function takes a comparison function and a list, and returns a sorted list.
To run this program, save it as CustomSorting.idr
and use the Idris compiler:
This example demonstrates how to implement custom sorting logic in Idris, which can be applied to both built-in types like String and custom data types like Person.