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) peopleIn this PureScript version:
We use
Data.Array.sortByinstead ofslices.SortFunc. PureScript’ssortBytakes a comparison function as its first argument.The
lenCmpfunction is defined usingcomparing String.length. This creates a comparison function based on the length of strings.For sorting the
Personrecords, we usecomparing _.age. This creates a comparison function based on theagefield of the records.PureScript doesn’t have a separate
cmp.Comparefunction. Instead, thecomparingfunction fromData.Ordis used to create comparison functions.We use
log $ show $to print the results, as PureScript doesn’t have a direct equivalent to Go’sfmt.Printlnfor 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.