gpt4 book ai didi

haskell - 是否可以将其他类型变量引入父类(super class)约束?

转载 作者:行者123 更新时间:2023-12-03 15:01:15 25 4
gpt4 key购买 nike

在处理类型族时,使用等式约束来避免在签名中重复某些类型函数的名称通常很方便:

class Foo f where
type BulkyAssociatedType f :: *
foo :: BulkyAssociatedType f -> f
...

bar :: forall m f b .
( Monad m, Foo f, b ~ BulkyAssociatedType f
, Monoid b, Monoid (m b)
) => f -> m f

即使缩写没有出现在签名本身中,这也有效,只有在约束中。

对于类,这显然是不可能的;
class ( Foo f, b ~ BulkyAssociatedType f, Monoid b, ...) => Bar f

提示类型变量 b不在范围内。

是否有某种方法可以实现类似的事情,以避免一些重复样板?

最佳答案

得知您无法做到这一点让我感到惊讶(我使用了相同的技术并且知道它适用于实例声明),但似乎有一个长期存在的 GHC feature request支持这一点。

也许你可以使用 ConstraintKinds 获得相同的好处:

{-# LANGUAGE TypeFamilies , FlexibleContexts , ConstraintKinds #-}
import Data.Monoid

class Foo f where
type BulkyAssociatedType f :: *

type B f = (Monoid (BulkyAssociatedType f))

class ( Foo f, B f) => Bar f

关于haskell - 是否可以将其他类型变量引入父类(super class)约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21270013/

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