Re: Stuck... is it even possible?

Bulat Ziganshin <[email protected]> Fri, 20 Jan 2006 16:32:13 +0300
Newsgroups gmane.comp.lang.haskell.template
Message-ID <[email protected]>
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:[email protected]

_______________________________________________
template-haskell mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/template-haskell
flen.hs (application/octet-stream, 960 B) - not displayed
flen-test.hs (application/octet-stream, 228 B) - not displayed