Select in PureScript
Our example demonstrates how to use channels and concurrency in PureScript. We’ll create two channels and select from them as they receive values.
In this example, we’re simulating channels using functions that return values after a delay. The simulateChannel
function takes a message and a delay in milliseconds, and returns the message after the specified delay.
We create two “channels”, c1
and c2
, which will return their values after 1 and 2 seconds respectively.
To simulate selecting from multiple channels, we use the parallel
function from Control.Parallel
. The <|>
operator is used to race the parallel computations against each other, similar to how select
works in other languages.
We run this twice to get both results, simulating a loop that selects from the channels multiple times.
To run this program, you would typically use the PureScript compiler (purs
) to compile it, and then execute it with Node.js:
Note that the total execution time is only about 2 seconds since both the 1 and 2 second delays execute concurrently.
This example demonstrates how to work with asynchronous operations and select from multiple concurrent computations in PureScript, providing similar functionality to channels and select statements in other languages.