[Template-haskell] Stuck... is it even possible?

Bulat Ziganshin bulatz at HotPOP.com
Fri Jan 20 08:32:13 EST 2006


Hello Tim,

Friday, January 20, 2006, 12:51:39 PM, you wrote:

TN>      flen ("Word8",_,_)    should compute "containerLength newWord8"
TN>      flen ("Word16",_,_)   should compute "containerLength newWord16"
TN>      flen ("IP",_,_)       should compute "containerLength newIP"
TN>      flen (n,_,_)          should compute "containerLength" of ("new"++n)

first, `flen` must be monadic computation because it needs access to the Q
monad

second, define it recursively:

flen t | t=='Word8  = return 1
flen t | t=='Word16 = return 2
flen t = do -- Get information about type t, assuming it is declared as
            -- one-constructor "data", such as "data T = T Int16 Word32"
            TyConI (DataD _ _ _ [constructor] _)  <-  reify t
            -- Get types of individual fields
            let fields = fieldTypes constructor
            -- Calculate len for each field
            flens <- mapM flen fields
            return (sum flens)

... i attached the finally debugged version together with test

you can't run at compile time your run-time function
`containerLength`, so you just need to arrange these calcultaions
yourself, using `reify` to get fieldlist for each data type

> I have a record name and a field name (and a field type name), all
> as strings.

passing them as the strings is not good idea. it's better to keep them
as Name values (Name type is defined in TH)

-- 
Best regards,
 Bulat                            mailto:bulatz at HotPOP.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: flen.hs
Type: application/octet-stream
Size: 960 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/template-haskell/attachments/20060120/48d4d6ae/flen.obj
-------------- next part --------------
A non-text attachment was scrubbed...
Name: flen-test.hs
Type: application/octet-stream
Size: 228 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/template-haskell/attachments/20060120/48d4d6ae/flen-test.obj


More information about the template-haskell mailing list