Advertisement
Guest User

Untitled

a guest
Feb 17th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# Language RankNTypes , DefaultSignatures #-}
  2.  
  3. class Unfoldable f => Set f where
  4.  set :: (Maybe (a,f a) -> f a)
  5.  
  6. class Foldable' f => Get f where
  7. get :: (f a -> Maybe (a,f a))
  8.  
  9. class (Get f,Set f) => Stream f
  10.  
  11. --
  12.  
  13. class Foldable' f where
  14.  foldr' :: (Maybe (a,b) -> b) -> f a -> b
  15. default foldr' :: Get f => (Maybe (a,b) -> b) -> f a -> b
  16.  foldr' f xs = case get xs of
  17.                      Nothing -> f Nothing
  18.                      (Just (x,xs')) -> f (Just (x,(foldr' f xs')))
  19.                      
  20.  
  21. class Unfoldable f where
  22.  unfoldr :: s -> (s->Maybe (a,s)) -> f a
  23.  default unfoldr :: Set f => s -> (s->Maybe (a,s)) -> f a
  24.  unfoldr s fs = case fs s of
  25.                      Nothing -> set Nothing
  26.                      (Just (a,s')) ->  set (Just (a,(unfoldr s' fs)))
  27.  
  28. --
  29.  
  30. instance Get [] where
  31.  get [] = Nothing
  32.  get (x : xs) = Just (x,xs)
  33.  
  34. instance Set [] where
  35.  set Nothing = []
  36.  set (Just (x,xs)) = x : xs
  37.  
  38. instance Stream []
  39.  
  40. instance Foldable' []
  41.  
  42. instance Unfoldable []
  43.  
  44. --
  45.  
  46. data Church a = Church {runChurch :: forall b. ((Maybe (a,b) -> b) -> b)}
  47.  
  48. instance Set Church where
  49. set Nothing = Church (\f -> f Nothing)
  50. set (Just (x,(Church xs))) = Church (\set' -> set' (Just (x,(xs set'))))
  51.  
  52. instance Unfoldable Church
  53.  
  54. data CoChurch' f a = CoChurch' {runCoChurch' :: Set f => (CoChurch' f a->Maybe (a,CoChurch' f a)) -> f a}
  55.  
  56. instance Set f => Set (CoChurch' f) where
  57.  set Nothing = CoChurch' (\get' -> set Nothing)
  58.  set (Just (x,(CoChurch' xs))) = CoChurch' (\get' -> set (Just (x,xs get')))
  59.   where
  60.    get'' get' x c = Just (x,c)
  61.  
  62. instance Set f => Unfoldable (CoChurch' f)
  63.  
  64. --
  65.  
  66. build :: Set f => Church a -> f a
  67. build (Church f) = f set
  68.  
  69. cobuild :: Set f => CoChurch' f a -> f a
  70. cobuild (CoChurch' f) = f undefined
  71.  
  72. --
  73.  
  74. loop :: Set f => s -> (s -> Maybe (a,s)) -> f a
  75. loop s = build . unfoldr s
  76.  
  77. testLoop :: [ Char ]
  78. testLoop = loop eg (\y -> case y of [] -> Nothing; (x:xs) -> Just (x,xs))
  79.  
  80. coLoop :: (Get f,Set f') => f a -> (forall s. s -> Maybe (a,s)) -> f' a
  81. coLoop xs f = cobuild $ unfoldr xs get
  82.  
  83. testCoLoop :: [ Char ]
  84. testCoLoop = coLoop eg undefined
  85.  
  86. eg = "hello world"
  87.  
  88. {-
  89. *Main> testLoop
  90. "hello world"
  91. *Main> testCoLoop
  92. "hello world"
  93. -}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement