Tickers in Haskell
Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.
When we run this program the ticker should tick 3 times before we stop it.
In this Haskell version, we use forkIO
to create a new thread that simulates the ticker. We use threadDelay
to pause the execution for a specified amount of time, similar to time.Sleep
in Go.
The newTicker
function returns a pair of IO actions: one to start the ticker thread and another to stop it. This is similar to how Go’s time.NewTicker
returns a Ticker
struct with a Stop
method.
We use getCurrentTime
from the Data.Time.Clock
module to get the current time, which we print with each tick.
The MVar
type is used to communicate between threads and to signal when the ticker should stop, similar to how channels are used in the Go version.
Note that Haskell doesn’t have a direct equivalent to Go’s select
statement. In this example, we’ve structured the code differently to achieve similar behavior.