Line Filters in PureScript

Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. This example writes a capitalized version of all input text. You can use this pattern to write your own PureScript line filters.

module Main where

import Prelude

import Effect (Effect)
import Effect.Console (log, error)
import Node.Process (stdin, stderr)
import Node.Stream (onDataString, onEnd)
import Data.String (toUpper)

main :: Effect Unit
main = do
  -- Create a stream from stdin
  let inputStream = stdin

  -- Listen for data on the input stream
  onDataString inputStream \chunk -> do
    -- Process each line (chunk) as it comes in
    let upperCaseChunk = toUpper chunk
    log upperCaseChunk

  -- Handle the end of the stream
  onEnd inputStream do
    pure unit

  -- Error handling would typically be done here
  -- but PureScript's type system helps prevent many runtime errors

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | spago run
HELLO
FILTER

This PureScript version uses the Node.Stream module to read from stdin line by line. The onDataString function is used to process each chunk of data (which corresponds to a line in this case) as it’s read from the input stream.

The toUpper function from the Data.String module is used to convert each line to uppercase, similar to the strings.ToUpper function in the original Go example.

Error handling in PureScript is typically done through the type system, so we don’t need an explicit error check at the end like in the Go version. However, if you needed to handle specific runtime errors, you could add error handling logic in the onEnd callback or use the onError function from the Node.Stream module.

To run this program, you would typically use the PureScript build tool, spago. The command spago run will compile and run the program.