代数的データ型とF-代数
#圏論とプログラミング
代数的データ型とF-代数の対応
Catamorphismとfoldの対応
リスト型とF-始代数
$ X,\mathrm{Nil},B,AはHask圏の対象。$ aは射。
Hask圏において、関手$ F(X)=\mathrm{Nil}+B\times Xを考える
この関手のF-始代数$ (A,a)が存在したとすると、
Lembekの定理より$ A\cong F(A)が成り立つ
さらに$ A=\mathrm{List}Bとすると、これらより
$ \mathrm{List}B\cong\mathrm{Nil}+B\times\mathrm{List}Bになる
data List b = Nil | Cons b (List b)と対応していることがわかる
#??
$ \rm{List}(B)は始対象として扱っていいのか?なんで?
つまり「$ A=\mathrm{List}Bとすると」は言っていいのか?
今回の話に固有の変数を代入する前のF-代数の図と、代入したものの図を並べて書いてみる
https://gyazo.com/ecc5f10314a300115e8fabf9ad5482c7
まず、画像右の上の矢印$ \mathrm{Nil}+B\times\mathrm{List}B\to\mathrm{List}Bの射を考える
先ほどの型List bの値コンストラクタの型を調べるとこうなる
code:hs
data List b = Nil | Cons b (List b)
-- Nil :: List b
-- Cons :: b -> List b -> List b
これに合うように射を定義する
$ n:\mathrm{Nil}\to\mathrm{List}B
$ c:B\times\mathrm{List}B\to\mathrm{List}B
この2つの射をこの記事に倣って$ [n,c] と表記する
$ \phiについても
同じノリで$ [f,x] を割り当てる
すると上図右はこうなる
https://gyazo.com/cecbdae7c9d3f4b061155e647513f0cd
この図を直和の性質を用いて2つの図にわける ref
なにこれ #??
https://gyazo.com/724ef02fb29930dff760eea8867a6306
緑を左辺、青を右辺とすれば以下の2式が導かれる
$ |[x,f]|\circ c=f\circ(B\times|[x,f]|)
$ |[x,f]|\circ n=x
これはfoldrの定義そのもの
code:hs
foldr :: a -> (b -> a -> a) -> List b -> a
(foldr x f) Nil = x
(foldr x f) (Cons a as) = f a ((foldr x f) as)
一般のfoldrと引数の順番が異なることには注意
まとめるとこうなる
https://gyazo.com/006a951aaaaa5339fd7961fff6070f35
つまりCatamorphismがfoldに対応する
この記事によると
F-始代数は有限データ構造を表す
Catamorphismはfoldに対応する
F-終余代数は無限のデータ構造を表す
Anamorphismはunfoldに対応する
Haskellは遅延評価なのでF-始代数とF-終余代数が一致する
#??
F-始代数はリスト型以外にも応用可能?
foldlも導ける?
やってみようmrsekut.icon
参考
代数的データ型とF代数 - Qiita
さいきょうの記事
https://qiita.com/rinse_/items/878a962f92e675f21695#catamorphism
とちゅう
https://ja.wikipedia.org/wiki/Catamorphism
https://ja.wikipedia.org/wiki/始代数
https://gist.github.com/aiya000/c5919ba4039376bdf0574ba3f68a25c7
http://nineties.github.io/category-seminar/7.html#/44
http://nineties.github.io/category-seminar/8.html#/
http://nineties.github.io/category-seminar/10.html#/
https://qiita.com/rinse_/items/022e212474e40da3a2fe
https://qiita.com/rinse_/items/8335294ebb7e93cc84c2
http://bitterharvest.hatenablog.com/entry/2019/06/09/061439
http://cympfh.cc/aiura/F-algebra.html
https://bartoszmilewski.com/2017/02/28/f-algebras/