Advertisement
nrnrnr

A touch of GADT

Nov 23rd, 2013
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE GADTs, KindSignatures #-}
  2.  
  3. module E2
  4.        ( Value(..), Expr(..)
  5.        )
  6. where
  7.  
  8. import System.IO
  9.  
  10. data In
  11. data Out
  12. data InOut
  13. data Exe
  14.  
  15. data Mode :: * -> * where
  16.   In :: Mode In
  17.   Out :: Mode Out
  18.   InOut ::  Mode InOut
  19.   Exe :: Mode Exe
  20.  
  21. data OpenFile a = OpenFile Handle
  22.  
  23. data Value a where
  24.   File :: FilePath -> Mode a -> Value (Mode a)
  25.   Double :: Double -> Value Double
  26.   Int :: Integer -> Value Integer
  27.   String :: String -> Value String
  28.   Handle :: Handle -> Mode a -> Value (OpenFile a)
  29.  
  30. -- probably deBruijn is the way to go; see
  31. -- http://www.cse.unsw.edu.au/~chak/haskell/term-conv/
  32.  
  33. data Ix env t where
  34.   ZeroIx ::             Ix (env, t) t
  35.   SuccIx :: Ix env t -> Ix (env, s) t
  36.  
  37.  
  38.  
  39. data Expr :: * -> * -> * where  -- context, type
  40.   RunTo :: Expr c (Mode Exe) -> Expr c [String] -> Expr c (Mode Out) -> Expr c (IO ())
  41.   Open :: Expr c (Mode a) -> Expr c (IO (OpenFile a))
  42.   Apply :: Expr c (a -> b) -> Expr c a -> Expr c b
  43.   Lambda :: Expr (c, tau) b -> Expr c (tau -> b) -- maybe de Bruijn?
  44.   Var :: Ix c a -> Expr c a
  45.   Lit :: Value a -> Expr c a
  46.  
  47.  
  48. -----------------------------------------------------
  49.   -- more from M. Chakravarty
  50.  
  51.   -- Valuation for a type environment
  52. --
  53. data Val env where
  54.   Empty :: Val ()
  55.   Push  :: Val env -> t -> Val (env, t)
  56.  
  57. -- Projection of a value from a valuation using a de Bruijn index
  58. --
  59. prj :: Ix env t -> Val env -> t
  60. prj ZeroIx      (Push val v) = v
  61. prj (SuccIx ix) (Push val _) = prj ix val
  62.  
  63. run :: Val context -> Expr context a -> a
  64. run rho (Var ix) = prj ix rho
  65. run rho (Apply f x) = run rho f (run rho x)  
  66. run rho (Lambda body) = \x -> run (Push rho x) body
  67.  
  68. class Writeable a where -- File value constructors must be private
  69.   openOut :: Value (Mode a) -> IO Handle
  70.  
  71. instance Writeable Out where
  72.   openOut (File s Out) = openFile s WriteMode
  73.  
  74. instance Writeable InOut where
  75.   openOut (File s InOut) = openFile s WriteMode
  76.  
  77.  
  78. type Name = String
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement