List fold
foldL ::(a -> b -> b) -> b -> List a -> b
foldL f e Nil = e
foldL f e (Cons x xs) = f x (foldL f e xs)
sumL = foldL (+) 0
productL = foldL (*) 1
reverseL = foldL (a r -> r ++ [a]) []
7.
Tree fold
foldT ::(b -> b -> b) -> (a -> b) -> (T a -> b)
foldT _ l (L a) = l a
foldT b l (B s t) = b (foldT b l s)
(foldT b l t)
productT = foldT (*) id
8.
fold의 예: fact
•어셈블리
fact0 0 = 1
fact0 n = n * fact (n - 1)
• Structured programming: control structure를 data
structure와 combining form으로 교체
fact1 n = product [1..n]
Fix로 정의한 Expr
dataExpr = Fix ExprF
val :: Fix ExprF
val = In (Const 12)
testExpr = In $ (In $ (In $ Const 2) `Add`
(In $ Const 3)) `Mul` (In $ Const 4)
Catamorphism
g :: Fixf -> a
g = alg . (fmap g) . unFix
• g = cata alg로 정의하면
cata :: Functor f => (f a -> a) -> Fix f -> a
cata alg = alg . fmap (cata alg) . unFix
26.
cata를 이용한 eval의정
의
type SimpleA = Algebra
ExprF Int
alg :: SimpleA
alg (Const i) = i
alg (x `Add` y) = x + y
alg (x `Mul` y) = x * y
cata :: Functor f => (f a -> a) ->
Fix f -> a
cata alg = alg . fmap (cata alg) .
unFix
eval :: Fix ExprF -> Int
eval = alg . fmap eval . unFix
27.
List 다시 보기
dataListF a b = Nil | Cons a b
instance Functor (ListF a) where
fmap f Nil = Nil
fmap f (Cons e x) = Cons e (f x)
28.
algSum
algSum :: ListFInt Int -> Int
algSum Nil = 0
algSum (Cons e acc) = e + acc
lst :: Fix (ListF Int)
lst = In $ Cons 2 (In $ Cons 3 (In $ Cons 4 (In Nil)))
cata algSum lst
== foldr (e acc -> e + acc) 0 [2..4]
29.
Tree 다시 보기
dataTreeF a b = L a | B b b
deriving (Show)
instance Functor (TreeF a) where
fmap f (L a) = L a
fmap f (B x y) = B (f x) (f y)
30.
algSum
algSum :: TreeFInt Int -
> Int
algSum (L a) = a
algSum (B x y) = x + y
> cata algSum tree
6
type IntTree = Fix (TreeF Int)
l :: Int -> IntTree
l x = In (L x)
b :: IntTree -> IntTree -> IntTree
b x y = In (x `B` y)
tree :: IntTree
tree = ((l 1) `b` (l 2)) `b` (l 3)
31.
정리
1. 재귀 함수가일반 함수의 fixed point로 정의되는 것처럼 재귀 타입은 일반
타입의 fixed point로 정의
2. functor는 nested data structure에 대한 recursive evaluation을 지원
3. F-algebra는 1) functor f, 2) carrier type a, 3) f a -> a로 가는 함수로 정의
4. initial algebra는 해당 functor로 정의되는 모든 algebra로 매핑 가능. 이
algebra의 carrier type은 functor의 fixed point
5. initial algebra와 다른 algebra 사이의 유일한 mapping은 catamorphism으
로 생성
6. catamorphism은 simple algebra를 받아서 nested data structure에 대한
recursive evaluator를 제공. 이는 list folding을 다른 데이터 타입으로 일반
화한 것.
32.
참고 자료
1. Origamiprogramming, Jeremy Gibbons
• https://www.cs.ox.ac.uk/jeremy.gibbons/publicatio
ns/origami.pdf
2. Understanding F-Algebras
• https://bartoszmilewski.com/2013/06/10/understa
nding-f-algebras/