Exercise solution: Keeping state

Exercise

Write a server using ioServer, newCounter, and incrementCounter. The server should respond with a number that increases by one with each request.

type Counter = TVar Natural

newCounter :: IO Counter
newCounter =
    newTVarIO 0

incrementCounter :: Counter -> IO Natural
incrementCounter counter =
    atomically $
      do
        x <- readTVar counter
        let x' = x + 1
        writeTVar counter x'
        return x'

counterServer :: IO ()
counterServer = _

Solution

Sign up for access to the full page, plus the complete archive and all the latest content.