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