Sorting By Functions in PureScript

Our example demonstrates how to implement custom sorting in PureScript. We’ll sort strings by their length and custom objects by a specific field.

module Main where

import Prelude

import Data.Array (sort, sortBy)
import Data.Ord (comparing)
import Effect (Effect)
import Effect.Console (log)

main :: Effect Unit
main = do
  let fruits = ["peach", "banana", "kiwi"]

  -- We implement a comparison function for string lengths.
  let lenCmp = comparing String.length

  -- Now we can use `sortBy` with this custom comparison function
  -- to sort `fruits` by name length.
  log $ show $ sortBy lenCmp fruits

  -- We can use the same technique to sort an array of
  -- values that aren't built-in types.
  type Person = { name :: String, age :: Int }

  let people = [
    { name: "Jax", age: 37 },
    { name: "TJ", age: 25 },
    { name: "Alex", age: 72 }
  ]

  -- Sort `people` by age using `sortBy`.
  log $ show $ sortBy (comparing _.age) people

In this PureScript version:

  1. We use Data.Array.sortBy instead of slices.SortFunc. PureScript’s sortBy takes a comparison function as its first argument.

  2. The lenCmp function is defined using comparing String.length. This creates a comparison function based on the length of strings.

  3. For sorting the Person records, we use comparing _.age. This creates a comparison function based on the age field of the records.

  4. PureScript doesn’t have a separate cmp.Compare function. Instead, the comparing function from Data.Ord is used to create comparison functions.

  5. We use log $ show $ to print the results, as PureScript doesn’t have a direct equivalent to Go’s fmt.Println for complex types.

To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js:

$ spago build
$ node -e "require('./output/Main').main()"
["kiwi","peach","banana"]
[{"name":"TJ","age":25},{"name":"Jax","age":37},{"name":"Alex","age":72}]

This example demonstrates how PureScript’s powerful type system and functional programming features can be used to implement custom sorting logic in a concise and type-safe manner.