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