Sorting By Functions in Elm
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Elm.
import Html exposing (Html, div, text)
import List exposing (sortWith)
main : Html msg
main =
div []
[ sortFruits
, sortPeople
]
sortFruits : Html msg
sortFruits =
let
fruits = ["peach", "banana", "kiwi"]
-- We implement a comparison function for string lengths
lenCmp a b =
compare (String.length a) (String.length b)
-- Now we can call List.sortWith with this custom comparison function
-- to sort fruits by name length
sortedFruits =
sortWith lenCmp fruits
in
div [] [ text (Debug.toString sortedFruits) ]
-- We can use the same technique to sort a list of values that aren't built-in types
type alias Person =
{ name : String
, age : Int
}
sortPeople : Html msg
sortPeople =
let
people =
[ Person "Jax" 37
, Person "TJ" 25
, Person "Alex" 72
]
-- Sort people by age using List.sortWith
sortedPeople =
sortWith (\a b -> compare a.age b.age) people
in
div [] [ text (Debug.toString sortedPeople) ]
In this Elm code:
We import the necessary modules:
Html
for rendering, andList
for thesortWith
function.The
main
function combines the results ofsortFruits
andsortPeople
.In
sortFruits
, we define a list of fruits and a comparison functionlenCmp
that compares string lengths. We then useList.sortWith
to sort the fruits based on this comparison.For sorting custom types, we define a
Person
type alias withname
andage
fields.In
sortPeople
, we create a list ofPerson
records and sort them by age usingList.sortWith
with an inline comparison function.The results are converted to strings using
Debug.toString
for display purposes.
To run this Elm program, you would typically compile it to JavaScript and run it in a web browser. The output would show the sorted lists of fruits and people.
Note: Elm’s type system and functional nature lead to a somewhat different structure compared to imperative languages, but the core concept of custom sorting is preserved.