我有一些做作的类型:
{-# LANGUAGE DeriveFunctor #-}
data T a = T a deriving (Functor)
Run Code Online (Sandbox Code Playgroud)
......那个类型是一些人为的类的实例:
class C t where
toInt :: t -> Int
instance C (T a) where
toInt _ = 0
Run Code Online (Sandbox Code Playgroud)
如何在一个函数约束中表达,它T a
是一个所有类的实例a
?
例如,请考虑以下功能:
f t = toInt $ fmap Left t
Run Code Online (Sandbox Code Playgroud)
直觉上,我希望,因为上面的功能工作toInt
的作品T a
为所有a
,但我无法表达的类型.这不起作用:
f :: (Functor t, C (t a)) => t a -> Int
Run Code Online (Sandbox Code Playgroud)
...因为当我们应用fmap
类型已成为Either a b
.我无法解决这个问题:
f :: (Functor t, C (t (Either a b))) => t a -> Int
Run Code Online (Sandbox Code Playgroud)
...因为b
不代表普遍量化的变量.我也不能说:
f :: (Functor t, C (t x)) => t a -> Int
Run Code Online (Sandbox Code Playgroud)
...或用于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)))
Run Code Online (Sandbox Code Playgroud)