我正在使用 -XExistentialQuantification
GHC 扩展为特定类型类 (Shape
) 的值创建异构容器:
-- Container type
data Object = forall a. Shape a => Object a
-- 'Shape' class. Methods not important
class Eq s => Shape s where
doStuff :: s -> s
鉴于 Shape
的所有实例也是 Eq
的实例,是否有办法使 Object
成为 Eq 的实例
也是如此吗?
最佳答案
如果添加 Typeable
约束,这是可能的:
import Data.Typeable
data Object = forall a. (Shape a, Typeable a) => Object a
instance Eq Object where
Object x == Object y =
case cast y of
Just y' -> x == y'
Nothing -> False
这里,如果 y'
是所需的类型(通过使用 = 推断出),
和 cast y
将返回 Just y'
=x
) 匹配 y
的实际类型,否则 Nothing
。
关于haskell - 测试两个异构值之间的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13015949/