考虑一个带有两个参数 a 和 b 的 Users 类型。显然,这使 User 可以由两种不同的类型组成:
data Users a b = User a b deriving (Show, Eq, Ord)
我们如何为这个实例声明仿函数和应用程序?
我试过这些方法不会编译:
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)
这些无法编译的原因是什么?
最佳答案
看看Data.Bifunctor
对于在两个参数中都是仿函数的 ADT 的类型类。 User
只是元组的别名,它已经支持这样的实例。在 Haskell 中可以导出双仿函数实例。
@Bakuriu 建议将 User
定义为 newtype
并使用扩展名 GeneralizedNewtypeDeriving
。
对于第二个,请参阅 Biapplicative
.不出所料,它的 (,)
实例是:
instance Biapplicative (,) where
pure = (,)
ap (f, g) (a, b) = (f a, g b)
关于haskell - 在具有多个类型类的自定义数据类型上使用仿函数/应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173864/