haskell - 测试两个异构值之间的相等性

标签 haskell ghc existential-type

我正在使用 -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/

相关文章:

haskell - Haskell 中的可扩展状态机

macos - 为什么 Haskell Stack 在尝试构建我的项目时挂起?

list - 为什么 GHC 不能对一些无限列表进行推理?

haskell - 在没有 unsafeCoerce 的情况下玩弄存在主义

c++ - C++中存在量化的等价物?

haskell - 在 Haskell 中将 Writer monad 与 Conduit 结合使用

haskell - 理解单态与多态 Core 表达式

haskell - 为什么默认情况下 forall(RankNTypes 用法)不适用?

haskell - 如何将Haskell编译成静态库?

haskell - 反序列化存在的数据类型