【发布时间】:2018-08-03 11:29:02
【问题描述】:
我正在学习 Haskell 并尝试从 Haskell Programming 一书中从第一原理开始做练习,我正在尝试为 Pair 类型编写应用程序
data Pair a = Pair a a deriving Show
我在网上看到了一些其他的例子,但我正在尝试一些不同的应用函子,我正在尝试利用这种类型的单曲面结构。这是我所拥有的
data Pair a = Pair a a deriving (Show, Eq)
instance Functor Pair where
fmap f (Pair x y) = Pair (f x) (f y)
instance Semigroup a => Semigroup (Pair a) where
(Pair x y) <> (Pair x' y') = Pair (x <> x') (y <> y')
instance Applicative Pair where
pure x = Pair x x
(Pair f g) <*> p = fmap f p <> fmap g p
不幸的是,这不会编译:
* No instance for (Semigroup b) arising from a use of `<>'
Possible fix:
add (Semigroup b) to the context of
the type signature for:
(<*>) :: forall a b. Pair (a -> b) -> Pair a -> Pair b
* In the expression: fmap f p <> fmap g p
In an equation for `<*>': (Pair f g) <*> p = fmap f p <> fmap g p
In the instance declaration for `Applicative Pair'
这就是我的堆栈;我看不到如何将 typeclass 约束添加到 Applicative 定义中,我认为制作 Semigroup 的类型 Pair 实例就足够了。
我见过的其他解决方案是这样的
Pair (f g) <*> Pair x y = Pair (f x) (g y)
但这些解决方案不使用 Pair 类型的单曲面部分
是否有可能以我不尝试的方式进行应用?
【问题讨论】:
-
我可能是错的,但我认为您使用的术语“monoidal functor”指的是 actual definition 以外的其他东西。
-
您遇到了同样的问题,这意味着
Set不能是Monad(或Applicative),因此围绕该问题的许多讨论也应该在网上流传对你来说很有趣。考虑在谷歌上搜索“受约束的单子”以获得很多很多起点。
标签: haskell applicative monoids