Sorting in PureScript

Our example demonstrates sorting in PureScript using the Data.Array module, which provides functions for working with arrays, including sorting operations.

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
  -- Sorting functions work for any type that implements the Ord typeclass
  let strs = ["c", "a", "b"]
  log $ "Strings: " <> show (sort strs)

  -- An example of sorting Ints
  let ints = [7, 2, 4]
  log $ "Ints:    " <> show (sort ints)

  -- We can also check if an array is already in sorted order
  let isSorted = \arr -> arr == sort arr
  log $ "Sorted:  " <> show (isSorted ints)

To run this program, you would typically use the PureScript compiler (psc) to compile it and then execute it with Node.js:

$ pulp run
Strings: ["a","b","c"]
Ints:    [2,4,7]
Sorted:  true

In this PureScript version:

  1. We import necessary modules, including Data.Array for array operations and sorting.

  2. The sort function from Data.Array is used to sort arrays. It works for any type that implements the Ord typeclass, which includes strings and integers.

  3. We define a simple isSorted function to check if an array is already sorted. It compares the original array with its sorted version.

  4. PureScript uses <> for string concatenation and show to convert values to strings for output.

  5. The Effect monad is used for side effects like console output.

This example demonstrates basic sorting operations in PureScript, which are similar in concept to the original example but use PureScript’s functional programming paradigms and type system.