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:
Htmlfor rendering, andListfor thesortWithfunction.The
mainfunction combines the results ofsortFruitsandsortPeople.In
sortFruits, we define a list of fruits and a comparison functionlenCmpthat compares string lengths. We then useList.sortWithto sort the fruits based on this comparison.For sorting custom types, we define a
Persontype alias withnameandagefields.In
sortPeople, we create a list ofPersonrecords and sort them by age usingList.sortWithwith an inline comparison function.The results are converted to strings using
Debug.toStringfor 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.