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:
We use
Data.Array.sortBy
instead ofslices.SortFunc
. PureScript’ssortBy
takes a comparison function as its first argument.The
lenCmp
function is defined usingcomparing String.length
. This creates a comparison function based on the length of strings.For sorting the
Person
records, we usecomparing _.age
. This creates a comparison function based on theage
field of the records.PureScript doesn’t have a separate
cmp.Compare
function. Instead, thecomparing
function fromData.Ord
is used to create comparison functions.We use
log $ show $
to print the results, as PureScript doesn’t have a direct equivalent to Go’sfmt.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.