简体   繁体   English

多态约束

[英]Polymorphic constraint

I have some contrived type: 我有一些做作的类型:

{-# LANGUAGE DeriveFunctor #-}

data T a = T a deriving (Functor)

... and that type is the instance of some contrived class: ......那个类型是一些人为的类的实例:

class C t where
    toInt :: t -> Int

instance C (T a) where
    toInt _ = 0

How can I express in a function constraint that T a is an instance of some class for all a ? 如何在函数约束中表达T a是所有a的某个类的实例?

For example, consider the following function: 例如,请考虑以下功能:

f t = toInt $ fmap Left t

Intuitively, I would expect the above function to work since toInt works on T a for all a , but I cannot express that in the type. 直观地说,我希望上面的函数能够工作,因为toIntT a为所有a ,但我不能在类型中表达。 This does not work: 这不起作用:

f :: (Functor t, C (t a)) => t a -> Int

... because when we apply fmap the type has become Either ab . ...因为当我们应用fmap ,类型已成为fmap Either ab I can't fix this using: 我无法解决这个问题:

f :: (Functor t, C (t (Either a b))) => t a -> Int

... because b does not represent a universally quantified variable. ...因为b不代表普遍量化的变量。 Nor can I say: 我也不能说:

f :: (Functor t, C (t x)) => t a -> Int

... or use forall x to suggest that the constraint is valid for all x . ...或使用forall x来表明约束对所有x都有效。

So my question is if there is a way to say that a constraint is polymorphic over some of its type variables. 所以我的问题是,是否有一种方法可以说约束对某些类型变量是多态的。

Using the constraints package: 使用约束包:

{-# LANGUAGE FlexibleContexts, ConstraintKinds, DeriveFunctor, TypeOperators #-}

import Data.Constraint
import Data.Constraint.Forall

data T a = T a deriving (Functor)

class C t where
    toInt :: t -> Int

instance C (T a) where
    toInt _ = 0

f :: ForallF C T => T a -> Int
f t = (toInt $ fmap Left t) \\ (instF :: ForallF C T :- C (T (Either a b)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM