简体   繁体   English

在具有多个类型类的自定义数据类型上使用仿函数/求和论?

[英]Using functors/applicatives on custom data types with multiple type classes?

Consider a Users type with two parameters, a and b. 考虑具有两个参数a和b的用户类型。 Clearly, this enables User to be composed of two different types: 显然,这使用户可以由两种不同的类型组成:

data Users a b = User a b deriving (Show, Eq, Ord)

How can we declare functors and applicative for this instance? 我们如何为该实例声明函子和应用函数?

I've tried these approaches won't compile: 我尝试过这些方法无法编译:

instance Functor Users where
   fmap f(User a b) = User (f a) (f b) 

instance Applicative Users where
   pure a b = User a b
   (<*>) User a b = (fmap a) (fmap b)

What's the reason these won't compile? 这些文件无法编译的原因是什么?

Have a look at Data.Bifunctor for a type class for ADTs which are functorial in both arguments. 看一下Data.Bifunctor中用于ADT的类型类,这两个函数都是函数性的。 User is then just a fancy name for tuple, and this already supports such an instance. 然后, User只是元组的一个奇特的名称,并且该名称已经支持这样的实例。 Deriving a bifunctor instance is possible in Haskell. 在Haskell中可以导出bifunctor实例。

@Bakuriu suggests defining User as a newtype and the using the extension GeneralizedNewtypeDeriving . @Bakuriu指出定义User作为newtype和使用扩展GeneralizedNewtypeDeriving

For the second one, see Biapplicative . 对于第二个,请参见Biapplicative As to be expected, its instance for (,) is: 可以预期,其(,)实例为:

instance Biapplicative (,) where
  pure = (,)
  ap (f, g) (a, b) = (f a, g b)

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

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