RE: [Template-haskell] Using a Typ as a Type
| Is there any way that I can use a Typ (i.e., a reified Type) as a Type inside | a template so that I can use the Typ to select an instance of a type class. | | For example, I'd like to be able to write (this doesn't parse): | | $(test [t[ Float ]] "1.0") | | test :: Q Typ -> String -> Q [Dec] | test qty x = do | ty <- qty | print (read x :: $ty) -- The ':: $ty' part is the important bit | return [] I've Sean's reply and Alastair's reply to that, and I still can't figure out what you are trying to do. The above code looks weird. test is a Q [Dec], but you are doing a print in the middle of it. Why? In principle you can certainly say: $(test [t| Float ]] "2.0") test :: Q Type -> String -> Q [Dec] test qty x = [| read (x::$qty) |] so that $(test [t| Float ]] "2.0") ===> read ("2.0" :: Float) TH doesn't support type splices today; that's one of the things I'm actively working on. But I'm not sure if this is what you meant. Simon
I've Sean's reply and Alastair's reply to that, and I still can't figure out what you are trying to do. The above code looks weird. test is a Q [Dec], but you are doing a print in the middle of it. Why?
I have been rewriting Greencard in Template Haskell. The templates I'm writing do IO because: 1) They need to pass state between calls to templates. 2) They need to generate a file of C code (as Greencard does). What I really, really wanted to do was use typeclasses to implement automatic fillin. In Greencard 2, we translate types into DIS invocations using the following translation: Int -> int String -> string AnyType -> anyType Foo Bar -> error "can't handle type applications" where we change the first letter to lower case. In Template Greencard, I wanted users to define these translations by writing typeclasses: instance DIS Int where dis = int instance DIS String where dis = string instance DIS AnyType where ... instance DIS (Foo a) where ... instance DIS Bar where ... and I'd then write: dis :: $ty to do the lookup.
TH doesn't support type splices today; that's one of the things I'm actively working on. But I'm not sure if this is what you meant.
It is but it is very important that: 1) We can do dictionary lookups using the spliced type. 2) The lookup happen at compile time so that it can affects the code being generated. 3) Instances declared in the code being compiled (like the DIS instances above) can be found by this mechanism. That is, I'm not interested in finding any DIS instances that might have been present in the source code for ghc. -- Alastair
participants (2)
-
Alastair Reid -
Simon Peyton-Jones