我刚开始学习 Template Haskell,并坚持简单的拼接问题。
在一个模块中,我实现tupleN
了回复元组的第 N 个元素的函数:
tupleN :: Lift a => a -> Int -> Q Exp
tupleN a n = do
(TupE as) <- lift a
return $ as !! n
在主模块中,我有:
main :: IO ()
main = do
let tup = (1::Int,'a',"hello")
putStrLn $ show $(tupleN $tup 1)
这似乎有效,但它不会。编译器打印错误:
GHC stage restriction: `tup'
is used in a top-level splice or annotation,
and must be imported, not defined locally
In the expression: tup
In the first argument of `tupleN', namely `$tup'
In the expression: tupleN ($tup) 1
如果我将元组描述直接放入拼接表达式中,代码就会起作用:
main :: IO ()
main = do
putStrLn $ show $(tupleN (1::Int,'a',"hello") 1)
我在第一个变体中缺少什么?