首页 > 解决方案 > 我可以表达一个子类约束吗?

问题描述

仍然在玩存在主义而不是约束(只是探索这个设计空间,我知道许多 Haskeller 认为它很糟糕)。有关更多信息,请参阅此问题

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ConstraintKinds #-}
{-# Language TypeApplications #-}

import GHC.Exts (Constraint)

class Foo a where
   foo :: a -> Int

class Foo a => Bar a where
   bar :: a -> String

instance Foo Int where
   foo = id

instance Bar Int where
   bar = show

data Obj cls = forall o. (cls o) => Obj o

fooable = Obj @Foo $ (42 :: Int)
barable = Obj @Bar $ (42 :: Int)

doFoo :: Obj Foo -> Int
doFoo (Obj x) = foo x

现在我有这个问题。doFoo fooable有效,但doFoo barable没有。

• Couldn't match type ‘Bar’ with ‘Foo’
  Expected type: Obj Foo
    Actual type: Obj Bar
• In the first argument of ‘doFoo’, namely ‘barable’
  In the expression: doFoo barable
  In an equation for ‘it’: it = doFoo barable

这当然是真的。Obj Foo是不同的Obj Bar

我可以给一个合适的类型doFoo吗?基本上我想要一种类型,Obj cls where cls is a subclass of Foo但我找不到表达它的方法。请多多包涵,我对这些狂野的奇妙类型是新手。

标签: haskelltypestypeclassexistential-type

解决方案


您可以为此使用量化约束:

{-# LANGUAGE QuantifiedConstraints #-}

doFoo :: forall c . (forall a. c a => Foo a) => Obj c -> Int
doFoo (Obj x) = foo x

本质上,doFoo采用 any Obj c,其中c任何类型类都暗示Foo,即满足量化约束的类型类

forall a. c a => Foo a

推荐阅读