Advertisement
Guest User

Untitled

a guest
Feb 26th, 2013
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1.  
  2. — explicit type recursion with functors and catamorphisms
  3.  
  4. newtype Mu f = In (f (Mu f))
  5.  
  6. unIn (In x) = x
  7.  
  8. cata phi = phi . fmap (cata phi) . unIn
  9.  
  10. — base functor and data type for natural numbers,
  11. — using locally-defined «eliminators»
  12.  
  13. data N c = Z | S c
  14.  
  15. instance Functor N where
  16. fmap g Z = Z
  17. fmap g (S x) = S (g x)
  18.  
  19. type Nat = Mu N
  20.  
  21. zero = In Z
  22. suck n = In (S n)
  23.  
  24. add m = cata phi where
  25. phi Z = m
  26. phi (S f) = suck f
  27.  
  28. mult m = cata phi where
  29. phi Z = zero
  30. phi (S f) = add m f
  31.  
  32. — explicit products and their functorial action
  33.  
  34. data Prod e c = Pair c e
  35.  
  36. outl (Pair x y) = x
  37. outr (Pair x y) = y
  38.  
  39. fork f g x = Pair (f x) (g x)
  40.  
  41. instance Functor (Prod e) where
  42. fmap g = fork (g . outl) outr
  43.  
  44. — comonads, the categorical «opposite» of monads
  45.  
  46. class Functor n => Comonad n where
  47. extr :: n a -> a
  48. dupl :: n a -> n (n a)
  49.  
  50. instance Comonad (Prod e) where
  51. extr = outl
  52. dupl = fork id outr
  53.  
  54.  
  55. gcata :: (Functor f, Comonad n) =>
  56. (forall a. f (n a) -> n (f a))
  57. -> (f (n c) -> c) -> Mu f -> c
  58.  
  59. gcata dist phi = extr . cata (fmap phi . dist . fmap dupl)
  60.  
  61. zygo chi = gcata (fork (fmap outl) (chi . fmap outr))
  62.  
  63. para :: Functor f => (f (Prod (Mu f) c) -> c) -> Mu f -> c
  64. para = zygo In
  65.  
  66. fac = para phi where
  67. phi Z = suck zero
  68. phi (S (Pair f n)) = mult f (suck n)
  69.  
  70. int = cata phi where
  71. phi Z = 0
  72. phi (S f) = 1 + f
  73.  
  74. instance Show (Mu N) where
  75. show = show . int
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement