关于Product与Coproduct中factorizer模式识别的技术问询
Let's unpack these two questions one by one—they're perfect examples of how category theory concepts map directly to Haskell code!
1. Why does (c -> (a, b)) fit the Product factorizer pattern?
First, let's recall the categorical definition of a Product:
A Product of objects
aandbis an objectPtogether with two projection functionsp: P → aandq: P → b, such that for any objectcand pair of functionsf: c → a,g: c → b, there exists a unique functionh: c → P(the factorizer!) wherep ∘ h = fandq ∘ h = g.
Now map this to your Haskell code:
- The Product object
Phere is the tuple(a, b). - The projection functions are Haskell's built-in
fst :: (a, b) → aandsnd :: (a, b) → b. - Your
factorizerfunction is exactly that uniqueh! Let's verify:- When you call
factorizer p q, you get a function\x -> (p x, q x). - Composing
fstwith this function givesfst (h x) = fst (p x, q x) = p x—which matchesfst ∘ h = p. - Similarly,
snd (h x) = q x, sosnd ∘ h = q.
- When you call
The key insight is that tuples in Haskell are the categorical Product for types, and your factorizer enforces the universal property of Products: it takes any pair of functions from c to a/b and combines them into a single function to the Product object, which "commutes" with the projection functions.
2. How to spot the Coproduct pattern in the second factorizer?
Coproducts are the dual of Products—here's their categorical definition:
A Coproduct of objects
aandbis an objectQtogether with two injection functionsi: a → Qandj: b → Q, such that for any objectcand pair of functionsf: a → c,g: b → c, there exists a unique functionh: Q → c(the factorizer!) whereh ∘ i = fandh ∘ j = g.
Let's map this to your Either code:
- The Coproduct object
Qhere isEither a b. - The injection functions are the constructors
Left :: a → Either a bandRight :: b → Either a b. - Your
factorizeris that uniqueh! Let's check the universal property:- When you pass
i :: a → candj :: b → ctofactorizer, it returns a function that handlesEither a bcases:- For
Left a, it runsi a—this is exactlyh (Left a) = i a, meaningh ∘ Left = i. - For
Right b, it runsj b—soh ∘ Right = j.
- For
- When you pass
This is the core of Coproducts: the factorizer takes two functions from a/b to c and combines them into a single function from the Coproduct object to c, which commutes with the injection constructors. In Haskell, Either is the standard Coproduct for types, and this factorizer is actually the same as the base library's either function (you might know it as either i j!).
内容的提问来源于stack exchange,提问作者softshipper

