[英]Polymorphic constraint
我有一些做作的类型:
{-# LANGUAGE DeriveFunctor #-}
data T a = T a deriving (Functor)
......那个类型是一些人为的类的实例:
class C t where
toInt :: t -> Int
instance C (T a) where
toInt _ = 0
如何在函数约束中表达T a
是所有a
的某个类的实例?
例如,请考虑以下功能:
f t = toInt $ fmap Left t
直观地说,我希望上面的函数能够工作,因为toInt
在T a
为所有a
,但我不能在类型中表达。 这不起作用:
f :: (Functor t, C (t a)) => t a -> Int
...因为当我们应用fmap
,类型已成为fmap
Either ab
。 我无法解决这个问题:
f :: (Functor t, C (t (Either a b))) => t a -> Int
...因为b
不代表普遍量化的变量。 我也不能说:
f :: (Functor t, C (t x)) => t a -> Int
...或使用forall x
来表明约束对所有x
都有效。
所以我的问题是,是否有一种方法可以说约束对某些类型变量是多态的。
使用约束包:
{-# 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.