Created
March 4, 2012 03:51
-
-
Save tmhedberg/1970595 to your computer and use it in GitHub Desktop.
Using Template Haskell to declare operators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# 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 ('-':) "-") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# 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