Reputation: 29772
Today I was trying to deepen my understanding of the IO monad, and I tried to write a function that take an Int
n
and returns an IO Bool
than produces True
n
times, then False
forever afterwards.
trueThenFalse :: Int -> IO Bool
Normally I'd address something like this with recursion, but here there seems to be nothing to recurse into.
How would I go about implementing this function? Is it possible and/or advisable to do so?
Upvotes: 2
Views: 555
Reputation: 198103
It might make more sense as an IO (IO Bool)
, because you have to set up some state first:
trueThenFalse n = do
holder <- newMVar n
return (modifyMVar holder (\ k -> return (k - 1, k > 0)))
That creates a mutable holder to store the count of how many Trues are "left," and returns another IO
operation which can be run multiple times, modifying the count and returning True
if the count was > 0.
Upvotes: 6