Skip to content

Instantly share code, notes, and snippets.

@tmhedberg
Created March 4, 2012 03:51
Show Gist options
  • Select an option

  • Save tmhedberg/1970595 to your computer and use it in GitHub Desktop.

Select an option

Save tmhedberg/1970595 to your computer and use it in GitHub Desktop.
Using Template Haskell to declare operators
{-# LANGUAGE TemplateHaskell #-}
module THOp (mkOps) where
import Control.Monad
import Language.Haskell.TH
mkOp :: String -> Q [Dec]
mkOp n = [| $(varE a) + $(varE b) + length (filter (=='-') n) |] >>= \body ->
return [FunD (mkName n) [Clause [VarP a, VarP b] (NormalB body) []]]
where a = mkName "a"
b = mkName "b"
mkOps :: Int -> Q [Dec]
mkOps n = fmap join $ mapM mkOp $ take n validOps
validOps :: [String]
validOps = fmap (('+':) . (++"+")) (iterate ('-':) "-")
{-# LANGUAGE TemplateHaskell #-}
module THOpTest where
import THOp
mkOps 10
test1 :: IO ()
test1 = putStrLn $ "2 +---+ 3 == 8 : " ++ show (2 +---+ 3 == 8)
test2 :: IO ()
test2 = putStrLn $ "9 +-------+ 7 == 23 : " ++ show (9 +-------+ 7 == 23)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment