gpt4 book ai didi

haskell - 根据子类优化父类(super class)方法

转载 作者:行者123 更新时间:2023-12-02 02:05:23 26 4
gpt4 key购买 nike

当类型也在另一个类中时,我能否在类实例中提供方法的精细实现(又名 OOP 中的覆盖)?或者至少,如果该其他类是子类。

我有课C用方法m , 一个子类 SC用方法s和一个类型 T a所以有实例化

class C a where m :: [a] -> Bool
class C a => S a where s :: a -> a -> Bool
instance C a => C (T a) where m = ...
instance S a => S (T a) where s = ...

照常。
现在恰好是当 T a在子类中(我不知道,因为它取决于 a ),方法 m使用 s 可以更有效地实现(二次与指数时间) .

我尝试了“覆盖” m在实现中
instance S a => S (T a) where
s = ...
m = (all . uncurry) (=^=) . pairs -- override C.m

但编译器错误基本上是因为, m不是 S 的公共(public)方法.好吧,它不是,但它在 OO 意义上是继承的。

针对特定目的, m 的专业版可用于所有实例;它不是在任何地方被覆盖的默认值。

编辑:由于要求,具体代码有点解释。

我有课 Model它有(除其他外)一个方法 con检查列表的一致性。
class Model a where
con :: [a] -> Bool

两个模型可以组成一个箭头模型。
data Arrow a b = [a] :->: b
lhs w = [ a | (u :->: _) <- w, a <- u ]
rhs w = [ b | (_ :->: b) <- w ]

具体实例 Model (Arrow a b) , 一般 con实现非常昂贵(注意 powerset 在定义中)。
instance (Model a, Model b) => Model (Arrow a b) where
con w = all (\w' -> con (lhs w') `implies` con (rhs w')) (powerset w)

有一个子类 CoherentModelModel它有一个方法 (=^=)检查两个对象的一致性。连贯模型的条件是,如果所有对都是一致的,则列表是一致的。
class Model a => CoherentModel a where
(=^=) :: a -> a -> Bool
a =^= b = con [a, b]

类(class) CoherentModel在这一点上,文档多于功能。

因此,鉴于模型是连贯的,一致性检查的效率要高得多。
instance (Model a, CoherentModel b) => CoherentModel (Arrow a b) where
(u :->: a) =^= (v :->: b) = con (u ++ v) `implies` a =^= b

在这种情况下, con可以使用实现
con = (all . uncurry) (=^=) . pairs
where
pairs :: [a] -> [(a,a)]
pairs [] = []
pairs [_] = []
pairs [x,y] = [(x,y)]
pairs (x:xs) = map ((,) x) xs ++ pairs xs

但我没有办法指定这一点。这不仅适用于 Arrow ,它适用于所有带参数的模型。我选择了 Arrow因为改进是显着的。

最佳答案

这是个好问题。要记住的一件事是,数据类型是否是类型类的实例只是编译时信息——即,我们总是能够使用使用站点上的静态可用信息来选择要使用的实例,而多态性来自于能够从上下文中选择一个实例。一般来说,如果你问“a 是类型类的成员 B 吗?”,你能得到的唯一答案是"is"和“编译错误”。 (第二个观察结果稍有更改 OverlappingInstances ,但对您的情况似乎没有帮助)

因此,您的直接问题的答案是否定的。除非您是该类型类的方法,否则您无法决定类型在类型类中的成员资格。我们可以做的是将此决定添加为一种方法(使用 constraints 包)

import Data.Constraint

class Model a where
con :: [a] -> Bool
isCoherent :: Maybe (Dict (CoherentModel a))
isCoherent = Nothing

您可以为已实例化的任何类型轻松定义 CoherentModel在:
instance Model Foo where
con = ...
isCoherent = Just Dict

现在您可以像这样实现您的决定(带扩展名 ScopedTypeVariablesTypeApplications ):
instance (Model a, Model b) => Model (Arrow a b) where
con | Just Dict <- isCoherent @b = -- efficient implementation
| otherwise = -- inefficient implementation

在第一个案例的主体中,我们将有一个本地 CoherentModel b在上下文中。这有点酷。

太糟糕了,我们有一种 expression problem这里是 con 的所有不同实现需要收集到一个地方。也太糟糕了 isCoherent需要在每个相干的 Model 上手动实现实例,与其 CoherentModel 的位置分开实例是。

这里有很多值得探索的地方,但我必须去。祝你好运!

关于haskell - 根据子类优化父类(super class)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com