Tickers in PureScript
PureScript uses the Effect
monad to handle side effects like timers and console output. We’ll use the purescript-effect
and purescript-console
libraries for this example.
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Effect.Timer (setInterval, clearInterval)
import Effect.Aff (launchAff_, delay)
import Effect.Aff.AVar (AVar, newEmptyAVar, putVar, takeVar)
import Effect.Class (liftEffect)
import Data.Time.Duration (Milliseconds(..))
main :: Effect Unit
main = do
-- Tickers in PureScript can be implemented using `setInterval`.
-- We'll create a ticker that fires every 500ms.
timerRef <- setInterval 500 $ do
now <- liftEffect $ log "Tick"
-- We'll use an AVar as a synchronization mechanism
done <- newEmptyAVar
-- This is similar to launching a goroutine
launchAff_ do
-- Wait for 1600ms
delay (Milliseconds 1600.0)
-- Stop the ticker
liftEffect $ clearInterval timerRef
-- Signal that we're done
putVar done unit
-- Wait for the "done" signal
launchAff_ do
_ <- takeVar done
liftEffect $ log "Ticker stopped"
When we run this program, the ticker should tick 3 times before we stop it.
To run this program, you would typically use the PureScript compiler (psc
) to compile it, and then execute the resulting JavaScript with Node.js. The output would look something like this:
$ spago run
Tick
Tick
Tick
Ticker stopped
In this PureScript version:
We use
setInterval
to create a recurring timer that logs “Tick” every 500 milliseconds.We use the
Effect
monad to handle side effects like logging and timer operations.The
launchAff_
function is used to start asynchronous computations, similar to launching goroutines in Go.We use an
AVar
(asynchronous variable) as a simple synchronization mechanism, similar to the channel in the Go example.After 1600 milliseconds, we clear the interval (stopping the ticker) and signal completion using the
AVar
.The main thread waits for the “done” signal before logging “Ticker stopped”.
This example demonstrates how to work with timers and asynchronous operations in PureScript, providing functionality similar to the original Go example.