Haskell 哈斯克尔:用Typeable证明“t”存在。a~dt`
我有Haskell 哈斯克尔:用Typeable证明“t”存在。a~dt`,haskell,dynamic-typing,Haskell,Dynamic Typing,我有 数据dt=。。。 data SomeStuff=对于所有a(可键入a,…)=>SomeStuff a 在某个时刻,我得到了一个something,它的内部a我想试着转换成dt(其中t可以是任何类型,我只对d部分感兴趣)。(在伪Haskell中)看起来像: 案例 SomeStuff(::a)->case eqT::Maybe(a:~:(exists t.dt))的 只是Refl->--证明了“t”的存在。a~dt` 没什么->——这里没什么可做的 我一直在摆弄Data.Type.Equa
数据dt=。。。
data SomeStuff=对于所有a(可键入a,…)=>SomeStuff a
在某个时刻,我得到了一个something,它的内部a
我想试着转换成dt
(其中t
可以是任何类型,我只对d
部分感兴趣)。(在伪Haskell中)看起来像:
案例
SomeStuff(::a)->case eqT::Maybe(a:~:(exists t.dt))的
只是Refl->--证明了“t”的存在。a~dt`
没什么->——这里没什么可做的
我一直在摆弄
Data.Type.Equality
和Type.Reflection
(如应用程序等),但我无法让它工作。任何人都有办法做到这一点吗?测试类型是否为D
的形式可以通过使用type.Reflection
实现,如下所示
我们首先根据您的示例给出一些具体的定义,以便稍后测试代码
{-# LANGUAGE GADTs, RankNTypes, ScopedTypeVariables, TypeOperators, TypeApplications #-}
{-# OPTIONS -Wall #-}
import Type.Reflection
data D t = D1 | D2 -- whatever
data SomeStuff = forall a. (Typeable a, Show a) => SomeStuff a
然后,我们测试D
,如下所示:
foo :: SomeStuff -> (forall t. D t -> String) -> String
foo (SomeStuff (x :: a)) f = case typeRep @a of
App d _ | Just HRefl <- eqTypeRep (typeRep @D) d -> f x
_ -> "the SomeStuff argument does not contain a value of type D t for any t"
问题是
t
可以是任何东西。我不能把它限制在一些类型上,比如()
。根据答案,我可能完全把问题搞错了-对不起,谢谢!:)钥匙是eqTypeRep
,不知什么原因,我错过了。。。
foo :: SomeStuff -> (forall t. D t -> String) -> String
foo (SomeStuff (x :: a)) f = case typeRep @a of
App (eqTypeRep (typeRep @D) -> Just HRefl) _ -> f x
_ -> "the SomeStuff argument does not contain a value of type D t for any t"