Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use getQ and putQ in template haskell?

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?

like image 508
kiripon Avatar asked Jun 30 '15 16:06

kiripon


1 Answers

There's currently a bug in getQ: it was recently fixed and should be working in the next version of GHC.

like image 94
Jeremy List Avatar answered Nov 03 '22 15:11

Jeremy List