Haskell实例上下文中的通用量化?

Haskell实例上下文中的通用量化?,haskell,typeclass,Haskell,Typeclass,原始问题 我想做以下工作: class Functor2 c where fmap2 :: (a->b) -> c x a -> c x b instance Functor (c x) => Functor2 c where fmap2 = fmap 但是我得到了一个错误: Could not deduce (Functor (c x1)) arising from a use of `fmap' from the context (Functor (c

原始问题

我想做以下工作:

class Functor2 c where
   fmap2 :: (a->b) -> c x a -> c x b

instance Functor (c x) => Functor2 c where
  fmap2 = fmap
但是我得到了一个错误:

Could not deduce (Functor (c x1)) arising from a use of `fmap'
from the context (Functor (c x))
我怎么做


我的用例

我想对我的
应用程序
实例使用
箭头
方法(和sugar等)。更具体地说,我想要:

newtype Wrap f g a b = W   { unwrap  :: ( f (g a b) ) } 

instance (Category g, "Forall x." Applicative (g x), Applicative f) => Arrow (Wrap f g)
此实例将自动跟随这些(已工作)实例:

instance (Category g, Applicative f) => Category (Wrap f g) where
  id = W $ pure id
  (W x) . (W y) = W $ liftA2 (.) x y

instance (Applicative (g x), Applicative f) => Functor (Wrap f g x) where
  fmap f = W . fmap (fmap f) . unwrap

instance (Applicative (g x), Applicative f) => Applicative (Wrap f g x) where
  pure = W . pure . pure
  (W ab) <*> (W a)  = W $ pure (<*>) <*> ab <*> a
instance(Category g,Applicative f)=>Category(Wrap f g)其中
id=W$pure id
(W x)。(W y)=W$liftA2(.)x y
实例(Applicative(gx),Applicative f)=>函子(Wrap fgx),其中
fmap f=W。fmap(FMAPF)。打开…的包装
实例(Applicative(gx),Applicative f)=>Applicative(Wrap f gx),其中
纯=W。纯净的纯净的
(W ab)(W a)=W$pure()ab a
如果我能让这个工作:

instance (Category c, "Forall x." Applicative (c x)) => Arrow c where
  arr f = (pure f) <*> id
  first a = pure (,) <*> (arr fst >>> a) <*> (arr snd)
instance(类别c,“Forall x.”Applicative(c x))=>箭头c,其中
arrf=(纯f)id
第一个a=纯(,)(arr fst>>>a)(arr snd)
arr
first
的类型在编译器中签出。问题是所有x.“”所需的
,我不知道如何在Haskell中说明


这类
g
的一个简单例子是
->
类别(->)
应用(->)x
对于所有
x

来说,这并不能真正实现您的目标,但可能是向前迈出的一步。 所有x的
。函子(cx)
就是用这种方法编写的
allfunctor2c
。 主要缺点是,您必须为要放入该类的每个函子提供一个实例

{-# LANGUAGE GADTs, ScopedTypeVariables #-}

data Ftor f where
   Ftor :: Functor f => Ftor f

class AllFunctor2 c where
   allFtor2 :: Ftor (c a)

instance AllFunctor2 (->) where
   allFtor2 = Ftor

fmap2 :: AllFunctor2 c => (a->b) -> c x a -> c x b
fmap2 f (x :: c x a) = case allFtor2 :: Ftor (c x) of Ftor -> fmap f x
上述内容可能与直接向
Functor2
提供实例没有太大区别:

class Functor2 c where
   fmap2 :: (a->b) -> c x a -> c x b

instance Functor2 (->) where
   fmap2 = fmap

不能对此很抱歉。即使使用类似的东西也不行?您能否向我们展示一个预期的用例,其中您确实需要这样一个
fmap2
,而
fmap
不会进行类型检查?不如改为将约束添加到类定义中?i、 使函子成为看起来可疑的超类。事实上,我认为,您的
functor 2
将是
(>)
中的Endo-
QFunctor