updated cata

This commit is contained in:
Yann Esposito (Yogsototh) 2012-12-09 22:01:56 +01:00
parent b00276eb7b
commit e79bee6398
3 changed files with 84 additions and 0 deletions

View file

@ -0,0 +1,39 @@
κατα-morphism: fold generalization
----------------------------------
Typically, you need a recursive type (list, trees, ...)
Str = Cons Char Str
1st: replace the recursive type by another type.
StrChar a = Cons Char a
Str' a = Mu StrChar
Str' = InF { outF :: StrChar (Mu ListElement) }
Str' = InF { outF :: StrChar (Str') }
Clearly isomorph to List.
~~~
type Algebra f a = f a -> a
data Mu f = InF { outF :: f (Mu f) }
cata :: Functor f => Algebra f a -> Mu f -> a
cata f = f . fmap (cata f) . outF
-- Example with natural fold on String
data StrF x = Cons Char x | Nil
type Str = Mu StrF
instance Functor StrF where
fmap f (Cons a as) = Cons a (f as)
fmap _ Nil = Nil
length' :: Str -> Int
length' = cata phi where
phi (Cons a b) = 1 + b
phi Nil = 0
toMu :: [Char] -> Str
toMu (x:xs) = InF { outF = Cons x (toMu xs) }
toMu [] = InF { outF = Nil }
~~~

View file

@ -0,0 +1,26 @@
κατα-morphism: example with strings
-----------------------------------
~~~
type Algebra f a = f a -> a
data Mu f = InF { outF :: f (Mu f) }
cata :: Functor f => Algebra f a -> Mu f -> a
cata f = f . fmap (cata f) . outF
-- Example with natural fold on String
data StrF x = Cons Char x | Nil
type Str = Mu StrF
instance Functor StrF where
fmap f (Cons a as) = Cons a (f as)
fmap _ Nil = Nil
length' :: Str -> Int
length' = cata phi where
phi (Cons a b) = 1 + b
phi Nil = 0
toMu :: [Char] -> Str
toMu (x:xs) = InF { outF = Cons x (toMu xs) }
toMu [] = InF { outF = Nil }
~~~

View file

@ -0,0 +1,19 @@
κατα-morphism: example with strings
-----------------------------------
~~~
type Algebra f a = f a -> a
data Mu f = InF { outF :: f (Mu f) }
cata :: Functor f => Algebra f a -> Mu f -> a
cata f = f . fmap (cata f) . outF
type Tree = Mu TreeF
data TreeF x = Node Int [x]
instance Functor TreeF where
fmap f (Node e xs) = Node e (fmap f xs)
depth = cata phi where
phi (Node x sons) = 1 + foldr max 0 sons
~~~