如何约束 class 实例

How to constrain a class instance

我正在尝试将类型约束应用于具有种类 ->.

的 class 实例
data Data1 = Data1 String

class Class1 m where
    c1f :: m -> m

instance Class1 Data1 where
    c1f (Data1 v) = Data1 v


data Data2 a = Data2 a

class Class2 m where
    c2f :: a -> m a

instance Class2 Data2 where
    c2f x = Data2 (c1f x)

我从最后一行看到这条错误消息:

No instance for (Class1 a) arising from a use of ‘c1f’

如何应用类型约束(数据 2 必须是 Class1 的实例)?

您想让 Class2 的每个实例选择自己的约束吗?如果是这样,试试这个:

{-# LANGUAGE ConstraintKinds, TypeFamilies #-}

import Data.Kind

data Data1 = Data1 String

class Class1 m where
    c1f :: m -> m

instance Class1 Data1 where
    c1f (Data1 v) = Data1 v


data Data2 a = Data2 a

class Class2 m where
    type C2c m :: Type -> Constraint
    c2f :: C2c m a => a -> m a

instance Class2 Data2 where
    type C2c Data2 = Class1
    c2f x = Data2 (c1f x)