User Tools

Site Tools


codesnippets:templatehaskell

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)

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
You could leave a comment if you were logged in.
codesnippets/templatehaskell.txt · Last modified: by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki