我在模块中有以下代码:
{-# 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 |]
然后我在主文件中有以下内容:
{-# 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"
我想为我$(findx three)
创造findThree = findName "Three"
。但相反,我收到了这个错误:
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
我该如何克服呢?我宁愿不必在单独的文件中定义one
,等。two
第二个问题是为什么$(findx (Alpha "Four" 4))
工作没有问题?