I would like to handle states in Q monad with Template Haskell.
According to some stack overflow's answers, there is a solution that uses unsafePerformIO
, but I want to avoid using it as long as I can.
I found getQ
and putQ
in the module Language.Haskell.TH.Syntax
. These functions handle states in Q monad shown by template-haskell 2.10 document.
I tried to use this API, but getQ
fails to get states.
Following code is an example of my problem.
I expects x
to be bounded to (Just B)
,but x
is always Nothing
.
-- X.hs
{-# LANGUAGE DeriveDataTypeable #-}
module X where
import Data.Typeable
data T = A | B | C deriving (Typeable,Show)
-- Y.hs
{-# LANGUAGE TemplateHaskell #-}
module Y where
import X
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
-- splice for testing getQ and putQ
do
putQ B
x <- getQ :: Q (Maybe T)
runIO $ print x -- prints Nothing
return []
as a result , I got following compile message.
$ ghc -fforce-recomp Y.hs
[1 of 2] Compiling X ( X.hs, X.o )
[2 of 2] Compiling Y ( Y.hs, Y.o )
Nothing
How to use getQ
and putQ
?
There's currently a bug in getQ: it was recently fixed and should be working in the next version of GHC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With