Tom*_*age 8 haskell existential-type ghc
我正在使用-XExistentialQuantificationGHC扩展为特定类型类(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
Run Code Online (Sandbox Code Playgroud)
鉴于所有实例Shape都是实例Eq,是否有办法制作Object实例Eq?
ham*_*mar 19
如果添加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
Run Code Online (Sandbox Code Playgroud)
这里,如果所需的类型(从使用with 推断)与实际类型匹配,cast y则返回,否则. Just y'y'==xyNothing