Advertisement
Guest User

Untitled

a guest
Feb 15th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# Language FunctionalDependencies,MultiParamTypeClasses #-}
  2.  
  3. import Data.Functor.Apply
  4. import Data.Functor.Identity
  5. import Data.Maybe (fromJust)
  6.  
  7. class GetS_r r f | f -> r where
  8.  getS_r :: f a -> (r a,Maybe (f a))
  9.  
  10. class SetS_r r f | f -> r  where
  11.  setS_r :: (r a,Maybe (f a)) -> f a
  12.  
  13. --
  14.  
  15. type SafeState   s a = s -> (a, Maybe s)
  16. type CoSafeState s a = (a, Maybe s) -> s
  17.  
  18. unfoldSafeState :: SafeState s a -> (CoSafeState b a) -> s ->  b
  19. unfoldSafeState f c = go
  20.  where
  21.      go = c . fmap (fmap go) . f
  22.  
  23. linearDifference :: (GetS_r r t, SetS_r r' t', Apply f) => (r a -> f (r' b)) -> SafeState (t a) (f (Maybe (t' b) -> t' b))
  24. linearDifference f xs = (\(x,xs')->(fmap (curry setS_r) (f x),xs')) (getS_r xs)
  25.  
  26. traverse1Default :: (GetS_r r t, SetS_r r' t', Apply f) => (r a -> f (r' b)) -> t a -> f (t' b)
  27. traverse1Default f = unfoldSafeState (c f) g
  28. where
  29.  g :: Apply f => CoSafeState (f (t' b)) (f (Maybe (t' b) -> t' b))
  30.   g (h,Nothing) = fmap (\h' -> h' Nothing) h
  31.   g (h,Just xs) = liftF2 (\f x ->f (Just x)) h xs -- is this lifting of Just slow?
  32.  
  33. --
  34.  
  35. infixr 5 :|
  36.  
  37. data NonEmpty a = a :| NonEmpty a | End a deriving (Show,Eq, Ord)
  38.  
  39. instance GetS_r Identity NonEmpty where
  40.  getS_r (x :| xs) = (Identity x,Just xs)
  41.  getS_r (End x) = (Identity x,Nothing)
  42.  
  43. instance SetS_r Identity NonEmpty where
  44.  setS_r (Identity x,Just xs) = (x :| xs)
  45.  setS_r (Identity x,Nothing) = (End x)
  46.  
  47. --
  48.  
  49. eg :: NonEmpty Int
  50. eg = 1 :| 2 :| 3 :| End 4
  51.  
  52. test :: NonEmpty Int
  53. test = runIdentity $ traverse1Default Identity eg
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement