简体   繁体   中英

Haskell function that converts type to string by type application

So, I'd like to have a function / value like this :

converter :: Converter a

where Converter would be some type family that always results in String and is used just so that we can apply the type that we want to convert to String by using type application eg

converter @Int => "Int"

I was thinking of using Typeable class which has typeOf function. Unfortunately that requires an actual value for it to work.

I could use Proxy to supply "actual" value, but than I'd have to remove Proxy from the resulting String and that feels a bit dirty and error prone.

Thoughts?

Why not just

{-# LANGUAGE TypeApplications #-}

import Data.Typeable

main = print $ typeRep (Proxy @Int)

typeRep is designed to take a proxy and will only concern itself with the type on that proxy (so no need to remove anything). Sure, the additional Proxy in there is not quite the syntax you're looking for but it's pretty much the same thing right?

We could exploit a bunch of extensions: AllowAmbiguousTypes, TypeApplications, ScopedTypeVariables , and produce a variant of @Cubic's answer.

> :{
| convert :: forall a . Typeable a => String
| convert = show . typeRep $ Proxy @ a
| :}
> convert @ Int
"Int"
> convert @ String
"[Char]"
> convert @ Float
"Float"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM