您可以使用 Template Haskell 来做到这一点,它在技术上是另一个 GHC 扩展,但可能在某种程度上比 C 预处理器更“纯”。
代码从这里窃取并稍作修改。
{-# LANGUAGE TemplateHaskell #-}
module WithLocation (withLocation) where
import Language.Haskell.TH
withLocation' :: String -> IO a -> IO a
withLocation' s f = do { putStrLn s ; f }
withLocation :: Q Exp
withLocation = withFileLine [| withLocation' |]
withFileLine :: Q Exp -> Q Exp
withFileLine f = do
let loc = fileLine =<< location
appE f loc
fileLine :: Loc -> Q Exp
fileLine loc = do
let floc = formatLoc loc
[| $(litE $ stringL floc) |]
formatLoc :: Loc -> String
formatLoc loc = let file = loc_filename loc
(line, col) = loc_start loc
in concat [file, ":", show line, ":", show col]
像这样使用它(来自另一个模块):
{-# LANGUAGE TemplateHaskell #-}
module Main where
import WithLocation
main = do
$withLocation $ putStrLn "===oo0=Ü=0oo=== Kilroy was here"