Hask 中的类型的副产品

直觉

两种类型 AB 的分类产品应包含包含在类型 A 或类型 B 的实例内所需的最小信息。我们现在可以看到两种类型的直观副产品应该是 Either a b。其他候选人,如 Either a (b,Bool),将包含一部分不必要的信息,并且它们不会是最小的。

正式定义源于副产品的分类定义。

分类副产品

分类副产品是分类产品的双重概念。它是通过反转产品定义中的所有箭头直接获得的。两个对象 XY 的副产品是另一个具有两个夹杂物的物体 Zi_1:X→Zi_2:Y→Z ; 这样,从 XY 到另一个物体的任何其他两个态射通过这些包含物唯一地分解。换句话说,如果有两个态射 f 1:X→Wf 2:Y→W ,则存在唯一的态射 g:Z→W ,使得 g○i 1 = f 1g○i 2 = f 2

Hask 中的副产品

翻译成 Hask 类是类似产品的翻译:

-- if there are two functions
f1 :: A -> W
f2 :: B -> W
-- and we have a coproduct with two inclusions
i1 :: A -> Z
i2 :: B -> Z
-- we can construct a unique function
g  :: Z -> W
-- such that the other two functions decompose using g
g . i1 == f1
g . i2 == f2

两种类型 AB 中的副产物类型 HaskEither a b 或任何其它类型的同构它:

-- Coproduct
-- The two inclusions are Left and Right
data Either a b = Left a | Right b

-- If we have those functions, we can decompose them through the coproduct
decompose :: (A -> W) -> (B -> W) -> (Either A B -> W)
decompose f1 f2 (Left x)  = f1 x
decompose f1 f2 (Right y) = f2 y