title: Template Haskell: GHC stage restriction and how to overcome
body: <p>I have the following code in a module:</p>
  
  <pre><code>{-# LANGUAGE TemplateHaskell #-}
  
  module Alpha where
  
  import Language.Haskell.TH
  import Data.List
  
  data Alpha = Alpha { name :: String, value :: Int } deriving (Show)
  findName n = find ((== n) . name)
  
  findx obj = sequence [valD pat bod []]
      where
          nam = name obj
          pat = varP (mkName $ "find" ++ nam)
          bod = normalB [| findName nam |]
  </code></pre>
  
  <p>And then I have the following in the main file:</p>
  
  <pre><code>{-# LANGUAGE TemplateHaskell #-}
  
  import Alpha
  
  one   = Alpha "One" 1
  two   = Alpha "Two" 2
  three = Alpha "Three" 3
  xs    = [one, two , three]
  
  findOne = findName "One"
  findTwo = findName "Two"
  
  $(findx three) -- This Fails
  $(findx (Alpha "Four" 4)) -- This Works
  
  main = putStrLn "Done"
  </code></pre>
  
  <p>I'd like the <code>$(findx three)</code> to create <code>findThree = findName "Three"</code> for me. But instead, I get this error:</p>
  
  <pre><code>GHC stage restriction: `three'
    is used in a top-level splice or annotation,
    and must be imported, not defined locally
  In the first argument of `findx', namely `three'
  In the expression: findx three
  </code></pre>
  
  <p>How do I overcome this? I would rather not have to define <code>one</code>, <code>two</code>, etc. in a separate file.</p>
  
  <p>Second question is why does <code>$(findx (Alpha "Four" 4))</code> work without problems?</p>