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:

  1. We import the necessary modules: Html for rendering, and List for the sortWith function.

  2. The main function combines the results of sortFruits and sortPeople.

  3. In sortFruits, we define a list of fruits and a comparison function lenCmp that compares string lengths. We then use List.sortWith to sort the fruits based on this comparison.

  4. For sorting custom types, we define a Person type alias with name and age fields.

  5. In sortPeople, we create a list of Person records and sort them by age using List.sortWith with an inline comparison function.

  6. 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.