Advertisement
Guest User

Untitled

a guest
Sep 28th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. {-# LANGUAGE TypeFamilies #-}
  2. {-# LANGUAGE RankNTypes #-}
  3.  
  4. data Z
  5. data S n
  6.  
  7. type family Pred n
  8. type instance Pred (S n) = n
  9.  
  10. newtype Vec n a = Vec {
  11. foldV' :: forall u. forall b.
  12. u Z b ->
  13. (forall k. a ->
  14. u k b ->
  15. u (S k) b) ->
  16. u n b
  17. }
  18.  
  19. newtype Const n a = C { unC :: a }
  20.  
  21. c2 = C . C
  22. unC2 = unC . unC
  23.  
  24. foldCV z c = unC . foldV (C z) (\x (C xs) -> C $ c x xs)
  25.  
  26. foldV ::
  27. u Z b ->
  28. (forall k. a ->
  29. u k b ->
  30. u (S k) b) ->
  31. Vec n a -> u n b
  32. foldV z c v = foldV' v z c
  33.  
  34. nilV = Vec $ \z c -> z
  35.  
  36. consV :: a -> Vec n a -> Vec (S n) a
  37. consV a v = Vec $ \z c -> c a (foldV z c v)
  38.  
  39. (@:) = consV
  40.  
  41. infixr @:
  42.  
  43. newtype TailV n a = TailV { unwrapTV :: (Vec (Pred n) a, Vec n a) }
  44.  
  45. tailV :: Vec (S n) a -> Vec n a
  46. tailV = fst . unwrapTV . foldV (TailV (undefined, nilV)) step
  47. where
  48. step :: a -> TailV k a -> TailV (S k) a
  49. step x (TailV (_, xs)) = TailV (xs, x `consV` xs)
  50.  
  51. headV :: Vec (S n) a -> a
  52. headV = foldCV undefined const
  53.  
  54. unconsV v = (headV v, tailV v)
  55.  
  56. instance Show a => Show (Vec n a) where
  57. show = unC2 . foldV (c2 "nilV") (\x xs -> c2 $ show x ++ " @: " ++ unC2 xs)
  58.  
  59. main :: IO ()
  60. main = putStrLn . show . unconsV $ 1 @: 2 @: 3 @: 4 @: nilV
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement