Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. module FAlgebra where
  2.  
  3. import Prelude hiding (foldr, unfoldr)
  4.  
  5. -- Nat
  6. data Nat = Zero | Succ Nat deriving Show
  7.  
  8. foldn :: (x, x -> x) -> Nat -> x
  9. foldn (c, f) = mu
  10. where
  11. mu Zero = c
  12. mu (Succ n) = f (mu n)
  13.  
  14. unfoldn :: (x -> Maybe x) -> x -> Nat
  15. unfoldn psi = nu
  16. where
  17. nu x = case psi x of
  18. Nothing -> Zero
  19. Just x' -> Succ (nu x')
  20.  
  21. -- List
  22. data List a = Nil | Cons a (List a) deriving Show
  23.  
  24. foldr :: (x, a -> x -> x) -> List a -> x
  25. foldr (c, f) = mu
  26. where
  27. mu Nil = c
  28. mu (Cons x xs) = f x (mu xs)
  29.  
  30. unfoldr :: (x -> Maybe (a, x)) -> x -> List a
  31. unfoldr psi = nu
  32. where
  33. nu x = case psi x of
  34. Nothing -> Nil
  35. Just (a, x') -> Cons a (nu x')
  36.  
  37. -- Tree
  38. data Tree a = Tip a | Bin (Tree a) (Tree a) deriving Show
  39.  
  40. foldtree :: (a -> x, x -> x -> x) -> Tree a -> x
  41. foldtree (f, g) = mu
  42. where
  43. mu (Tip a) = f a
  44. mu (Bin tl tr) = g (mu tl) (mu tr)
  45.  
  46. unfoldtree :: (x -> Either a (x, x)) -> x -> Tree a
  47. unfoldtree psi = nu
  48. where
  49. nu x = case psi x of
  50. Left a -> Tip a
  51. Right (xl, xr) -> Bin (nu xl) (nu xr)
  52.  
  53. -- List^{+}
  54. data ListPlus a = Wrap a | ConsPlus a (ListPlus a) deriving Show
  55.  
  56. foldrplus :: (a -> x, a -> x -> x) -> ListPlus a -> x
  57. foldrplus (f, g) = mu
  58. where
  59. mu (Wrap a) = f a
  60. mu (ConsPlus a x) = g a (mu x)
  61.  
  62. unfoldrplus :: (x -> Either a (a, x)) -> x -> ListPlus a
  63. unfoldrplus psi = nu
  64. where
  65. nu x = case psi x of
  66. Left a -> Wrap a
  67. Right (a, x') -> ConsPlus a (nu x')
  68.  
  69. -- Snoc List
  70. data SList a = SNil | Snoc (SList a) a deriving Show
  71.  
  72. foldl :: (x, x -> a -> x) -> SList a -> x
  73. foldl (c, f) = mu
  74. where
  75. mu SNil = c
  76. mu (Snoc x a) = f (mu x) a
  77.  
  78. unfoldl :: (x -> Maybe (x, a)) -> x -> SList a
  79. unfoldl psi = nu
  80. where
  81. nu x = case psi x of
  82. Nothing -> SNil
  83. Just (x', a) -> Snoc (nu x') a
  84.  
  85. -- Snoc List^{+}
  86. data SListPlus a = SWrap a | SnocPlus (SListPlus a) a deriving Show
  87.  
  88. foldlplus :: (a -> x, x -> a -> x) -> SListPlus a -> x
  89. foldlplus (f, g) = mu
  90. where
  91. mu (SWrap a) = f a
  92. mu (SnocPlus x a) = g (mu x) a
  93.  
  94. unfoldlplus :: (x -> Either a (x, a)) -> x -> SListPlus a
  95. unfoldlplus psi = nu
  96. where
  97. nu x = case psi x of
  98. Left a -> SWrap a
  99. Right (x', a) -> SnocPlus (nu x') a
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement