Working with a list in TemplateHaskell

Here's the tutorial I'm working from .

He has an example, tupleReplicatewhich returns a function that takes a value and replicates it:

tupleReplicate :: Int -> Q Exp
tupleReplicate n = do id <- newName "x"
                      return $ LamE (VarP id)
                                    (TupE $ replicate n $ VarE id)

So, VarE idreturns an expression that can then be used with replicate? My question is: how does it work if there idwas a list? I want to do something like:

let vals = mkName "vals"
LamE (ListP vals) (map reverse $ ListE vals)

except that it does not work because it ListEreturns Exp, not [Exp].

In general, I want to write a function that takes a list and applies a function to it in TemplateHaskell.


Here is sample code here , and I'm trying to write a function like

makeModel (id_ : name_ : []) = Person (fromSql id_) (fromSql name_)
+5
source share
1

:

{-# LANGUAGE FlexibleInstances, TemplateHaskell #-}

import Language.Haskell.TH

, :

data Person = Person Int String deriving Show

class SQL a where 
  fromSql :: String -> a

instance SQL Int where fromSql = read
instance SQL String where fromSql = id -- This is why I needed FlexibleInstances

, , . , makeModel ( ):

LamE [ListP [VarP id,VarP name]] (AppE (AppE (ConE Person) (AppE (VarE fromSql) (VarE id))) (AppE (VarE fromSql) (VarE name)))
\       [         id,     name ] -> (    (         Person     (        fromSql        id ))   (         fromSql        name ))
\       [         id,     name ] ->                Person $            fromSql        id   $            fromSql        name 

( Exp, runQ [| \[id,name] -> Person (fromSql id) (fromSql name) |] ghci!)

id name, , field_1 ..

makeMakeModel qFieldNames qMapFunction qConstructor =  -- ["id","name"] 'fromSql 'Person
      LamE [ListP (map VarP qFieldNames)]              -- \ [id,name]
           $ foldl AppE (ConE qConstructor)            -- Person  
                        [AppE (VarE qMapFunction) (VarE name)|name <- qFieldNames]
                                                       -- $ id $ name

makeModel fieldNames mapFunction constructor = do
   names <- mapM newName fieldNames
   return $ makeMakeModel names mapFunction constructor

ghci -XTemplateHaskell:

*Main> runQ $ makeModel ["id","name"] 'fromSql 'Person
LamE [ListP [VarP id_0,VarP name_1]] (AppE (AppE (ConE Main.Person) (AppE (VarE Main.fromSql) (VarE id_0))) (AppE (VarE Main.fromSql) (VarE name_1)))

*Main> $(makeModel ["id","name"] 'fromSql 'Person) ["1234","James"]
Person 1234 "James"

, , newName, , , , , 'fromSql 'Person .


,

runQ [d| makeModel [id,name] = Person (fromSql id) (fromSql name) |]

- [d| ... |] .

+2

All Articles