Suppress runtime error "Bad template not executed for template Data.Maybe.Just b"
I have the following function:
loopMyQ s q m = forever $ do
q' <- atomically $ readTVar q
let Just b = PSQ.findMin q' --irrefutable pattern here in case the queue has just been created
duetime = (PSQ.prio b) + 2.000
now <- getPOSIXTime
when (now > duetime) (transMit2 s now q m)
The problem is that when the PSQ was "just" created as an empty PSQ, "Just" cannot match and gives me an irrefutable runtime template error. This happens exactly once as the queue seems to fill up later and Just b is always the same.
I tried to check if the queue is empty or not and then act on it in my function, but that made everything run twice as slow.
Since it doesn't seem to hurt, can this error be suppressed in some way, e.g. a compiler option or will I need to catch the exception and then ignore it (which could also cost extra time).
source to share
You are probably better off using retry
if the queue is empty: the action STM
won't repeat until the queue is updated in TVar
!
loopMyQ s q m = forever $ do
b <- atomically $ do q' <- readTVar q
case PSQ.findMin q' of
Just b -> return b
Nothing -> retry
let duetime = (PSQ.prio b) + 2.000
now <- getPOSIXTime
when (now > duetime) (transMit2 s now q m)
source to share
Assuming that if your queue is not empty it will never be empty, one thing you could do is make the expensive version (check for non-empty) only until it is empty, then switch to the cheaper version.
loopMyQ s q m = do
q' <- atomically $ readTVar q
case PSQ.findMin q' of
Nothing -> loopMyQ s q m
Just b -> do
body b
forever $ do
q' <- atomically $ readTVar q
let Just b <- PSQ.findMin q'
body b
where body b = do
let duetime = 2 + PSQ.prio b
now <- getPOSIXTime
when (now > duetime) (transMit2 s now q m)
source to share