You can write multiple lines in TemplateHaskell splices
One day, I found out that TemplateHaskell splices (that $()
thingy) accept multiple lines (confirmed on GHC 7.6.3), like,
{-# LANGUAGE TemplateHaskell #-} import Data.Aeson.TH (deriveJSON, Options(..), SumEncoding(..), defaultOptions) import Data.Aeson (encode) import Data.ByteString.Lazy.Char8 (unpack) data Sex = Male | Femail | OtherSex data Person = Person { first_name :: String, second_name :: String, age :: Int, sex :: Sex } $(do let opts = defaultOptions { sumEncoding = ObjectWithSingleField } derive_sex <- deriveJSON opts ''Sex derive_person <- deriveJSON opts ''Person return (derive_sex ++ derive_person) ) main :: IO () main = do let p = Person { first_name = "Toshio", second_name = "Ito", age = 30, sex = Male } putStrLn $ unpack $ encode p
The executable code above prints
{"first_name":"Toshio","second_name":"Ito","age":30,"sex":"Male"}
The top-level splice (the $()
where we use deriveJSON
) expects the type Q [Dec]
. Q
is just a Monad
, so we can use do
notation inside the splice.
I've searched on the Internet about this multi-line feature, but never found any information. Maybe it's too obvious.