本文介绍了在类型族实例上输入类约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以指定类型族的所有实例必须满足的类型约束?

例如,给定以下声明,我将如何确保所有实例都是 Eq 的实例:

数据族通道c :: *



非常感谢,



Michael

$ b { - #LANGUAGE FlexibleContexts,TypeFamilies,FlexibleInstances# - }

- 类中的数据族,以便我们可以添加额外的Eq约束条件
class Eq(Channel c)=> MyClass c其中
数据通道c :: *

- 一个简单的玩具实例
实例MyClass Int其中
数据Channel Int = CI Int推导Eq

- 具有单独Eq实例的更复杂实例
实例MyClass Char其中
数据通道Char = CC Char

实例Eq(Channel Char)其中
(CC x)==(CC y)= x == y


Is it possible to specify a type class constraint that must be satisfied by all instances of a type family?

For example, given the following declaration, how would I ensure that all instances are also instances of Eq:

data family Channel c :: *

Many thanks,

Michael

解决方案

Is this what you are looking for?

{-# LANGUAGE FlexibleContexts, TypeFamilies, FlexibleInstances #-}

-- Data family inside a class so that we can add an extra Eq constraint
class Eq (Channel c) => MyClass c where
    data Channel c :: *

-- A simple toy instance
instance MyClass Int where
    data Channel Int = CI Int deriving Eq

-- A more complex instance with separate Eq instance
instance MyClass Char where
    data Channel Char = CC Char

instance Eq (Channel Char) where
   (CC x) == (CC y) = x == y

这篇关于在类型族实例上输入类约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 01:52
查看更多