Advertisement
Guest User

Untitled

a guest
Aug 10th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE AllowAmbiguousTypes #-}
  2. {-# LANGUAGE FlexibleInstances #-}
  3. {-# LANGUAGE InstanceSigs #-}
  4. {-# LANGUAGE MultiParamTypeClasses #-}
  5. {-# LANGUAGE RankNTypes #-}
  6. {-# LANGUAGE TypeOperators #-}
  7. {-# LANGUAGE UndecidableInstances #-}
  8.  
  9. module Main where
  10.  
  11. import Data.Functor
  12.  
  13. main :: IO ()
  14. main = putStrLn "Hello :)"
  15.  
  16. newtype Fix f = Fix
  17.   { unFix :: f (Fix f)
  18.   }
  19.  
  20. class (Functor f, Functor g) =>
  21.       f :~> g
  22.   where
  23.   transform :: f a -> g a
  24.  
  25. instance Functor f => f :~> f where
  26.   transform = id
  27.  
  28. type Algebra f a = f a -> a
  29.  
  30. type Coalgebra f a = a -> f a
  31.  
  32. data BinTreeF e a
  33.   = Leaf e
  34.   | Branch a
  35.            a
  36.  
  37. instance Functor (BinTreeF e) where
  38.   fmap f (Leaf x) = Leaf x
  39.   fmap f (Branch x y) = Branch (f x) (f y)
  40.  
  41. k :: Algebra (BinTreeF Int) Int
  42. k (Leaf x) = x
  43. k (Branch x y) = max x y
  44.  
  45. data TreeF e a =
  46.   Tree e
  47.        [a]
  48.  
  49. instance Functor (TreeF e) where
  50.   fmap f (Tree x xs) = Tree x (fmap f xs)
  51.  
  52. h :: Algebra (TreeF Int) Int
  53. h (Tree x xs) = maximum (x : xs)
  54.  
  55. p :: Algebra (TreeF Int) Int
  56. p (Tree x xs) = x + sum xs
  57.  
  58. i :: Coalgebra (TreeF Int) (Int, [Int])
  59. i (i, []) = Tree i []
  60. i (i, x:xs) = Tree x [(i + 1, xs)]
  61.  
  62. data ExprF a
  63.   = Const Int
  64.   | Add a
  65.         a
  66.   | Mul a
  67.         a
  68.   deriving (Show)
  69.  
  70. instance Functor ExprF where
  71.   fmap f (Add x y) = Add (f x) (f y)
  72.   fmap f (Mul x y) = Mul (f x) (f y)
  73.   fmap f (Const x) = Const x
  74.  
  75. f :: Algebra ExprF Int
  76. f (Add x y) = x + y
  77. f (Mul x y) = x * y
  78. f (Const x) = x
  79.  
  80. g :: Coalgebra ExprF [Int]
  81. g [] = Const 0
  82. g [x] = Const x
  83. g (x:xs) = Add [x] xs
  84.  
  85. cata :: Functor f => Algebra f a -> Fix f -> a
  86. cata alg =
  87.   let f = alg . fmap (cata alg) . unFix
  88.    in f
  89.  
  90. ana :: Functor f => Coalgebra f a -> a -> Fix f
  91. ana coalg =
  92.   let f = Fix . fmap f . coalg
  93.    in f
  94.  
  95. hylo ::
  96.      (Functor f, Functor g, f :~> g) => Algebra g b -> Coalgebra f a -> a -> b
  97. hylo alg coalg =
  98.   let f = alg . transform . fmap f . coalg
  99.    in f
  100.  
  101. y :: Int
  102. y = hylo f g [1, 2, 3, 4, 5]
  103.  
  104. z :: Int
  105. z = hylo p i (0, [1, 2, 3, 4, 5])
  106.  
  107. c = ana i (0, [1, 2, 3, 4, 5])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement