Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 22nd, 2012  |  syntax: None  |  size: 2.15 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. -- probably broken
  2. -- no polymorphic kind signatures, which may make things cleaner
  3. {-# OPTIONS_GHC -Wall #-}
  4. {-# LANGUAGE DataKinds #-}
  5. {-# LANGUAGE PolyKinds #-}
  6. {-# LANGUAGE ConstraintKinds #-}
  7. {-# LANGUAGE KindSignatures #-}
  8. {-# LANGUAGE TypeFamilies #-}
  9. {-# LANGUAGE GADTs #-}
  10. {-# LANGUAGE TypeOperators#-}
  11. {-# LANGUAGE ExplicitNamespaces #-}
  12. {-# LANGUAGE ScopedTypeVariables #-}
  13. {-# LANGUAGE FlexibleContexts #-}
  14. {-# LANGUAGE RecordWildCards #-}
  15. {-# LANGUAGE ViewPatterns #-}
  16.  
  17. import GHC.TypeLits
  18. import Unsafe.Coerce (unsafeCoerce)
  19.  
  20. -- Proxies and polymorphic kinds
  21.  
  22. data Proxy p = Proxy
  23.  
  24. f :: SingI n => Proxy n -> SingRep n
  25. f (_ :: Proxy n) = fromSing (sing :: Sing n)
  26.  
  27. test1 :: IO ()
  28. test1 = mapM_ putStrLn [show $ f n, show $ f s]
  29.   where n = Proxy :: Proxy 4096
  30.         s = Proxy :: Proxy "lol"
  31.  
  32. -- Vectors
  33.  
  34. data Vec (n :: Nat) (a :: *) where
  35.   Nil :: Vec 0 a
  36.   Cons :: a -> (Vec n a) -> Vec (n+1) a
  37.  
  38. instance Show a => Show (Vec n a) where
  39.   show Nil         = "Nil"
  40.   show (Cons x xs) = "Cons " ++ show x ++ " (" ++ show xs ++ ")"
  41.  
  42. {--}
  43. vappend :: (m+n) ~ r => Vec n a -> Vec m a -> Vec r a
  44. vappend Nil Nil                = unsafeCoerce $ Nil
  45. vappend Nil z@(Cons{})         = unsafeCoerce $ z
  46. vappend z@(Cons{}) Nil         = unsafeCoerce $ z
  47. vappend (Cons x xs) y@(Cons{}) = unsafeCoerce $ Cons x (vappend xs y)
  48. --}
  49.  
  50. -- Pointers
  51.  
  52. newtype IntBound (n :: Nat) = IntBound { unIntBound :: Sing n }
  53.  
  54.  
  55. -- A pointer pointing to 'w' words of memory, each
  56. -- 'b' bits wide
  57. data Ptr (w :: Nat) (b :: Nat) = Ptr
  58. type PtrBounds w b i j = (SingI i, SingI j, SingI w, SingI b, i <= w, j <= (2^b))
  59.  
  60.  
  61. new_memory :: (SingI w, SingI b) => IO (Ptr w b)
  62. new_memory = return Ptr
  63.  
  64. bound :: SingI (n :: Nat) => Integer -> Maybe (IntBound n)
  65. bound i = maybe Nothing (Just . IntBound) $ singThat (>= i)
  66.  
  67.  
  68. write_memory :: (PtrBounds w b i j) => Ptr w b -> IntBound i -> IntBound j -> IO ()
  69. write_memory _ a1 a2 = do
  70.   -- write ptr  
  71.  
  72.   return ()
  73.   where i = fromSing $ unIntBound a1
  74.         j = fromSing $ unIntBound a2
  75.  
  76. test2 :: IO ()
  77. test2 = do
  78.   m <- new_memory :: IO (Ptr 20 8)
  79.   let Just i = bound 5  :: Maybe (IntBound 5)
  80.       Just j = bound 10 :: Maybe (IntBound 10)
  81.   write_memory m i j
  82.   return ()