GHC.Generics Comp1的编写器(:。:)

时间:2017-04-09 08:47:44

标签: haskell functional-programming

我坚持使用Functor实例来构建haskell中的其他仿函数。

data Cmps f g x = Cmps {getCmps :: f (g x)} deriving (Eq,Show) 

--
instance (Functor f, Functor g) => Functor (Cmps f g) where
  -- fmap :: (a -> b) -> (Cmps f g) a -> (Cmps f g) b
  fmap = ?

在GHC.Generics functor中使用{ - #LANGUAGE DeriveFunctor# - }

派生
-- | Composition of functors
infixr 7 :.:
newtype (:.:) f (g :: * -> *) (p :: *) = Comp1 { unComp1 :: f (g p) }
  deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)`

由于错误,我无法得到fmap h (Cmps f g x) = Cmps f g (h x)之类的内容 The constructor ‘Cmps’ should have 1 argument, but has been given 3fmap h (f (g x))之类的内容也不起作用。如何在fmap实现中从f, g and x类型获取Cmps

1 个答案:

答案 0 :(得分:1)

将Li-yao Xia和orlan的评论作为答案加以巩固。

Cmps定义中......

data Cmps f g x = Cmps {getCmps :: f (g x)} deriving (Eq,Show)

... fgx是类型变量;他们不代表田野。 Cmps有一个f (g x)类型的字段。因此,fmap的实现应该是:

instance (Functor f, Functor g) => Functor (Cmps f g) where
  -- fmap :: (a -> b) -> (Cmps f g) a -> (Cmps f g) b
  fmap h (Cmps x) = Cmps (fmap (fmap h) x)

如果要将其与未派生的核心库中的等效实例进行比较,请查看Data.Functor.Compose中的Compose