我看到的唯一方法是添加
Proxy
将类型变量与
ScopedTypeVariables
.
data Gadt a where
Lit :: KnownNat s => Proxy s -> Gadt ('Index s)
format :: Gadt a -> String
format (Lit (Proxy :: Proxy s)) = undefined
如果您担心额外的分配,可以将字段解包。(编辑:删除以前提到的
Proxy#
因为这似乎不必要)。
import Data.Proxy
-- This should be as efficient as the original Gadt with a nullary Lit
data Gadt a where
Lit :: {-# UNPACK #-} !(Proxy r) -> Gadt ('Index r)
format :: Gadt a -> String
format (Lit (_ :: Proxy r)) = undefined
从长远来看,以下GHC提案将解决这一问题:
Type Applications in Patterns
.
-- The original type
data Gadt a where
Lit :: forall s. Gadt ('Index s)
format :: Gadt a -> String
format (Lit @s) = ...