[英]Haskell function that converts type to string by type application
所以,我想有一個像這樣的函數/值:
converter :: Converter a
其中Converter
是某種類型族,它總是會導致String
並被使用,以便我們可以通過使用類型應用程序將想要轉換為String
的類型應用為例如
converter @Int => "Int"
我正在考慮使用具有typeOf
函數的Typeable
類。 不幸的是,這需要一個實際值才能起作用。
我可以使用Proxy
來提供“實際”值,但是比起我必須從生成的String
刪除Proxy
,這感覺有點臟並且容易出錯。
有什么想法嗎?
為什么不只是
{-# LANGUAGE TypeApplications #-}
import Data.Typeable
main = print $ typeRep (Proxy @Int)
typeRep
設計為采用代理,並且只關心該代理上的類型(因此無需刪除任何內容)。 當然,其中的其他Proxy
並不是您正在尋找的語法,但是幾乎是同一回事嗎?
我們可以利用大量擴展: AllowAmbiguousTypes, TypeApplications, ScopedTypeVariables
, AllowAmbiguousTypes, TypeApplications, ScopedTypeVariables
,並產生AllowAmbiguousTypes, TypeApplications, ScopedTypeVariables
答案的變體。
> :{
| convert :: forall a . Typeable a => String
| convert = show . typeRep $ Proxy @ a
| :}
> convert @ Int
"Int"
> convert @ String
"[Char]"
> convert @ Float
"Float"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.