updated cata
This commit is contained in:
parent
b00276eb7b
commit
e79bee6398
3 changed files with 84 additions and 0 deletions
39
categories/30_How/300_Catamorphisms/030.md
Normal file
39
categories/30_How/300_Catamorphisms/030.md
Normal 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 }
|
||||
~~~
|
26
categories/30_How/300_Catamorphisms/040.md
Normal file
26
categories/30_How/300_Catamorphisms/040.md
Normal 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 }
|
||||
~~~
|
19
categories/30_How/300_Catamorphisms/050.md
Normal file
19
categories/30_How/300_Catamorphisms/050.md
Normal 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
|
||||
~~~
|
Loading…
Reference in a new issue