====== TemplateHaskell ====== ===== Creating code at compile time ===== * Example, creates a curry function for arbitrary large curry functions module Curry ( curryN ) where import Control.Monad import Language.Haskell.TH curryN :: Int -> Q Exp curryN n = do f <- newName "f" xs <- replicateM n (newName "x") let args = map VarP (f:xs) ntup = TupE (map (pure . VarE) xs) return $ LamE args (AppE (VarE f) ntup) ===== Using the created code ===== * Example, uses the curry function by using the placeholder `$(C.curryN 3)` that will be expanded by ghc {-# LANGUAGE TemplateHaskell #-} module Lib ( someFunc ) where import qualified Curry as C someFunc :: IO () someFunc = do print $ $(C.curryN 3) f1 1 ' ' ["Hallo"] print $ $(C.curryN 3) f1 1 '_' ["Hallo","world"] print $ $(C.curryN 3) f1 1 '.' ["Hallo","world","!"] f1 :: (Int,Char,[String]) -> String f1 (ni,ch,[]) = [] f1 (ni,ch,[s0]) = s0 f1 (ni,ch,s0:s1:rls) = s0 ++ replicate ni ch ++ f1 (ni,ch,s1:rls) ===== ✎ ===== ~~DISCUSSION~~