Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert any type to Symbol using type families?

I want to convert any type to type-level string using some type families.

Of course, I can write something like this:

type family ShowType (t :: Type) :: Symbol where
    ShowType Int    = "Int"
    ShowType String = "String"
    ...

But I wonder is there some existing mechanism for this? I can do this in runtime using Typeable techniques. But how can I automatically convert any type to Symbol?

like image 636
Shersh Avatar asked Nov 08 '22 10:11

Shersh


1 Answers

There isn't a general solution for all types. But maybe you'll find the following interesting.

You can get the name of a type constructor with an instance of Generic, although that excludes primitive types like Int and Float. Two different ways are given below:

{-# LANGUAGE AllowAmbiguousTypes#-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}

import Data.Proxy
import GHC.Generics
import GHC.TypeLits

-- Solution 1: Defines a type family that extracts the type
-- constructor name as a Symbol from a generic Rep.
-- Then it can be reified via GHC.TypeLits.symbolVal.

type family TyConName (f :: * -> *) :: Symbol where
  TyConName (M1 D ('MetaData name _mdl _pkg _nt) _f) = name

tyConName
  :: forall a s
  .  (Generic a, s ~ TyConName (Rep a), KnownSymbol s) => String
tyConName = symbolVal (Proxy @s)

-- Solution 2: Uses the GHC.Generics.datatypeName helper
-- (value-level string only).

tyConName'
  :: forall a d f p
  .  (Generic a, Rep a ~ D1 d f, Datatype d) => String
tyConName' = datatypeName (from @a undefined)

main = do
  print (tyConName @(Maybe Int))   -- "Maybe"
  print (tyConName' @(Maybe Int))  -- "Maybe"
like image 136
Li-yao Xia Avatar answered Nov 15 '22 06:11

Li-yao Xia