我可以表达子类约束吗? [英] Can I express a subclassing constraint?
问题描述
仍然在限制条件下使用存在性(只是探索这个设计空间,我知道许多Haskellers认为它很糟糕).有关更多信息,请参见此问题./p>
Still playing with existentials over constraints (just exploring this design space, I know it is considered bad by many Haskellers). See this question for more info.
{-# 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
无效.
Now I have this problem. doFoo fooable
works, but doFoo barable
doesn't.
• 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这样的类型,其中cls是Foo的子类
,但是我找不到表达它的方法.请多多包涵,我是这些狂野奇特的人的新手.
Can I give a suitable type to doFoo
? Basically I want a type like Obj cls where cls is a subclass of Foo
but I cannot find a way to express it. Please bear with me, I'm new to these wild wonderful types.
推荐答案
您可以为此使用量化约束:
You can use a quantified constraint for that:
{-# LANGUAGE QuantifiedConstraints #-}
doFoo :: forall c . (forall a. c a => Foo a) => Obj c -> Int
doFoo (Obj x) = foo x
基本上, doFoo
可以使用任何 Obj c
,其中 c
是任何暗示 Foo
的类型类,即满足量化约束的类型类
Essentially, doFoo
takes any Obj c
, where c
is any type class which implies Foo
, i.e. a type class satisfying the quantified constraint
forall a. c a => Foo a
这篇关于我可以表达子类约束吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!