Created
May 16, 2012 17:37
-
-
Save MgaMPKAy/2712499 to your computer and use it in GitHub Desktop.
Learn some template haskell
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 #-} | |
import TH | |
fstNTest1 = $(fstN 3) (1, 2, 4) | |
fstNTest2 = $(fstN 4) (2, 3, 4, 5) | |
applyAdd2 = $(apply 'add2 2) 1 2 | |
applyAdd3 = $(apply 'add3 3) 1 2 3 | |
applyAnd = $(apply 'and 4) True True True True | |
add2 [x, y] = x + y | |
add3 [x, y, z] = x + y + z | |
add4 x y z = x + y + z | |
x = $(applyToList 'add4 3) [1, 2, 3] | |
main = undefined |
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 TH where | |
import Language.Haskell.TH | |
import Control.Monad (replicateM) | |
-- f :: Int -> Int -> Int -> Int | |
-- $(apply 'f n) :: [Int] -> Int | |
applyToList f n = do | |
names <- replicateM n (newName "a") | |
return $ LamE [ListP $ map VarP names] | |
(curry' (VarE f) (map VarE names)) | |
where | |
curry' f [] = f | |
curry' f [x] = AppE f x | |
curry' f (x:xs) = curry' (AppE f x) xs | |
apply f n = do | |
xs <- replicateM n (newName "x") | |
return $ LamE (map VarP xs) (AppE (VarE f) (ListE $ map VarE xs)) | |
fstN :: Int -> Q Exp | |
fstN n = do | |
x <- newName "x" | |
return $ LamE [ TupP $ VarP x : replicate (n - 1) WildP] (VarE x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment