Haskell 中的乘积和总和类型平行线类型 类

Product and Sum Type Parallels in Haskell Type Classes

似乎分别键入 类 例如 Applicative, Monad and Arrow have some sort of sum type equivalent in type classes such as Alternative, MonadPlus and ArrowPlus。例如,Applicative 和 Alternative 可用于定义以下内容:

(<&&>) :: Applicative f => f a -> f b -> f (a, b)
a <&&> b = (,) <$> a <*> b

(<||>) :: Alternative f => f a -> f b -> f (Either a b)
a <||> b = (Left <$> a) <|> (Right <$> b)

然而,在所有这些情况下(以及 ArrowChoice), the product type class is a prerequisite for the sum type class. Are there type class rules or common functions that depend on the prerequisite class? The Typeclassopedia 都涉及到这些关系,但不幸的是我找不到任何明确的依赖原因。

Arrow 基本上是 monoidal categories1 的 class——“幺半群”不是指 Monoid,而是Haskell 类型 的乘积幺半群。即,单位元素 () 和乘法 (,)。现在,求和类型也构成了一个幺半群,这就是 ArrowChoice 所使用的。这两个 classes 在这个意义上是互补的; ArrowChoice 不应该是 Arrow 的子 class。

在幺半群类别中,您可以继续 monoidal functors。这些结果如何取决于你使用什么作为你的类型幺半群。 (), (,),你得到

class ProdMonoidalFtor f where
  prodUnit :: () -> f ()
  prodZip :: (f a, f b) -> f (a,b)

type (+) = Either
class SumMonoidalFtor f where
  sumUnit :: Void -> f Void
  sumZip :: f a + f b -> f (a+b)

事实证明后者基本上没用,因为 Voidinitial object of Hask, meaning there exists exactly one Void -> a (namely absurd) for all types a。然而,有意义的是 comonoidal functor with +:

class SumCoMonoidalFtor f where
  sumCounit :: f Void -> Void -- I bet you find this useless too, but it's not totally.
  sumCozip :: f (a+b) -> f a + f b

这反过来对产品类型没有意义,因为 () 终端 对象。

现在有趣的是 ProdMonoidalFtor 等同于 Applicative:

instance (ProdMonoidalFtor f) => Applicative f where
  pure x = fmap (const x) $ prodUnit ()
  fs <*> xs = fmap (\(f,x) -> f x) $ prodZip (fs,xs)

有人可能会怀疑 Alternative 等同于 SumMonoidalFtor,但事实并非如此!实际上,它等同于 decisive functors, which are to comonads 就像应用程序对 monads 一样。

AlternativeMonadPlus 似乎并没有太多的数学支持,它们本质上是你在“非克莱斯利”时得到的 ArrowChoice class,但使用来自 ProdMonoidalFtor 的 Kleisli 类别。有点可疑。


1这只考虑了first/leftsecond/right***/+++。至于剩下的&&&|||arr,这些比较具体,IMO属于in seperate classes.