Range Over Channels in PureScript

Our first example demonstrates how to iterate over values received from a channel. In PureScript, we’ll use the Aff monad for asynchronous operations and the Channel module for channel-like functionality.

module Main where

import Prelude

import Effect (Effect)
import Effect.Console (log)
import Effect.Aff (launchAff_)
import Control.Coroutine (Producer, Consumer, runProcess, ($$))
import Control.Coroutine.Aff (produce, emit)

-- We'll create a producer that emits 2 values.
queueProducer :: Producer String Aff Unit
queueProducer = produce \emitter -> do
  emit emitter "one"
  emit emitter "two"

-- This consumer iterates over each element as it's received from the producer.
-- The iteration terminates after receiving the 2 elements.
consumer :: Consumer String Aff Unit
consumer = do
  elem <- await
  liftEffect $ log elem

main :: Effect Unit
main = launchAff_ $ runProcess (queueProducer $$ consumer)

To run the program, save it as RangeOverChannels.purs and use the PureScript compiler:

$ spago run
one
two

This example demonstrates how to create a producer that emits values and a consumer that processes these values. The runProcess function connects the producer and consumer, allowing data to flow between them.

In PureScript, we use the Aff monad for asynchronous operations and the Control.Coroutine module to create a channel-like system. The produce function creates a producer that emits values, and the consumer function processes these values as they’re received.

This approach provides similar functionality to ranging over channels in other languages, allowing for asynchronous processing of streamed data.