code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE DeriveGeneric #-} module App.Roster.Types ( TeamRoster(..) , current , next , addPersonToRoster , increaseRosterIndex , decreaseRosterIndex , replaceInCurrent , replaceInNext) where import App.Roster.RosterGeneration (generateNextRoster, generatePreviousRoster) import App.Helper.Lists (replaceElem) import Data.Aeson (FromJSON, ToJSON) import Data.List import GHC.Generics data TeamRoster = TeamRoster { teamName :: String , currentRoster :: [(String,String)] , nextRoster :: [(String,String)] , pairIndex :: Int } deriving ( Generic, Show ) instance ToJSON TeamRoster instance FromJSON TeamRoster instance Eq TeamRoster where TeamRoster n1 _ _ _ == TeamRoster n2 _ _ _ = n1 == n2 -- Functions on TeamRoster current :: TeamRoster -> (String, String) current roster = let pairs = safeCurrentRoster roster idx = pairIndex roster in pairs !! idx -- TODO dont use !!. It's risky. addPersonToRoster :: TeamRoster -> String -> TeamRoster addPersonToRoster roster personName = case findOddPair $ currentRoster roster of Just oddPair -> let updatedPair = replaceEmpty oddPair personName updatedRoster = updatePair oddPair updatedPair roster newNext = generateNextRoster $ currentRoster updatedRoster in updatedRoster {nextRoster = newNext} Nothing -> let newCurrent = (currentRoster roster)++[(personName, "")] newNext = generateNextRoster $ newCurrent in roster {currentRoster = newCurrent, nextRoster = newNext} replaceInCurrent :: TeamRoster -> String -> String -> TeamRoster replaceInCurrent roster oldName newName | oldName == fst (current roster) = let newCurrent = (newName, snd (current roster)) oldCurrent = current roster in updatePair oldCurrent newCurrent roster | oldName == snd (current roster) = let newCurrent = (fst (current roster), newName) oldCurrent = current roster in updatePair oldCurrent newCurrent roster | otherwise = roster replaceInNext :: TeamRoster -> String -> String -> TeamRoster replaceInNext roster oldName newName | oldName == fst (next roster) = let newVal = (newName, snd (next roster)) oldVal = next roster in updatePair oldVal newVal roster | oldName == snd (next roster) = let newVal = (fst (next roster), newName) oldVal = next roster in updatePair oldVal newVal roster | otherwise = roster next :: TeamRoster -> (String, String) next roster = let idx = 1 + pairIndex roster in getPair idx roster increaseRosterIndex :: TeamRoster -> TeamRoster increaseRosterIndex roster | (pairIndex roster) + 1 < lengthCurrentRoster roster = roster {pairIndex = (pairIndex roster) + 1} | otherwise = calculateNextRoster roster decreaseRosterIndex :: TeamRoster -> TeamRoster decreaseRosterIndex roster | (pairIndex roster) - 1 >= 0 = roster {pairIndex = (pairIndex roster) - 1} | otherwise = calculatePreviousRoster roster -- PRIVATE updatePair :: (String, String) -> (String, String) -> TeamRoster -> TeamRoster updatePair old new roster = let newCurrent = replaceElem old new (currentRoster roster) newNext = replaceElem old new (nextRoster roster) in roster {currentRoster = newCurrent, nextRoster = newNext} calculateNextRoster :: TeamRoster -> TeamRoster calculateNextRoster roster = let newCurrent = nextRoster roster newNext = generateNextRoster newCurrent in roster {currentRoster = newCurrent, nextRoster = newNext, pairIndex = 0} calculatePreviousRoster :: TeamRoster -> TeamRoster calculatePreviousRoster roster = let newNext = currentRoster roster newCurrent = generatePreviousRoster $ newNext newIdx = (lengthCurrentRoster roster) - 1 in roster {currentRoster = newCurrent, nextRoster = newNext, pairIndex = newIdx} getPair :: Int -> TeamRoster -> (String, String) getPair idx roster | idx < lengthCurrentRoster roster = (safeCurrentRoster roster) !! idx -- TODO dont use !!. It's risky. | otherwise = (safeNextRoster roster) !! (idx - (lengthCurrentRoster roster)) lengthCurrentRoster :: TeamRoster -> Int lengthCurrentRoster roster = length (safeCurrentRoster roster) filterOutEmpty :: [(String, String)] -> [(String, String)] filterOutEmpty list = let nonEmpty (s1, s2) = s1 /= "" && s2 /= "" in filter nonEmpty list findOddPair :: [(String, String)] -> Maybe (String, String) findOddPair list = let oddPair (s1, s2) = s1 == "" || s2 == "" in find oddPair list -- Current roster with no empty tuples safeCurrentRoster :: TeamRoster -> [(String, String)] safeCurrentRoster roster = filterOutEmpty $ currentRoster roster safeNextRoster :: TeamRoster -> [(String, String)] safeNextRoster roster = filterOutEmpty $ nextRoster roster replaceEmpty :: (String, String) -> String -> (String, String) replaceEmpty pair pName | "" == fst pair = (pName, snd pair) | "" == snd pair = ((fst pair), pName) | otherwise = pair
afcastano/cafe-duty
src/App/Roster/Types.hs
bsd-3-clause
6,268
0
14
2,266
1,557
813
744
101
2
{-# LANGUAGE TemplateHaskell #-} import Data.Angle import Debug.Trace import Lib import Object (Point(..), Vector(..), Ray(..), march, distanceFrom', Form(..)) import qualified Params import qualified System.Random as Random import Test.QuickCheck (quickCheck, quickCheckAll, (==>)) import qualified Test.QuickCheck as T import Triple import Util tolerance :: Double tolerance = 1e-8 (~=) :: Double -> Double -> Bool (~=) = aeq tolerance (^~=) :: Vec3 -> Vec3 -> Bool (^~=) = vecAeq tolerance propCross1 :: Vec3 -> Vec3 -> T.Property propCross1 v1 v2 = not (any ((0 ~=) . norm2) [v1, v2]) ==> ((v1 `dot` crossProduct) ~= 0) && ((v2 `dot` crossProduct) ~= 0) where crossProduct = v1 `cross` v2 propCross2 :: Vec3 -> Bool propCross2 v = 0 `cross` v ^~= pure 0 && v `cross` 0 ^~= pure 0 propNorm2 :: Bool propNorm2 = norm2 (Triple 3 4 5) ~= 7.0710678118654755 propNormalize1 :: Vec3 -> T.Property propNormalize1 vec = not (norm2 vec ~= 0) ==> norm2 (normalize vec) ~= 1 && x ~= y && y ~= z where Triple x y z = vec / (normalize vec) propNormalize2 :: Bool propNormalize2 = norm2 (normalize $ Triple 0 0 0) == 0 sphericalRelations :: Double -> Double -> Double -> Double -> Double -> Degrees Double -> Degrees Double -> Bool sphericalRelations x y z x' y' theta phi = x' ~= cosine phi && y' ~= sine phi && (y / x) ~= tangent phi && ((x ** 2) + (y ** 2)) ~= ((sine theta) ** 2) && z ~= cosine theta && (((x ** 2) + (y ** 2)) / (z ** 2)) ~= ((tangent theta) ** 2) propToSpherical1 :: Vec3 -> T.Property propToSpherical1 vec3 = not (norm2 vec3 ~= 0) ==> sphericalRelations x y z x' y' theta phi where Triple x y z = normalize vec3 Triple x' y' _ = normalize $ Triple x y 0 (theta, phi) = toSphericalCoords vec3 propFromSpherical1 :: Double -> Double -> T.Property propFromSpherical1 theta phi = all ((0, False, 180, True) `contains`) [theta, phi] ==> sphericalRelations x y z x' y' theta' phi' where [theta', phi'] = map Degrees [theta, phi] Triple x y z = fromSphericalCoords theta' phi' :: Vec3 Triple x' y' _ = normalize $ Triple x y 0 propFromSpherical2 :: Bool propFromSpherical2 = fromSphericalCoords 0 0 ^~= Triple 0 0 1 propToSpherical2 :: Bool propToSpherical2 = not $ any isNaN [phi, theta] where (Degrees phi, Degrees theta) = toSphericalCoords (pure 0) propSpherical1 :: Double -> Double -> T.Property propSpherical1 theta phi = (0, False, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> Degrees theta ~= theta' && Degrees phi ~= phi' where (~=) = aeq 1e-13 (theta', phi') = toSphericalCoords $ fromSphericalCoords (Degrees theta) (Degrees phi) propSpherical2 :: Vec3 -> T.Property propSpherical2 vec = not (norm2 vec ~= 0) ==> (normalize vec) ^~= vec' where (theta, phi) = toSphericalCoords vec vec' = fromSphericalCoords theta phi propRotateAbs1 :: Double -> Double -> T.Property propRotateAbs1 theta phi = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> (rotateAbs (Triple 0 0 1) theta' phi') ^~= (fromSphericalCoords theta' phi') where [theta', phi'] = map Degrees [theta, phi] propRotateAbs2 :: Double -> Double -> Vec3 -> T.Property propRotateAbs2 theta phi vector = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> norm2 vector ~= norm2 vector' where [theta', phi'] = map Degrees [theta, phi] vector' = rotateAbs vector theta' phi' propRotateAbs3 :: Double -> Double -> Vec3 -> Vec3 -> T.Property propRotateAbs3 theta phi vector1 vector2 = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> (vector1 `dot` vector2) ~= (vector1' `dot` vector2') where [theta', phi'] = map Degrees [theta, phi] [vector1', vector2'] = map (\v -> rotateAbs v theta' phi') [vector1, vector2] propRotateRel :: Double -> Double -> Vec3 -> T.Property propRotateRel theta phi vector = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi && not (norm2 vector ~= 0) ==> cosine theta' ~= (normalize vector `dot` normalize vector') where [theta', phi'] = map Degrees [theta, phi] vector' = rotateRel theta' phi' vector propSpecular :: Vec3 -> Vec3 -> T.Property propSpecular vector normal = not (any ((0 ~=) . norm2) [vector, normal]) ==> -- angle of incidence equals angle of reflection (normalize (-vector) `dot` normalize normal) ~= (normalize vector' `dot` normalize normal) && (projOntoSurface vector) ^~= (projOntoSurface vector') where (vector', _) = specular (Random.mkStdGen 0) 0 vector normal normal' = normalize normal projOntoSurface v = v - fmap (v `dot` normal' *) normal' defaultRay = Ray { _origin = Point $ pure 0 , _vector = Vector $ pure 0 , _gen = Random.mkStdGen 0 , _lastStruck = Nothing } propDistanceFrom' :: Vec3 -> Vec3 -> Vec3 -> Vec3 -> T.Property propDistanceFrom' origin vector normal point = not (any ((0 ~=) . norm2) [origin, vector, normal, point]) ==> (intersection - point) `dot` normal ~= 0 where intersection = march ray distance ray = defaultRay {_origin = Point origin, _vector = Vector vector} Just distance = distanceFrom' ray $ InfinitePlane (Point point) (Vector normal) propRandomRangeList :: Float -> Float -> Float -> Float -> Int -> T.Property propRandomRangeList l1 h1 l2 h2 seed = l1 > h1 && l2 > h2 ==> fst (randomRangeList gen [(l1, h1), (l2, h2)]) == [o1, o2] where gen = Random.mkStdGen seed (o1, gen') = Random.randomR (l1, h1) gen :: (Float, Random.StdGen) (o2, gen'') = Random.randomR (l2, h2) gen' :: (Float, Random.StdGen) main = do putStrLn "propCross1" quickCheck propCross1 putStrLn "propCross2" quickCheck propCross2 putStrLn "propRandomRangeList" quickCheck propRandomRangeList putStrLn "propDistanceFrom'" quickCheck propDistanceFrom' putStrLn "propNormalize1" quickCheck propNormalize1 putStrLn "propRotateAbs1" quickCheck propRotateAbs1 putStrLn "propRotateAbs2" quickCheck propRotateAbs2 putStrLn "propRotateAbs3" quickCheck propRotateAbs3 putStrLn "propRotateRel" quickCheck propRotateRel putStrLn "propSpherical1" quickCheck propSpherical1 putStrLn "propSpherical2" quickCheck propSpherical2 putStrLn "propToSpherical1" quickCheck propToSpherical1 putStrLn "propToSpherical2" quickCheck propToSpherical2 putStrLn "propFromSpherical1" quickCheck propFromSpherical1 putStrLn "propFromSpherical2" quickCheck propFromSpherical2 putStrLn "propSpecular" quickCheck propSpecular -- one offs putStrLn "propNorm2" quickCheck propNorm2 putStrLn "propNormalize2" quickCheck propNormalize2
lobachevzky/pathtracer
test/Spec.hs
bsd-3-clause
6,754
0
16
1,370
2,563
1,354
1,209
-1
-1
module Sexy.Classes.Functor (Functor(..)) where class Functor f where (<$>) :: (a -> b) -> f a -> f b (<$) :: a -> f b -> f a a <$ fb = (\_ -> a) <$> fb
DanBurton/sexy
src/Sexy/Classes/Functor.hs
bsd-3-clause
161
0
9
45
97
53
44
5
0
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE GADTs #-} module GDAL.Plugin.Compiler ( CompilerConfig (..) , Compiler , Result (..) , startCompilerWith , startCompiler , stopCompiler , compile -- * Re-exports , HscTarget (..) , def ) where import Control.Concurrent import Control.Exception ( SomeException ) import Control.Monad (void, forever) import Control.Monad.IO.Class ( MonadIO (..) ) import Data.Char (isDigit) import Data.Text (Text) import Data.String (fromString) import qualified Data.Text.Lazy as LT import Data.Text.Lazy.Builder (Builder, toLazyText) import Data.IORef (IORef, newIORef, writeIORef, readIORef, modifyIORef) import Data.Typeable (Typeable, typeOf) import Data.Monoid (mempty, mappend) import Data.Default (Default(..)) import GHC hiding (importPaths) import GHC.Paths (libdir) import ErrUtils as GHC import Exception ( ExceptionMonad, gtry, gmask ) import Outputable as GHC hiding (parens) import DynFlags as GHC import GHC.Exts (unsafeCoerce#) data Compiler = Compiler { compilerTid :: ThreadId , compilerChan :: Chan Request } data CompilerConfig = CompilerConfig { cfgLibdir :: FilePath , cfgImports :: [String] , cfgSearchPath :: [FilePath] , cfgOptions :: [String] , cfgSafeModeOn :: Bool , cfgVerbosity :: Int , cfgBuildDir :: FilePath , cfgTarget :: HscTarget } deriving Show instance Default CompilerConfig where def = CompilerConfig { cfgLibdir = libdir , cfgImports = [] , cfgSearchPath = ["."] , cfgOptions = defaultGhcOptions , cfgSafeModeOn = True , cfgVerbosity = 0 , cfgBuildDir = "gdal-hs-build" , cfgTarget = HscAsm } data Request where Compile :: forall a. Typeable a => [String] -> String -> MVar (Result a) -> Request type CompilerMessages = Text data Result a = Success a CompilerMessages | Failure SomeException CompilerMessages deriving Show startCompiler :: IO Compiler startCompiler = startCompilerWith def startCompilerWith :: CompilerConfig -> IO Compiler startCompilerWith cfg = do chan <- newChan tid <- forkIO (compilerThread chan cfg) return (Compiler tid chan) stopCompiler :: Compiler -> IO () stopCompiler = killThread . compilerTid compile :: forall a. Typeable a => Compiler -> [String] -> String -> IO (Result a) compile comp targets code = do resRef <- newEmptyMVar writeChan (compilerChan comp) (Compile targets code resRef) takeMVar resRef compilerThread :: Chan Request -> CompilerConfig -> IO () compilerThread chan cfg = do logRef <- newIORef mempty runGhc (Just (cfgLibdir cfg)) $ do dflags <- getSessionDynFlags let dflags' = (if not isInterpreted && GHC.dynamicGhc then addOptl "-lHSrts_thr-ghc8.2.1" --FIXME: Avoid hard-code . dynamicTooMkDynamicDynFlags else id) $ dflags { mainFunIs = Nothing , safeHaskell = if cfgSafeModeOn cfg then Sf_Safe else Sf_None , ghcLink = LinkInMemory , ghcMode = CompManager , hscTarget = cfgTarget cfg , ways = ways dflags ++ [WayThreaded | not isInterpreted] , importPaths = cfgSearchPath cfg , log_action = mkLogHandler logRef , verbosity = cfgVerbosity cfg , objectDir = Just (cfgBuildDir cfg) , stubDir = Just (cfgBuildDir cfg) , hiDir = Just (cfgBuildDir cfg) } isInterpreted = cfgTarget cfg == HscInterpreted setGhcOptions dflags' (cfgOptions cfg) forever $ do req <- liftIO (readChan chan) case req of Compile targets code resRef -> gmask $ \restore -> do -- gmask to make sure we're not interrupted before putting the result -- in the mvar so the requester does not hang (or throw a -- "blocked indefinetely on an mvar" exception) (eRes, msgs) <- capturingMessages logRef restore $ compileTargets cfg targets code liftIO . putMVar resRef $ case eRes of Right r -> Success r msgs Left e -> Failure e msgs capturingMessages :: (MonadIO m, ExceptionMonad m) => IORef Builder -> (m a -> m a) -> m a -> m (Either SomeException a, CompilerMessages) capturingMessages logRef restore act = do r <- gtry (restore act) liftIO $ do msgs <- LT.toStrict . toLazyText <$> readIORef logRef writeIORef logRef mempty return (r, msgs) defaultGhcOptions :: [String] defaultGhcOptions = [ "-fwarn-incomplete-patterns" , "-fwarn-incomplete-uni-patterns" , "-funbox-strict-fields" , "-Wall" , "-O" --, "-fexpose-all-unfoldings" --, "-funfolding-use-threshold500" --, "-funfolding-keeness-factor500" ] compileTargets :: forall a. Typeable a => CompilerConfig -> [String] -> String -> Ghc a compileTargets cfg targets code = do liftIO rts_revertCAFs -- make sure old modules can be unloaded setTargets =<< mapM (`guessTarget` Nothing) targets void $ load LoadAllTargets importModules (cfgImports cfg ++ targets) unsafeCoerce# <$> compileExpr (parens code ++ " :: " ++ show (typeOf (undefined :: a))) importModules:: [String] -> Ghc () importModules = GHC.setContext . map (GHC.IIDecl . import_) where import_ name = ( GHC.simpleImportDecl . GHC.mkModuleName $ name ) { GHC.ideclQualified = False } -- -- |stolen from hint parens :: String -> String parens s = concat ["(let {", foo, " =\n", s, "\n;} in ", foo, ")"] where foo = "e_1" ++ filter isDigit s mkLogHandler :: IORef Builder -> DynFlags -> t -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO () mkLogHandler r df _ severity src style msg = let renderErrMsg = GHC.showSDoc df errorEntry = mkGhcError renderErrMsg severity src style msg in modifyIORef r (`mappend` mappend errorEntry "\n") mkGhcError :: (GHC.SDoc -> String) -> GHC.Severity -> GHC.SrcSpan -> GHC.PprStyle -> GHC.MsgDoc -> Builder mkGhcError render severity src_span style msg = fromString niceErrMsg where niceErrMsg = render . GHC.withPprStyle style $ GHC.mkLocMessage severity src_span msg addOptl :: String -> DynFlags -> DynFlags addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s}) alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags alterSettings f dflags = dflags { settings = f (settings dflags) } setGhcOptions :: DynFlags -> [String] -> Ghc () setGhcOptions old_flags opts = do (new_flags,_not_parsed) <- pdf old_flags opts void $ GHC.setSessionDynFlags (updateWays new_flags) where pdf d = fmap firstTwo . GHC.parseDynamicFlags d . map GHC.noLoc firstTwo (a,b,_) = (a, map GHC.unLoc b) foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
meteogrid/gdal-plugin-hs
src/GDAL/Plugin/Compiler.hs
bsd-3-clause
7,293
0
24
2,014
1,988
1,072
916
178
4
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} module Main where import Control.Applicative hiding (empty) import Control.Monad.Reader -- import Data.Generics.PlateData import System.Console.CmdArgs import System.Environment import System.IO import Text.Keepalived main :: IO () main = do n <- getProgName m <- cmdArgs (n ++ " version 0.0.1") [verify, dump] v <- verbosity runApp mainApp (AppConf m v) -- * Application types newtype App a = App { runA :: ReaderT AppConf IO a } deriving (Functor, Monad, MonadIO, MonadReader AppConf) data AppConf = AppConf { appMode :: KcMode , appVerb :: Verbosity } deriving Show runApp :: App a -> AppConf -> IO a runApp a = runReaderT (runA a) . fillInFiles where fillInFiles (AppConf m v) | files m == [] = AppConf (m { files = ["/etc/keepalived/keepalived.conf"] }) v | otherwise = AppConf m v -- * App implementations mainApp :: App () mainApp = do m <- asks appMode case m of Verify _ -> verifyApp Dump _ -> dumpApp -- Search _ _ -> searchApp -- List _ _ -> listApp verifyApp :: App () verifyApp = do m <- asks appMode parseApp (files m) msg (hPutStr stderr "lexical/syntactic verification: ") >> okApp dumpApp :: App () dumpApp = do AppConf m _ <- local (\c -> c { appVerb = Verbose }) ask parseApp (files m) >>= msg . mapM_ print {- TODO searchApp :: App () searchApp = do m <- asks appMode cs <- parseApp (files m) case target m of VRID _ -> const noopApp cs VIP _ -> const noopApp cs _ -> const noopApp cs listApp :: App () listApp = do m <- asks appMode cs <- parseApp (files m) case target m of VRID _ -> const noopApp cs VIP _ -> const noopApp cs _ -> const noopApp cs listVRID :: Data a => a -> [(Vrid, [Ipaddress])] listVRID x = [ (vrid vi, virtualIpaddress vi ++ virtualIpaddressExcluded vi) | TVrrpInstance vi <- universeBi x ] listVIP :: Data a => a -> [Ipaddress] listVIP x = concat [ virtualIpaddress vi ++ virtualIpaddressExcluded vi | TVrrpInstance vi <- universeBi x ] -} noopApp :: App () noopApp = return () -- * Util Apps parseApp :: [FilePath] -> App [KeepalivedConf] parseApp fs = do c <- forM fs $ \f -> do msg $ hPutStrLn stderr $ "parsing " ++ f liftIO $ parseFromFile f verbMsg $ mapM_ print c return c msg :: IO a -> App () msg io = do v <- asks appVerb case v of Quiet -> return () _ -> liftIO io >> return () verbMsg :: IO a -> App () verbMsg io = do v <- asks appVerb case v of Verbose -> liftIO io >> return () _ -> return () okApp :: App () okApp = msg $ hPutStrLn stderr "OK" -- * Command-line parameters data KcMode = Verify { files :: [FilePath] } | Dump { files :: [FilePath] } -- | Search { files :: [FilePath], target :: Target } -- | List { files :: [FilePath], target :: Target } deriving (Data, Typeable, Show, Eq) data Target = VRID Int | VIP String | RIP String deriving (Data, Typeable, Show, Eq) verify :: Mode KcMode verify = mode $ Verify { files = def &= args } &= text "Verify configuration files." & defMode dump :: Mode KcMode dump = mode $ Dump { files = def &= args } &= text "Dump configuration files." {- TODO search :: Mode KcMode search = mode $ Search { target = enum (VRID def) [ VRID def &= text "Search VRID (0-255)" , VIP "192.168.0.1" &= text "Search virtual IP addresses" , RIP "192.168.0.1" &= text "Search real IP addresses" ] , files = defConf &= typFile & args } &= text "Search (VRID|VIP|RIP) from configuration files." list :: Mode KcMode list = mode $ List { target = enum (VRID def) [ VRID def &= text "List VRID (0-255)" , VIP "192.168.0.1" &= text "List virtual IP addresses" , RIP "192.168.0.1" &= text "List real IP addresses" ] , files = defConf &= typFile & args } &= text "List (VRID|VIP|RIP) from configuration files." -} data Verbosity = Quiet | Normal | Verbose deriving (Show, Eq, Ord, Enum) verbosity :: IO Verbosity verbosity = do norm <- fromEnum <$> isNormal loud <- fromEnum <$> isLoud return $ toEnum $ norm + loud
maoe/kc
Kc.hs
bsd-3-clause
4,460
0
15
1,330
996
507
489
84
2
module HVX.Internal.Matrix ( Mat , allMat , anyMat , diagMat , ei , fpequalsMat , lpnorm , matrixPow , reduceMat , scalarMat , zeroMat , zeroVec ) where import Numeric.LinearAlgebra import HVX.Internal.Util type Mat = Matrix Double allMat :: (Double -> Bool) -> Mat -> Bool allMat f x = all f (toList . flatten $ x) anyMat :: (Double -> Bool) -> Mat -> Bool anyMat f x = any f (toList . flatten $ x) diagMat :: Mat -> Mat diagMat = diag . flatten ei :: Int -> Int -> Mat ei n i = assoc (n, 1) 0.0 [((i, 0), 1)] fpequalsMat :: Mat -> Mat -> Bool fpequalsMat a b | ra == rb && ca == cb = all (uncurry fpequals) $ zip alist blist | otherwise = error "Two matrices with different dimensions cannot possibley be equal!" where ra = rows a rb = rows b ca = cols a cb = cols b alist = toList . flatten $ a blist = toList . flatten $ b lpnorm :: Double -> Mat -> Double lpnorm p x = sumElements y ** (1/p) where pMat = (1><1) [p] y = abs x ** pMat matrixPow :: Double -> Mat -> Mat matrixPow p = cmap (** p) reduceMat :: ([Double] -> Double) -> Mat -> Mat reduceMat f = (1><1) . (:[]) . f . toList . flatten scalarMat :: Double -> Mat scalarMat x = (1><1) [x] zeroMat :: Int -> Mat zeroMat n = konst 0.0 (n, n) zeroVec :: Int -> Mat zeroVec n = konst 0.0 (n, 1)
chrisnc/hvx
src/HVX/Internal/Matrix.hs
bsd-3-clause
1,333
0
10
349
600
323
277
48
1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-| Module : Stack.Sig.Sign Description : Signing Packages Copyright : (c) FPComplete.com, 2015 License : BSD3 Maintainer : Tim Dysinger <[email protected]> Stability : experimental Portability : POSIX -} module Stack.Sig.Sign (sign, signPackage, signTarBytes) where import Prelude () import Prelude.Compat import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip import Control.Monad (when) import Control.Monad.IO.Unlift import Control.Monad.Logger import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy as L import Data.Monoid ((<>)) import qualified Data.Text as T import Network.HTTP.Client (RequestBody (RequestBodyBS)) import Network.HTTP.Download import Network.HTTP.Simple import Network.HTTP.Types (methodPut) import Path import Path.IO import Stack.Package import Stack.Sig.GPG import Stack.Types.PackageIdentifier import Stack.Types.Sig import qualified System.FilePath as FP -- | Sign a haskell package with the given url of the signature -- service and a path to a tarball. sign #if __GLASGOW_HASKELL__ < 710 :: (Applicative m, MonadUnliftIO m, MonadLogger m, MonadThrow m) #else :: (MonadUnliftIO m, MonadLogger m, MonadThrow m) #endif => String -> Path Abs File -> m Signature sign url filePath = withRunIO $ \run -> withSystemTempDir "stack" (\tempDir -> do bytes <- liftIO (fmap GZip.decompress (BS.readFile (toFilePath filePath))) maybePath <- extractCabalFile tempDir (Tar.read bytes) case maybePath of Nothing -> throwM SigInvalidSDistTarBall Just cabalPath -> do pkg <- cabalFilePackageId (tempDir </> cabalPath) run (signPackage url pkg filePath)) where extractCabalFile tempDir (Tar.Next entry entries) = case Tar.entryContent entry of (Tar.NormalFile lbs _) -> case FP.splitFileName (Tar.entryPath entry) of (folder,file) | length (FP.splitDirectories folder) == 1 && FP.takeExtension file == ".cabal" -> do cabalFile <- parseRelFile file liftIO (BS.writeFile (toFilePath (tempDir </> cabalFile)) lbs) return (Just cabalFile) (_,_) -> extractCabalFile tempDir entries _ -> extractCabalFile tempDir entries extractCabalFile _ _ = return Nothing -- | Sign a haskell package with the given url to the signature -- service, a package tarball path (package tarball name) and a lazy -- bytestring of bytes that represent the tarball bytestream. The -- function will write the bytes to the path in a temp dir and sign -- the tarball with GPG. signTarBytes #if __GLASGOW_HASKELL__ < 710 :: (Applicative m, MonadUnliftIO m, MonadLogger m, MonadThrow m) #else :: (MonadUnliftIO m, MonadLogger m, MonadThrow m) #endif => String -> Path Rel File -> L.ByteString -> m Signature signTarBytes url tarPath bs = withRunIO $ \run -> withSystemTempDir "stack" (\tempDir -> do let tempTarBall = tempDir </> tarPath liftIO (L.writeFile (toFilePath tempTarBall) bs) run (sign url tempTarBall)) -- | Sign a haskell package given the url to the signature service, a -- @PackageIdentifier@ and a file path to the package on disk. signPackage :: (MonadIO m, MonadLogger m, MonadThrow m) => String -> PackageIdentifier -> Path Abs File -> m Signature signPackage url pkg filePath = do sig@(Signature signature) <- gpgSign filePath let (PackageIdentifier name version) = pkg fingerprint <- gpgVerify sig filePath let fullUrl = url <> "/upload/signature/" <> show name <> "/" <> show version <> "/" <> show fingerprint req <- parseUrlThrow fullUrl let put = setRequestMethod methodPut $ setRequestBody (RequestBodyBS signature) req res <- liftIO (httpLbs put) when (getResponseStatusCode res /= 200) (throwM (GPGSignException "unable to sign & upload package")) $logInfo ("Signature uploaded to " <> T.pack fullUrl) return sig
martin-kolinek/stack
src/Stack/Sig/Sign.hs
bsd-3-clause
4,811
0
22
1,509
994
520
474
94
5
{-# LANGUAGE OverloadedStrings #-} import RSSBuffer import Database.Redis -- hedis import Network.Curl.Download -- download-curl, sudo apt-get libcurl4-openssl-dev import Text.XML.Light -- xml import qualified Data.List as L import Control.Monad.IO.Class import Data.Maybe import Data.Monoid import Debug.Trace import Control.Concurrent import Control.Concurrent.MVar import qualified Data.ByteString.UTF8 as T import qualified Data.ByteString as BS main :: IO () main = do conn <- connect defaultConnectInfo mvar <- newMVar conn mapM_ (\x -> forkIO (updateFeed mvar x >> return ())) allFeeds updateFeed :: MVar Connection -> Feed -> IO (Either Reply Integer) updateFeed mvar (Feed idx _ url format) = do (Right xml) <- openAsXML url let (Just rss) = extractTree format xml let (h, es) = extractFeed format rss let newEs = L.reverse es readMVar mvar >>= \conn -> runRedis conn $ do set (feedMeta idx) $ foldl (\c x -> mappend c $ T.fromString . showElement $ x) "" h -- failed pattern matches are the least of my concerns (Right top) <- lrange (feedElems idx) 0 100 let newCont = newArticles format top newEs -- liftIO . print . uniqId . head . onlyElems . parseXML $ fromJust top -- liftIO . print $ (map uniqId newCont) -- liftIO . print $ (map uniqId old) lpush (feedElems idx) $ map (T.fromString . showElement) newCont extractFeed :: FeedType -> Element -> ([Element], [Element]) extractFeed Atom xs = (filterFeed "entry" (/=) xs, filterFeed "entry" (==) xs) extractFeed RSS xs = (filterFeed "item" (/=) xs, filterFeed "item" (==) xs) filterFeed str o xs = filterChildrenName (\(QName n _ _) -> o n str) xs extractTree Atom xml = treeFind "feed" xml extractTree RSS xml = treeFind "rss" xml treeFind str xml = L.find (\(Element (QName n _ _) _ _ _) -> n == str) $ onlyElems xml -- find where the feed is up to -- we want everything AFTER the first element that matches the break pred -- TODO: several feeds have not been following the "linear time" concept. :( newArticles :: FeedType -> [BS.ByteString] -> [Element] -> [Element] newArticles ft ts = filter (\x -> (uniqId ft x) `notElem` items) where items = map ((uniqId ft) . head . onlyElems . parseXML) ts
mxswd/rss-buffer
job.hs
bsd-3-clause
2,294
0
19
488
741
387
354
41
1
module Ghazan( module Ghazan.Area , module Ghazan.Length , module Ghazan.Liquid , module Ghazan.Numerics , module Ghazan.Speed , module Ghazan.Temperature , module Ghazan.Volume , module Ghazan.Weight , module Ghazan.Time ) where -- Source Imports import Ghazan.Area import Ghazan.Length import Ghazan.Liquid import Ghazan.Numerics import Ghazan.Speed import Ghazan.Temperature import Ghazan.Volume import Ghazan.Weight import Ghazan.Time
Cortlandd/ConversionFormulas
src/Ghazan.hs
bsd-3-clause
479
0
5
91
106
68
38
19
0
module Main where import Control.Concurrent (forkIO) import Control.Concurrent.STM import Control.Concurrent.STM.TVar import Control.Monad.Trans (liftIO) import Data.Time import System.Environment (getArgs) import System.Process.Monitor main = do args <- getArgs putStrLn "Monitoring beginning..." time <- getCurrentTime comm <- liftIO $ atomically $ newTVar $ mkComm time doWork args comm time putStrLn "Monitoring complete" doWork args comm time = do let workerBin = head args intervalBin = head $ drop 1 args worker = Executable workerBin [] job = mkJob worker launchWorker job comm [ Interval time 3 intervalJob1 , Interval time 5 intervalJob2 ] intervalJob1 _ = putStrLn "Example interval 1" intervalJob2 _ = putStrLn "Example interval 2"
stormont/vg-process-monitor
DefaultIntervalMonitor.hs
bsd-3-clause
872
0
11
232
232
117
115
28
1
{- (c) The GRASP Project, Glasgow University, 1994-1998 \section[TysWiredIn]{Wired-in knowledge about {\em non-primitive} types} -} {-# LANGUAGE CPP #-} -- | This module is about types that can be defined in Haskell, but which -- must be wired into the compiler nonetheless. C.f module TysPrim module TysWiredIn ( -- * All wired in things wiredInTyCons, isBuiltInOcc_maybe, -- * Bool boolTy, boolTyCon, boolTyCon_RDR, boolTyConName, trueDataCon, trueDataConId, true_RDR, falseDataCon, falseDataConId, false_RDR, promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon, -- * Ordering ltDataCon, ltDataConId, eqDataCon, eqDataConId, gtDataCon, gtDataConId, promotedOrderingTyCon, promotedLTDataCon, promotedEQDataCon, promotedGTDataCon, -- * Char charTyCon, charDataCon, charTyCon_RDR, charTy, stringTy, charTyConName, -- * Double doubleTyCon, doubleDataCon, doubleTy, doubleTyConName, -- * Float floatTyCon, floatDataCon, floatTy, floatTyConName, -- * Int intTyCon, intDataCon, intTyCon_RDR, intDataCon_RDR, intTyConName, intTy, -- * Word wordTyCon, wordDataCon, wordTyConName, wordTy, -- * List listTyCon, listTyCon_RDR, listTyConName, listTyConKey, nilDataCon, nilDataConName, nilDataConKey, consDataCon_RDR, consDataCon, consDataConName, mkListTy, mkPromotedListTy, -- * Tuples mkTupleTy, mkBoxedTupleTy, tupleTyCon, tupleDataCon, tupleTyConName, promotedTupleTyCon, promotedTupleDataCon, unitTyCon, unitDataCon, unitDataConId, unitTy, unitTyConKey, pairTyCon, unboxedUnitTyCon, unboxedUnitDataCon, unboxedSingletonTyCon, unboxedSingletonDataCon, unboxedPairTyCon, unboxedPairDataCon, cTupleTyConName, cTupleTyConNames, isCTupleTyConName, -- * Kinds typeNatKindCon, typeNatKind, typeSymbolKindCon, typeSymbolKind, -- * Parallel arrays mkPArrTy, parrTyCon, parrFakeCon, isPArrTyCon, isPArrFakeCon, parrTyCon_RDR, parrTyConName, -- * Equality predicates eqTyCon_RDR, eqTyCon, eqTyConName, eqBoxDataCon, coercibleTyCon, coercibleDataCon, coercibleClass, mkWiredInTyConName -- This is used in TcTypeNats to define the -- built-in functions for evaluation. ) where #include "HsVersions.h" import {-# SOURCE #-} MkId( mkDataConWorkId ) -- friends: import PrelNames import TysPrim -- others: import Constants ( mAX_TUPLE_SIZE, mAX_CTUPLE_SIZE ) import Module ( Module ) import Type ( mkTyConApp ) import DataCon import ConLike import Var import TyCon import Class ( Class, mkClass ) import TypeRep import RdrName import Name import NameSet ( NameSet, mkNameSet, elemNameSet ) import BasicTypes ( Arity, RecFlag(..), Boxity(..), TupleSort(..) ) import ForeignCall import Unique ( incrUnique, mkTupleTyConUnique, mkTupleDataConUnique, mkCTupleTyConUnique, mkPArrDataConUnique ) import SrcLoc ( noSrcSpan ) import Data.Array import FastString import Outputable import Util import BooleanFormula ( mkAnd ) alpha_tyvar :: [TyVar] alpha_tyvar = [alphaTyVar] alpha_ty :: [Type] alpha_ty = [alphaTy] {- ************************************************************************ * * \subsection{Wired in type constructors} * * ************************************************************************ If you change which things are wired in, make sure you change their names in PrelNames, so they use wTcQual, wDataQual, etc -} -- This list is used only to define PrelInfo.wiredInThings. That in turn -- is used to initialise the name environment carried around by the renamer. -- This means that if we look up the name of a TyCon (or its implicit binders) -- that occurs in this list that name will be assigned the wired-in key we -- define here. -- -- Because of their infinite nature, this list excludes tuples, Any and implicit -- parameter TyCons. Instead, we have a hack in lookupOrigNameCache to deal with -- these names. -- -- See also Note [Known-key names] wiredInTyCons :: [TyCon] wiredInTyCons = [ unitTyCon -- Not treated like other tuples, because -- it's defined in GHC.Base, and there's only -- one of it. We put it in wiredInTyCons so -- that it'll pre-populate the name cache, so -- the special case in lookupOrigNameCache -- doesn't need to look out for it , boolTyCon , charTyCon , doubleTyCon , floatTyCon , intTyCon , wordTyCon , listTyCon , parrTyCon , eqTyCon , coercibleTyCon , typeNatKindCon , typeSymbolKindCon ] mkWiredInTyConName :: BuiltInSyntax -> Module -> FastString -> Unique -> TyCon -> Name mkWiredInTyConName built_in modu fs unique tycon = mkWiredInName modu (mkTcOccFS fs) unique (ATyCon tycon) -- Relevant TyCon built_in mkWiredInDataConName :: BuiltInSyntax -> Module -> FastString -> Unique -> DataCon -> Name mkWiredInDataConName built_in modu fs unique datacon = mkWiredInName modu (mkDataOccFS fs) unique (AConLike (RealDataCon datacon)) -- Relevant DataCon built_in -- See Note [Kind-changing of (~) and Coercible] eqTyConName, eqBoxDataConName :: Name eqTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "~") eqTyConKey eqTyCon eqBoxDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "Eq#") eqBoxDataConKey eqBoxDataCon -- See Note [Kind-changing of (~) and Coercible] coercibleTyConName, coercibleDataConName :: Name coercibleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Coercible") coercibleTyConKey coercibleTyCon coercibleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "MkCoercible") coercibleDataConKey coercibleDataCon charTyConName, charDataConName, intTyConName, intDataConName :: Name charTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Char") charTyConKey charTyCon charDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "C#") charDataConKey charDataCon intTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Int") intTyConKey intTyCon intDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "I#") intDataConKey intDataCon boolTyConName, falseDataConName, trueDataConName :: Name boolTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Bool") boolTyConKey boolTyCon falseDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "False") falseDataConKey falseDataCon trueDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "True") trueDataConKey trueDataCon listTyConName, nilDataConName, consDataConName :: Name listTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "[]") listTyConKey listTyCon nilDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit "[]") nilDataConKey nilDataCon consDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit ":") consDataConKey consDataCon wordTyConName, wordDataConName, floatTyConName, floatDataConName, doubleTyConName, doubleDataConName :: Name wordTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Word") wordTyConKey wordTyCon wordDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "W#") wordDataConKey wordDataCon floatTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Float") floatTyConKey floatTyCon floatDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "F#") floatDataConKey floatDataCon doubleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Double") doubleTyConKey doubleTyCon doubleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "D#") doubleDataConKey doubleDataCon -- Kinds typeNatKindConName, typeSymbolKindConName :: Name typeNatKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Nat") typeNatKindConNameKey typeNatKindCon typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol") typeSymbolKindConNameKey typeSymbolKindCon parrTyConName, parrDataConName :: Name parrTyConName = mkWiredInTyConName BuiltInSyntax gHC_PARR' (fsLit "[::]") parrTyConKey parrTyCon parrDataConName = mkWiredInDataConName UserSyntax gHC_PARR' (fsLit "PArr") parrDataConKey parrDataCon boolTyCon_RDR, false_RDR, true_RDR, intTyCon_RDR, charTyCon_RDR, intDataCon_RDR, listTyCon_RDR, consDataCon_RDR, parrTyCon_RDR, eqTyCon_RDR :: RdrName boolTyCon_RDR = nameRdrName boolTyConName false_RDR = nameRdrName falseDataConName true_RDR = nameRdrName trueDataConName intTyCon_RDR = nameRdrName intTyConName charTyCon_RDR = nameRdrName charTyConName intDataCon_RDR = nameRdrName intDataConName listTyCon_RDR = nameRdrName listTyConName consDataCon_RDR = nameRdrName consDataConName parrTyCon_RDR = nameRdrName parrTyConName eqTyCon_RDR = nameRdrName eqTyConName {- ************************************************************************ * * \subsection{mkWiredInTyCon} * * ************************************************************************ -} pcNonRecDataTyCon :: Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon -- Not an enumeration, not promotable pcNonRecDataTyCon = pcTyCon False NonRecursive False -- This function assumes that the types it creates have all parameters at -- Representational role! pcTyCon :: Bool -> RecFlag -> Bool -> Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon pcTyCon is_enum is_rec is_prom name cType tyvars cons = buildAlgTyCon name tyvars (map (const Representational) tyvars) cType [] -- No stupid theta (DataTyCon cons is_enum) is_rec is_prom False -- Not in GADT syntax NoParentTyCon pcDataCon :: Name -> [TyVar] -> [Type] -> TyCon -> DataCon pcDataCon = pcDataConWithFixity False pcDataConWithFixity :: Bool -> Name -> [TyVar] -> [Type] -> TyCon -> DataCon pcDataConWithFixity infx n = pcDataConWithFixity' infx n (incrUnique (nameUnique n)) -- The Name's unique is the first of two free uniques; -- the first is used for the datacon itself, -- the second is used for the "worker name" -- -- To support this the mkPreludeDataConUnique function "allocates" -- one DataCon unique per pair of Ints. pcDataConWithFixity' :: Bool -> Name -> Unique -> [TyVar] -> [Type] -> TyCon -> DataCon -- The Name should be in the DataName name space; it's the name -- of the DataCon itself. pcDataConWithFixity' declared_infix dc_name wrk_key tyvars arg_tys tycon = data_con where data_con = mkDataCon dc_name declared_infix (map (const HsNoBang) arg_tys) [] -- No labelled fields tyvars [] -- No existential type variables [] -- No equality spec [] -- No theta arg_tys (mkTyConApp tycon (mkTyVarTys tyvars)) tycon [] -- No stupid theta (mkDataConWorkId wrk_name data_con) NoDataConRep -- Wired-in types are too simple to need wrappers modu = ASSERT( isExternalName dc_name ) nameModule dc_name wrk_occ = mkDataConWorkerOcc (nameOccName dc_name) wrk_name = mkWiredInName modu wrk_occ wrk_key (AnId (dataConWorkId data_con)) UserSyntax {- ************************************************************************ * * Kinds * * ************************************************************************ -} typeNatKindCon, typeSymbolKindCon :: TyCon -- data Nat -- data Symbol typeNatKindCon = pcTyCon False NonRecursive True typeNatKindConName Nothing [] [] typeSymbolKindCon = pcTyCon False NonRecursive True typeSymbolKindConName Nothing [] [] typeNatKind, typeSymbolKind :: Kind typeNatKind = TyConApp (promoteTyCon typeNatKindCon) [] typeSymbolKind = TyConApp (promoteTyCon typeSymbolKindCon) [] {- ************************************************************************ * * Stuff for dealing with tuples * * ************************************************************************ Note [How tuples work] See also Note [Known-key names] in PrelNames ~~~~~~~~~~~~~~~~~~~~~~ * There are three families of tuple TyCons and corresponding DataCons, expressed by the type BasicTypes.TupleSort: data TupleSort = BoxedTuple | UnboxedTuple | ConstraintTuple * All three families are AlgTyCons, whose AlgTyConRhs is TupleTyCon * BoxedTuples - A wired-in type - Data type declarations in GHC.Tuple - The data constructors really have an info table * UnboxedTuples - A wired-in type - Have a pretend DataCon, defined in GHC.Prim, but no actual declaration and no info table * ConstraintTuples - Are known-key rather than wired-in. Reason: it's awkward to have all the superclass selectors wired-in. - Declared as classes in GHC.Classes, e.g. class (c1,c2) => (c1,c2) - Given constraints: the superclasses automatically become available - Wanted constraints: there is a built-in instance instance (c1,c2) => (c1,c2) - Currently just go up to 16; beyond that you have to use manual nesting - Their OccNames look like (%,,,%), so they can easily be distinguished from term tuples. But (following Haskell) we pretty-print saturated constraint tuples with round parens; see BasicTypes.tupleParens. * In quite a lot of places things are restrcted just to BoxedTuple/UnboxedTuple, and then we used BasicTypes.Boxity to distinguish E.g. tupleTyCon has a Boxity argument * When looking up an OccName in the original-name cache (IfaceEnv.lookupOrigNameCache), we spot the tuple OccName to make sure we get the right wired-in name. This guy can't tell the difference betweeen BoxedTuple and ConstraintTuple (same OccName!), so tuples are not serialised into interface files using OccNames at all. -} isBuiltInOcc_maybe :: OccName -> Maybe Name -- Built in syntax isn't "in scope" so these OccNames -- map to wired-in Names with BuiltInSyntax isBuiltInOcc_maybe occ = case occNameString occ of "[]" -> choose_ns listTyConName nilDataConName ":" -> Just consDataConName "[::]" -> Just parrTyConName "()" -> tup_name Boxed 0 "(##)" -> tup_name Unboxed 0 '(':',':rest -> parse_tuple Boxed 2 rest '(':'#':',':rest -> parse_tuple Unboxed 2 rest _other -> Nothing where ns = occNameSpace occ parse_tuple sort n rest | (',' : rest2) <- rest = parse_tuple sort (n+1) rest2 | tail_matches sort rest = tup_name sort n | otherwise = Nothing tail_matches Boxed ")" = True tail_matches Unboxed "#)" = True tail_matches _ _ = False tup_name boxity arity = choose_ns (getName (tupleTyCon boxity arity)) (getName (tupleDataCon boxity arity)) choose_ns tc dc | isTcClsNameSpace ns = Just tc | isDataConNameSpace ns = Just dc | otherwise = pprPanic "tup_name" (ppr occ) mkTupleOcc :: NameSpace -> Boxity -> Arity -> OccName mkTupleOcc ns sort ar = mkOccName ns str where -- No need to cache these, the caching is done in mk_tuple str = case sort of Unboxed -> '(' : '#' : commas ++ "#)" Boxed -> '(' : commas ++ ")" commas = take (ar-1) (repeat ',') mkCTupleOcc :: NameSpace -> Arity -> OccName mkCTupleOcc ns ar = mkOccName ns str where str = "(%" ++ commas ++ "%)" commas = take (ar-1) (repeat ',') cTupleTyConName :: Arity -> Name cTupleTyConName arity = mkExternalName (mkCTupleTyConUnique arity) gHC_CLASSES (mkCTupleOcc tcName arity) noSrcSpan -- The corresponding DataCon does not have a known-key name cTupleTyConNames :: [Name] cTupleTyConNames = map cTupleTyConName (0 : [2..mAX_CTUPLE_SIZE]) cTupleTyConNameSet :: NameSet cTupleTyConNameSet = mkNameSet cTupleTyConNames isCTupleTyConName :: Name -> Bool isCTupleTyConName n = ASSERT2( isExternalName n, ppr n ) nameModule n == gHC_CLASSES && n `elemNameSet` cTupleTyConNameSet tupleTyCon :: Boxity -> Arity -> TyCon tupleTyCon sort i | i > mAX_TUPLE_SIZE = fst (mk_tuple sort i) -- Build one specially tupleTyCon Boxed i = fst (boxedTupleArr ! i) tupleTyCon Unboxed i = fst (unboxedTupleArr ! i) tupleTyConName :: TupleSort -> Arity -> Name tupleTyConName ConstraintTuple a = cTupleTyConName a tupleTyConName BoxedTuple a = tyConName (tupleTyCon Boxed a) tupleTyConName UnboxedTuple a = tyConName (tupleTyCon Unboxed a) promotedTupleTyCon :: Boxity -> Arity -> TyCon promotedTupleTyCon boxity i = promoteTyCon (tupleTyCon boxity i) promotedTupleDataCon :: Boxity -> Arity -> TyCon promotedTupleDataCon boxity i = promoteDataCon (tupleDataCon boxity i) tupleDataCon :: Boxity -> Arity -> DataCon tupleDataCon sort i | i > mAX_TUPLE_SIZE = snd (mk_tuple sort i) -- Build one specially tupleDataCon Boxed i = snd (boxedTupleArr ! i) tupleDataCon Unboxed i = snd (unboxedTupleArr ! i) boxedTupleArr, unboxedTupleArr :: Array Int (TyCon,DataCon) boxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Boxed i | i <- [0..mAX_TUPLE_SIZE]] unboxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Unboxed i | i <- [0..mAX_TUPLE_SIZE]] mk_tuple :: Boxity -> Int -> (TyCon,DataCon) mk_tuple boxity arity = (tycon, tuple_con) where tycon = mkTupleTyCon tc_name tc_kind arity tyvars tuple_con tup_sort prom_tc NoParentTyCon tup_sort = case boxity of Boxed -> BoxedTuple Unboxed -> UnboxedTuple prom_tc = case boxity of Boxed -> Just (mkPromotedTyCon tycon (promoteKind tc_kind)) Unboxed -> Nothing modu = case boxity of Boxed -> gHC_TUPLE Unboxed -> gHC_PRIM tc_name = mkWiredInName modu (mkTupleOcc tcName boxity arity) tc_uniq (ATyCon tycon) BuiltInSyntax tc_kind = mkArrowKinds (map tyVarKind tyvars) res_kind res_kind = case boxity of Boxed -> liftedTypeKind Unboxed -> unliftedTypeKind tyvars = take arity $ case boxity of Boxed -> alphaTyVars Unboxed -> openAlphaTyVars tuple_con = pcDataCon dc_name tyvars tyvar_tys tycon tyvar_tys = mkTyVarTys tyvars dc_name = mkWiredInName modu (mkTupleOcc dataName boxity arity) dc_uniq (AConLike (RealDataCon tuple_con)) BuiltInSyntax tc_uniq = mkTupleTyConUnique boxity arity dc_uniq = mkTupleDataConUnique boxity arity unitTyCon :: TyCon unitTyCon = tupleTyCon Boxed 0 unitTyConKey :: Unique unitTyConKey = getUnique unitTyCon unitDataCon :: DataCon unitDataCon = head (tyConDataCons unitTyCon) unitDataConId :: Id unitDataConId = dataConWorkId unitDataCon pairTyCon :: TyCon pairTyCon = tupleTyCon Boxed 2 unboxedUnitTyCon :: TyCon unboxedUnitTyCon = tupleTyCon Unboxed 0 unboxedUnitDataCon :: DataCon unboxedUnitDataCon = tupleDataCon Unboxed 0 unboxedSingletonTyCon :: TyCon unboxedSingletonTyCon = tupleTyCon Unboxed 1 unboxedSingletonDataCon :: DataCon unboxedSingletonDataCon = tupleDataCon Unboxed 1 unboxedPairTyCon :: TyCon unboxedPairTyCon = tupleTyCon Unboxed 2 unboxedPairDataCon :: DataCon unboxedPairDataCon = tupleDataCon Unboxed 2 {- ************************************************************************ * * \subsection[TysWiredIn-boxed-prim]{The ``boxed primitive'' types (@Char@, @Int@, etc)} * * ************************************************************************ -} eqTyCon :: TyCon eqTyCon = mkAlgTyCon eqTyConName (ForAllTy kv $ mkArrowKinds [k, k] constraintKind) [kv, a, b] [Nominal, Nominal, Nominal] Nothing [] -- No stupid theta (DataTyCon [eqBoxDataCon] False) NoParentTyCon NonRecursive False Nothing -- No parent for constraint-kinded types where kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k eqBoxDataCon :: DataCon eqBoxDataCon = pcDataCon eqBoxDataConName args [TyConApp eqPrimTyCon (map mkTyVarTy args)] eqTyCon where kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k args = [kv, a, b] coercibleTyCon :: TyCon coercibleTyCon = mkClassTyCon coercibleTyConName kind tvs [Nominal, Representational, Representational] rhs coercibleClass NonRecursive where kind = (ForAllTy kv $ mkArrowKinds [k, k] constraintKind) kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k tvs = [kv, a, b] rhs = DataTyCon [coercibleDataCon] False coercibleDataCon :: DataCon coercibleDataCon = pcDataCon coercibleDataConName args [TyConApp eqReprPrimTyCon (map mkTyVarTy args)] coercibleTyCon where kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k args = [kv, a, b] coercibleClass :: Class coercibleClass = mkClass (tyConTyVars coercibleTyCon) [] [] [] [] [] (mkAnd []) coercibleTyCon charTy :: Type charTy = mkTyConTy charTyCon charTyCon :: TyCon charTyCon = pcNonRecDataTyCon charTyConName (Just (CType "" Nothing ("HsChar",fsLit "HsChar"))) [] [charDataCon] charDataCon :: DataCon charDataCon = pcDataCon charDataConName [] [charPrimTy] charTyCon stringTy :: Type stringTy = mkListTy charTy -- convenience only intTy :: Type intTy = mkTyConTy intTyCon intTyCon :: TyCon intTyCon = pcNonRecDataTyCon intTyConName (Just (CType "" Nothing ("HsInt",fsLit "HsInt"))) [] [intDataCon] intDataCon :: DataCon intDataCon = pcDataCon intDataConName [] [intPrimTy] intTyCon wordTy :: Type wordTy = mkTyConTy wordTyCon wordTyCon :: TyCon wordTyCon = pcNonRecDataTyCon wordTyConName (Just (CType "" Nothing ("HsWord", fsLit "HsWord"))) [] [wordDataCon] wordDataCon :: DataCon wordDataCon = pcDataCon wordDataConName [] [wordPrimTy] wordTyCon floatTy :: Type floatTy = mkTyConTy floatTyCon floatTyCon :: TyCon floatTyCon = pcNonRecDataTyCon floatTyConName (Just (CType "" Nothing ("HsFloat", fsLit "HsFloat"))) [] [floatDataCon] floatDataCon :: DataCon floatDataCon = pcDataCon floatDataConName [] [floatPrimTy] floatTyCon doubleTy :: Type doubleTy = mkTyConTy doubleTyCon doubleTyCon :: TyCon doubleTyCon = pcNonRecDataTyCon doubleTyConName (Just (CType "" Nothing ("HsDouble",fsLit "HsDouble"))) [] [doubleDataCon] doubleDataCon :: DataCon doubleDataCon = pcDataCon doubleDataConName [] [doublePrimTy] doubleTyCon {- ************************************************************************ * * \subsection[TysWiredIn-Bool]{The @Bool@ type} * * ************************************************************************ An ordinary enumeration type, but deeply wired in. There are no magical operations on @Bool@ (just the regular Prelude code). {\em BEGIN IDLE SPECULATION BY SIMON} This is not the only way to encode @Bool@. A more obvious coding makes @Bool@ just a boxed up version of @Bool#@, like this: \begin{verbatim} type Bool# = Int# data Bool = MkBool Bool# \end{verbatim} Unfortunately, this doesn't correspond to what the Report says @Bool@ looks like! Furthermore, we get slightly less efficient code (I think) with this coding. @gtInt@ would look like this: \begin{verbatim} gtInt :: Int -> Int -> Bool gtInt x y = case x of I# x# -> case y of I# y# -> case (gtIntPrim x# y#) of b# -> MkBool b# \end{verbatim} Notice that the result of the @gtIntPrim@ comparison has to be turned into an integer (here called @b#@), and returned in a @MkBool@ box. The @if@ expression would compile to this: \begin{verbatim} case (gtInt x y) of MkBool b# -> case b# of { 1# -> e1; 0# -> e2 } \end{verbatim} I think this code is a little less efficient than the previous code, but I'm not certain. At all events, corresponding with the Report is important. The interesting thing is that the language is expressive enough to describe more than one alternative; and that a type doesn't necessarily need to be a straightforwardly boxed version of its primitive counterpart. {\em END IDLE SPECULATION BY SIMON} -} boolTy :: Type boolTy = mkTyConTy boolTyCon boolTyCon :: TyCon boolTyCon = pcTyCon True NonRecursive True boolTyConName (Just (CType "" Nothing ("HsBool", fsLit "HsBool"))) [] [falseDataCon, trueDataCon] falseDataCon, trueDataCon :: DataCon falseDataCon = pcDataCon falseDataConName [] [] boolTyCon trueDataCon = pcDataCon trueDataConName [] [] boolTyCon falseDataConId, trueDataConId :: Id falseDataConId = dataConWorkId falseDataCon trueDataConId = dataConWorkId trueDataCon orderingTyCon :: TyCon orderingTyCon = pcTyCon True NonRecursive True orderingTyConName Nothing [] [ltDataCon, eqDataCon, gtDataCon] ltDataCon, eqDataCon, gtDataCon :: DataCon ltDataCon = pcDataCon ltDataConName [] [] orderingTyCon eqDataCon = pcDataCon eqDataConName [] [] orderingTyCon gtDataCon = pcDataCon gtDataConName [] [] orderingTyCon ltDataConId, eqDataConId, gtDataConId :: Id ltDataConId = dataConWorkId ltDataCon eqDataConId = dataConWorkId eqDataCon gtDataConId = dataConWorkId gtDataCon {- ************************************************************************ * * \subsection[TysWiredIn-List]{The @List@ type (incl ``build'' magic)} * * ************************************************************************ Special syntax, deeply wired in, but otherwise an ordinary algebraic data types: \begin{verbatim} data [] a = [] | a : (List a) data () = () data (,) a b = (,,) a b ... \end{verbatim} -} mkListTy :: Type -> Type mkListTy ty = mkTyConApp listTyCon [ty] listTyCon :: TyCon listTyCon = pcTyCon False Recursive True listTyConName Nothing alpha_tyvar [nilDataCon, consDataCon] mkPromotedListTy :: Type -> Type mkPromotedListTy ty = mkTyConApp promotedListTyCon [ty] promotedListTyCon :: TyCon promotedListTyCon = promoteTyCon listTyCon nilDataCon :: DataCon nilDataCon = pcDataCon nilDataConName alpha_tyvar [] listTyCon consDataCon :: DataCon consDataCon = pcDataConWithFixity True {- Declared infix -} consDataConName alpha_tyvar [alphaTy, mkTyConApp listTyCon alpha_ty] listTyCon -- Interesting: polymorphic recursion would help here. -- We can't use (mkListTy alphaTy) in the defn of consDataCon, else mkListTy -- gets the over-specific type (Type -> Type) {- ************************************************************************ * * \subsection[TysWiredIn-Tuples]{The @Tuple@ types} * * ************************************************************************ The tuple types are definitely magic, because they form an infinite family. \begin{itemize} \item They have a special family of type constructors, of type @TyCon@ These contain the tycon arity, but don't require a Unique. \item They have a special family of constructors, of type @Id@. Again these contain their arity but don't need a Unique. \item There should be a magic way of generating the info tables and entry code for all tuples. But at the moment we just compile a Haskell source file\srcloc{lib/prelude/...} containing declarations like: \begin{verbatim} data Tuple0 = Tup0 data Tuple2 a b = Tup2 a b data Tuple3 a b c = Tup3 a b c data Tuple4 a b c d = Tup4 a b c d ... \end{verbatim} The print-names associated with the magic @Id@s for tuple constructors ``just happen'' to be the same as those generated by these declarations. \item The instance environment should have a magic way to know that each tuple type is an instances of classes @Eq@, @Ix@, @Ord@ and so on. \ToDo{Not implemented yet.} \item There should also be a way to generate the appropriate code for each of these instances, but (like the info tables and entry code) it is done by enumeration\srcloc{lib/prelude/InTup?.hs}. \end{itemize} -} mkTupleTy :: Boxity -> [Type] -> Type -- Special case for *boxed* 1-tuples, which are represented by the type itself mkTupleTy Boxed [ty] = ty mkTupleTy boxity tys = mkTyConApp (tupleTyCon boxity (length tys)) tys -- | Build the type of a small tuple that holds the specified type of thing mkBoxedTupleTy :: [Type] -> Type mkBoxedTupleTy tys = mkTupleTy Boxed tys unitTy :: Type unitTy = mkTupleTy Boxed [] {- ************************************************************************ * * \subsection[TysWiredIn-PArr]{The @[::]@ type} * * ************************************************************************ Special syntax for parallel arrays needs some wired in definitions. -} -- | Construct a type representing the application of the parallel array constructor mkPArrTy :: Type -> Type mkPArrTy ty = mkTyConApp parrTyCon [ty] -- | Represents the type constructor of parallel arrays -- -- * This must match the definition in @PrelPArr@ -- -- NB: Although the constructor is given here, it will not be accessible in -- user code as it is not in the environment of any compiled module except -- @PrelPArr@. -- parrTyCon :: TyCon parrTyCon = pcNonRecDataTyCon parrTyConName Nothing alpha_tyvar [parrDataCon] parrDataCon :: DataCon parrDataCon = pcDataCon parrDataConName alpha_tyvar -- forall'ed type variables [intTy, -- 1st argument: Int mkTyConApp -- 2nd argument: Array# a arrayPrimTyCon alpha_ty] parrTyCon -- | Check whether a type constructor is the constructor for parallel arrays isPArrTyCon :: TyCon -> Bool isPArrTyCon tc = tyConName tc == parrTyConName -- | Fake array constructors -- -- * These constructors are never really used to represent array values; -- however, they are very convenient during desugaring (and, in particular, -- in the pattern matching compiler) to treat array pattern just like -- yet another constructor pattern -- parrFakeCon :: Arity -> DataCon parrFakeCon i | i > mAX_TUPLE_SIZE = mkPArrFakeCon i -- build one specially parrFakeCon i = parrFakeConArr!i -- pre-defined set of constructors -- parrFakeConArr :: Array Int DataCon parrFakeConArr = array (0, mAX_TUPLE_SIZE) [(i, mkPArrFakeCon i) | i <- [0..mAX_TUPLE_SIZE]] -- build a fake parallel array constructor for the given arity -- mkPArrFakeCon :: Int -> DataCon mkPArrFakeCon arity = data_con where data_con = pcDataCon name [tyvar] tyvarTys parrTyCon tyvar = head alphaTyVars tyvarTys = replicate arity $ mkTyVarTy tyvar nameStr = mkFastString ("MkPArr" ++ show arity) name = mkWiredInName gHC_PARR' (mkDataOccFS nameStr) unique (AConLike (RealDataCon data_con)) UserSyntax unique = mkPArrDataConUnique arity -- | Checks whether a data constructor is a fake constructor for parallel arrays isPArrFakeCon :: DataCon -> Bool isPArrFakeCon dcon = dcon == parrFakeCon (dataConSourceArity dcon) -- Promoted Booleans promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon :: TyCon promotedBoolTyCon = promoteTyCon boolTyCon promotedTrueDataCon = promoteDataCon trueDataCon promotedFalseDataCon = promoteDataCon falseDataCon -- Promoted Ordering promotedOrderingTyCon , promotedLTDataCon , promotedEQDataCon , promotedGTDataCon :: TyCon promotedOrderingTyCon = promoteTyCon orderingTyCon promotedLTDataCon = promoteDataCon ltDataCon promotedEQDataCon = promoteDataCon eqDataCon promotedGTDataCon = promoteDataCon gtDataCon
urbanslug/ghc
compiler/prelude/TysWiredIn.hs
bsd-3-clause
34,151
0
14
8,910
5,403
2,954
2,449
474
10
module Compile.Types.AbstractAssembly where import Compile.Types.Ops data AAsm = AAsm {aAssign :: [ALoc] ,aOp :: Op ,aArgs :: [AVal] } | ACtrl COp AVal | AComment String deriving Show data AVal = ALoc ALoc | AImm Int deriving Show data ALoc = AReg Int | ATemp Int deriving Show
maurer/15-411-Haskell-Base-Code
src/Compile/Types/AbstractAssembly.hs
bsd-3-clause
379
0
9
149
95
59
36
11
0
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Dimensions.AF ( allDimensions ) where import Duckling.Dimensions.Types allDimensions :: [Seal Dimension] allDimensions = [ Seal Numeral ]
facebookincubator/duckling
Duckling/Dimensions/AF.hs
bsd-3-clause
371
0
6
65
45
29
16
6
1
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.Assignment.View where import Prelude hiding (min) import Control.Arrow ((&&&)) import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy.Char8 as BsLazy import Data.Maybe (fromMaybe) import Data.Monoid import Data.String (IsString(..), fromString) import qualified Data.Time as Time import qualified Text.Blaze.Html5.Attributes as A (id) import Text.Blaze.Html5.Attributes as A hiding (id) import Text.Blaze.Html5 as H hiding (map) import Text.Printf (printf) import Bead.Controller.Pages (PageDesc) import qualified Bead.Controller.Pages as Pages import qualified Bead.Domain.Entity.Assignment as Assignment import Bead.Domain.Shared.Evaluation import Bead.View.Fay.HookIds import Bead.View.Fay.Hooks import Bead.View.Content hiding (name, option, required) import qualified Bead.View.Content.Bootstrap as Bootstrap import Bead.View.Markdown import Bead.View.Content.Assignment.Data newAssignmentContent :: PageData -> IHtml newAssignmentContent pd = do msg <- getI18N let hook = assignmentEvTypeHook -- Renders a evaluation selection or hides it if there is a submission already for the assignment, -- and renders an explanation. evalConfig <- do let evaluationTypeSelection = return $ do Bootstrap.selectionWithLabel (evHiddenValueId hook) (msg $ msg_NewAssignment_EvaluationType "Evaluation Type") (== currentEvaluationType) [ (binaryConfig, fromString . msg $ msg_NewAssignment_BinEval "Binary") , (percentageConfig 0.0, fromString . msg $ msg_NewAssignment_PctEval "Percentage") , (freeFormConfig, fromString . msg $ msg_NewAssignment_FftEval "Free form textual") ] let hiddencfg asg = return $ do let e = Assignment.evType asg showEvaluationType msg e fromString . msg $ msg_NewAssignment_EvalTypeWarn "The evaluation type can not be modified, there is a submission for the assignment." hiddenInput (evHiddenValueId hook) (encodeToFay' "selection" e) pageDataCata (const5 evaluationTypeSelection) (const5 evaluationTypeSelection) (\_tz _key asg _ts _fs _tc ev -> if ev then evaluationTypeSelection else hiddencfg asg) (const5 evaluationTypeSelection) (const7 evaluationTypeSelection) (const7 evaluationTypeSelection) (\_tz _key asg _ts _fs _tc _tm ev -> if ev then evaluationTypeSelection else hiddencfg asg) pd return $ do Bootstrap.row $ Bootstrap.colMd12 $ H.form ! A.method "post" $ H.div ! A.id (fromString $ hookId assignmentForm) $ do Bootstrap.formGroup $ do let assignmentTitleField = fromString $ fieldName assignmentNameField assignmentTitlePlaceholder = fromString $ fromAssignment (const "") (fromString . msg $ msg_NewAssignment_Title_Default "Unnamed Assignment") pd assignmentTitle = fromAssignment (fromString . Assignment.name) mempty pd Bootstrap.labelFor assignmentTitleField (fromString $ msg $ msg_NewAssignment_Title "Title") editOrReadOnly pd $ Bootstrap.textInputFieldWithDefault assignmentTitleField assignmentTitle H.p ! class_ "help-block"$ fromString . msg $ msg_NewAssignment_Info_Normal $ concat [ "Solutions may be submitted from the time of opening until the time of closing. " , "The assignment will not be visible until it is opened. " , "The assignments open and close automatically." ] -- Visibility information of the assignment H.h4 $ fromString $ msg $ msg_NewAssignment_SubmissionDeadline "Visibility" let date t = let localTime = timeZoneConverter t timeOfDay = Time.localTimeOfDay localTime in ( show $ Time.localDay localTime , printf "%02d" $ Time.todHour timeOfDay , printf "%02d" $ Time.todMin timeOfDay ) showDate (dt, hour, min) = concat [dt, " ", hour, ":", min, ":00"] startDateStringValue = showDate $ date $ pageDataCata (\_tz t _c _ts _fs -> t) (\_tz t _g _ts _fs -> t) (\_tz _k a _ts _fs _tc _ev -> Assignment.start a) (\_tz _k a _ts _tc -> Assignment.start a) (\_tz _t _c _ts _fs a _tc -> Assignment.start a) (\_tz _t _g _ts _fs a _tc -> Assignment.start a) (\_tz _k a _ts _fs _tc _tm _ev -> Assignment.start a) pd endDateStringValue = showDate $ date $ pageDataCata (\_tz t _c _ts _fs -> t) (\_tz t _g _ts _fs -> t) (\_tz _k a _ts _fs _tc _ev -> Assignment.end a) (\_tz _k a _ts _tc -> Assignment.end a) (\_tz _t _c _ts _fs a _tc -> Assignment.end a) (\_tz _t _g _ts _fs a _tc -> Assignment.end a) (\_tz _k a _ts _fs _tc _tm _ev -> Assignment.end a) pd -- Opening and closing dates of the assignment Bootstrap.formGroup $ do Bootstrap.row $ do -- Opening date of the assignment Bootstrap.colMd6 $ do let assignmentStart = fieldName assignmentStartField Bootstrap.labelFor assignmentStart $ fromString $ msg $ msg_NewAssignment_StartDate "Opens" Bootstrap.datetimePicker assignmentStart startDateStringValue isEditPage -- Closing date of the assignment Bootstrap.colMd6 $ do let assignmentEnd = fieldName assignmentEndField Bootstrap.labelFor assignmentEnd $ msg $ msg_NewAssignment_EndDate "Closes" Bootstrap.datetimePicker assignmentEnd endDateStringValue isEditPage Bootstrap.rowColMd12 $ H.hr -- Properties of the assignment H.h4 $ fromString $ msg $ msg_NewAssignment_Properties "Properties" let editable = True readOnly = False assignmentPropertiesSection ed = do let pwd = if Assignment.isPasswordProtected aas then Just (Assignment.getPassword aas) else Nothing noOfTries = if Assignment.isNoOfTries aas then Just (Assignment.getNoOfTries aas) else Nothing editable x = if ed then x else (x ! A.readonly "") readOnly = not ed assignmentAspect = fromString $ fieldName assignmentAspectField assignmentPwd = fromString $ fieldName assignmentPwdField assignmentNoOfTries = fromString $ fieldName assignmentNoOfTriesField bootstrapCheckbox $ checkBoxRO (fieldName assignmentAspectField) (Assignment.isBallotBox aas) readOnly Assignment.BallotBox (msg $ msg_NewAssignment_BallotBox "Ballot Box") Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_BallotBox $ concat [ "(Recommended for tests.) Students will not be able to access submissions and " , "their evaluations until the assignment is closed." ] bootstrapCheckbox $ checkBoxRO (fieldName assignmentAspectField) (Assignment.isIsolated aas) readOnly Assignment.Isolated (msg $ msg_NewAssignment_Isolated "Isolated") Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_Isolated $ concat [ "(Recommended for tests.) Submissions for other assignments of the course are not visible in the " , "precense of an isolated assignments. Note: If there is more than one isolated assignment for the " , "same course, all the isolated assignment and submissions will be visible for the students." ] Bootstrap.row $ Bootstrap.colMd6 $ do bootstrapCheckbox $ do checkBoxRO (fieldName assignmentAspectField) (Assignment.isNoOfTries aas) readOnly (Assignment.NoOfTries 0) (msg $ msg_NewAssignment_NoOfTries "No of tries") Bootstrap.row $ Bootstrap.colMd6 $ Bootstrap.formGroup $ editable $ numberInput assignmentNoOfTries (Just 1) (Just 1000) noOfTries ! Bootstrap.formControl Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_NoOfTries $ "Limitation the number of the submissions (per student) for the assignment." bootstrapCheckbox $ checkBoxRO (fieldName assignmentAspectField) (Assignment.isPasswordProtected aas) readOnly (Assignment.Password "") (msg $ msg_NewAssignment_PasswordProtected "Password-protected") Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_Password $ concat [ "(Recommended for tests.) Submissions may be only submitted by providing the password. " , "The teacher shall use the password during the test in order to authenticate the " , "submission for the student." ] Bootstrap.row $ Bootstrap.colMd6 $ Bootstrap.formGroup $ do H.label $ fromString $ msg $ msg_NewAssignment_Password "Password" editable $ Bootstrap.inputForFormControl ! name assignmentPwd ! type_ "text" ! value (fromString $ fromMaybe "" pwd) Bootstrap.rowColMd12 $ H.hr -- Assignment Properties pageDataCata (const5 $ assignmentPropertiesSection editable) (const5 $ assignmentPropertiesSection editable) (const7 $ assignmentPropertiesSection editable) (const5 $ assignmentPropertiesSection readOnly) (const7 $ assignmentPropertiesSection editable) (const7 $ assignmentPropertiesSection editable) (const8 $ assignmentPropertiesSection editable) pd submissionTypeSelection msg pd -- Assignment Description Bootstrap.formGroup $ do let assignmentDesc = fromString $ fieldName assignmentDescField Bootstrap.labelFor assignmentDesc $ fromString . msg $ msg_NewAssignment_Description "Description" editOrReadOnly pd $ Bootstrap.textAreaField assignmentDesc $ do fromString $ fromAssignment Assignment.desc (fromString . msg $ msg_NewAssignment_Description_Default $ unlines [ concat [ "This text shall be in markdown format. Here are some quick " , "examples:" ] , "" , " - This is a bullet list item with *emphasis* (italic)." , " - And this is another item in the list with " , " **strong** (bold). Note that the rest of the item" , " shall be aligned." , "" , concat [ "Sometimes one may want to write verbatim text, this how it can " , "be done. However, `verbatim` words may be inlined any time by " , "using the backtick (`` ` ``) symbol." ] , "" , "~~~~~" , "verbatim text" , "~~~~~" , "" , concat [ "Note that links may be also [inserted](http://haskell.org/). And " , "when everything else fails, <a>pure</a> <b>HTML code</b> " , "<i>may be embedded</i>." ] ]) pd -- Preview of the assignment let assignmentPreview a = do Bootstrap.formGroup $ do H.label $ fromString $ msg $ msg_NewAssignment_AssignmentPreview "Assignment Preview" H.div # assignmentTextDiv $ markdownToHtml $ Assignment.desc a pageDataCata (const5 empty) (const5 empty) (const7 empty) (const5 empty) (\_tz _t _key _tsType _fs a _tc -> assignmentPreview a) (\_tz _t _key _tsType _fs a _tc -> assignmentPreview a) (\_tz _k a _t _fs _tst _tm _ev -> assignmentPreview a) pd -- Assignment Test Script Selection Bootstrap.formGroup $ do testScriptSelection msg pd -- Test Case area Bootstrap.formGroup $ do testCaseArea msg pd -- Evaluation config Bootstrap.formGroup $ do let previewAndCommitForm cfg = do evalSelectionDiv hook evalConfig pageDataCata (const5 (previewAndCommitForm binaryConfig)) (const5 (previewAndCommitForm binaryConfig)) (\_timezone _key asg _tsType _files _testcase _ev -> previewAndCommitForm (Assignment.evType asg)) (\_timezone _key asg _tsInfo _testcase -> showEvaluationType msg $ Assignment.evType asg) (\_timezone _time _courses _tsType _files assignment _tccreatio -> previewAndCommitForm (Assignment.evType assignment)) (\_timezone _time _groups _tsType _files assignment _tccreation -> previewAndCommitForm (Assignment.evType assignment)) (\_timezone _key asg _tsType _files _testcase _tcmod _ev -> previewAndCommitForm (Assignment.evType asg)) pd -- Hidden course or group keys for the assignment creation pageDataCata (\_tz _t (key,_course) _tsType _fs -> hiddenInput (fieldName selectedCourse) (courseKeyMap id key)) (\_tz _t (key,_group) _tsType _fs -> hiddenInput (fieldName selectedGroup) (groupKeyMap id key)) (const7 (return ())) (const5 (return ())) (\_tz _t (key,_course) _tsType _fs _a _tc -> hiddenInput (fieldName selectedCourse) (courseKeyMap id key)) (\_tz _t (key,_group) _tsType _fs _a _tc -> hiddenInput (fieldName selectedGroup) (groupKeyMap id key)) (const8 (return ())) pd -- Submit buttons Bootstrap.row $ do let formAction page = onclick (fromString $ concat ["javascript: form.action='", routeOf page, "';"]) Bootstrap.colMd6 $ onlyOnEdit pd $ Bootstrap.submitButtonWithAttr (formAction $ pagePreview pd) (msg $ msg_NewAssignment_PreviewButton "Preview") Bootstrap.colMd6 $ onlyOnEdit pd $ Bootstrap.submitButtonWithAttr (formAction $ page pd) (msg $ msg_NewAssignment_SaveButton "Commit") Bootstrap.turnSelectionsOn where aas = fromAssignment Assignment.aspects Assignment.emptyAspects pd currentEvaluationType = fromAssignment Assignment.evType binaryConfig pd editOrReadOnly = pageDataCata (const5 id) (const5 id) (const7 id) (const5 (! A.readonly "")) (const7 id) (const7 id) (const8 id) onlyOnEdit pd t = pageDataCata (const5 t) (const5 t) (const7 t) (const5 mempty) (const7 t) (const7 t) (const8 t) pd isEditPage = pageDataCata (const5 True) (const5 True) (const7 True) (const5 False) (const7 True) (const7 True) (const8 True) pd timeZoneConverter = pageDataCata (\tz _t _c _ts _fs -> tz) (\tz _t _g _ts _fs -> tz) (\tz _k _a _ts _fs _tc _ev -> tz) (\tz _k _a _ts _tc -> tz) (\tz _t _c _ts _fs _a _tc -> tz) (\tz _t _g _ts _fs _a _tc -> tz) (\tz _k _a _ts _fs _tc _tm _ev -> tz) pd fromAssignment :: (Assignment -> a) -> a -> PageData -> a fromAssignment f d pd = maybe d f (get pd) where get (PD_Assignment _ _ a _ _ _ _) = Just a get (PD_Assignment_Preview _ _ a _ _ _ _ _) = Just a get (PD_ViewAssignment _ _ a _ __ ) = Just a get (PD_Course_Preview _ _ _ _ _ a _) = Just a get (PD_Group_Preview _ _ _ _ _ a _) = Just a get _ = Nothing -- Renders a submission type selection for all page type but the view -- which prints only the selected type submissionTypeSelection msg pd = do let submissionTypeSelection = Bootstrap.selectionWithLabel (fieldName assignmentSubmissionTypeField) (msg $ msg_NewAssignment_SubmissionType "Submission Type") (== currentSubmissionType) [ (txtSubmission, fromString . msg $ msg_NewAssignment_TextSubmission "Text") , (zipSubmission, fromString . msg $ msg_NewAssignment_ZipSubmission "Zip file") ] let showSubmissionType s = Bootstrap.readOnlyTextInputWithDefault "" (msg $ msg_NewAssignment_SubmissionType "Submission Type") (Assignment.submissionType (fromString . msg $ msg_NewAssignment_TextSubmission "Text") (fromString . msg $ msg_NewAssignment_ZipSubmission "Zip file") (Assignment.aspectsToSubmissionType $ Assignment.aspects s)) pageDataCata (const5 submissionTypeSelection) (const5 submissionTypeSelection) (const7 submissionTypeSelection) (\_timezone _key asg _tsInfo _testcase -> showSubmissionType asg) (const7 submissionTypeSelection) (const7 submissionTypeSelection) (const8 submissionTypeSelection) pd testScriptSelection :: (Translation String -> String) -> PageData -> H.Html testScriptSelection msg = pageDataCata (\_tz _t _c tsType _fs -> scriptSelection tsType) (\_tz _t _g tsType _fs -> scriptSelection tsType) (\_tz _k _a tsType _fs mts _ev -> modificationScriptSelection tsType mts) (const5 (return ())) (\_tz _t _c tsType _fs _a tc -> scriptSelectionPreview tsType tc) (\_tz _t _g tsType _fs _a tc -> scriptSelectionPreview tsType tc) (\_tz _k _a tsType _fs mts tm _ev -> modificationScriptSelectionPreview tsType mts tm) where testScriptField :: (IsString s) => s testScriptField = fieldName assignmentTestScriptField scriptSelection ts = maybe (return ()) tsSelection ts tsSelection ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Tester") (const False) (map keyValue (Nothing:map Just ts)) scriptSelectionPreview ts tcp = case tcp of (Just Nothing , _, _) -> scriptSelection ts (Just (Just tsk) , _, _) -> preview ts tsk _ -> return () where preview ts tsk = maybe (return ()) (tsSelectionPreview tsk) ts tsSelectionPreview tsk ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Tester") ((Just tsk)==) (map keyValue (Nothing:map Just ts)) modificationScriptSelection ts mts = maybe (return ()) (mtsSelection mts) ts mtsSelection mts ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Tester") (def mts) (map keyValue (Nothing:map Just ts)) where def Nothing Nothing = True def Nothing _ = False def (Just (_,_,tsk)) (Just tsk') = tsk == tsk' def _ _ = False modificationScriptSelectionPreview ts _mts tm = case (tcmpTestScriptKey tm, ts) of (Just Nothing , Just ts') -> mtsSelection' Nothing ts' (Just (Just tsk), Just ts') -> mtsSelection' (Just tsk) ts' _ -> return () where mtsSelection' tsk ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Test scripts") (def tsk) (map keyValue (Nothing:map Just ts)) where def Nothing Nothing = True def Nothing _ = False def (Just tsk) (Just tsk') = tsk == tsk' def _ _ = False keyValue :: Maybe (TestScriptKey, TestScriptInfo) -> (Maybe TestScriptKey, String) keyValue Nothing = (Nothing, msg $ msg_NewAssignment_NoTesting "Assignment without testing") keyValue (Just (testScriptKey, tsInfo)) = ((Just testScriptKey), tsiName tsInfo) nothing = Nothing :: Maybe TestScriptKey -- Test Case Ares testCaseArea msg = pageDataCata (\_tz _t _c tsType fs -> createTestCaseArea fs tsType) (\_tz _t _g tsType fs -> createTestCaseArea fs tsType) (\_tz _k _a tsType fs tc _ev -> overwriteTestCaseArea fs tsType tc) (\_tz _k _a ts tc -> viewTestCaseArea ts tc) (\_tz _t _c tsType fs _a tc -> createTestCaseAreaPreview fs tsType tc) (\_tz _t _g tsType fs _a tc -> createTestCaseAreaPreview fs tsType tc) (\_tz _k _a tsType fs tc tm _ev -> overwriteTestCaseAreaPreview fs tsType tc tm) where textArea val = do Bootstrap.labelFor (fieldName assignmentTestCaseField) (msg $ msg_NewAssignment_TestCase "Test cases") editOrReadOnly pd $ Bootstrap.textAreaOptionalField (fieldName assignmentTestCaseField) (maybe mempty fromString val) createTestCaseAreaPreview fs ts tcp = case tcp of (Just Nothing , Nothing, Nothing) -> createTestCaseArea fs ts (Just _ , Just uf, Nothing) -> userFileSelection uf (Just _ , Nothing, Just f) -> textAreaPreview f _ -> return () where userFileSelection uf = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (uf==) (map keyValue fs) Bootstrap.helpBlock $ fromString (printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File")) Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue = (id &&& (usersFile id id)) textAreaPreview f = textArea (Just f) createTestCaseArea fs ts = maybe (return ()) (selectionOrTextArea) (testScriptType' ts) where selectionOrTextArea = testScriptTypeCata (textArea Nothing) usersFileSelection usersFileSelection = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (const False) (map keyValue fs) Bootstrap.helpBlock $ printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File") Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue = (id &&& (usersFile id id)) testCaseText Nothing = Nothing testCaseText (Just (_,tc,_)) = withTestCaseValue (tcValue tc) Just (const Nothing) testCaseFileName Nothing = return () testCaseFileName (Just (_,tc',_)) = fromString $ tcInfo tc' viewTestCaseArea ts tc = maybe (return ()) (selectionOrTextArea) (testScriptType'' ts) where selectionOrTextArea = testScriptTypeCata (textArea (testCaseText tc)) (usersFile) usersFile = do H.h4 $ fromString . msg $ msg_NewAssignment_TestFile "Test File" H.pre $ testCaseFileName tc overwriteTestCaseAreaPreview fs ts tc tm = maybe (return ()) (selectionOrTextAreaPreview) (testScriptType' ts) where selectionOrTextAreaPreview = testScriptTypeCata (textArea (tcmpTextTestCase tm)) -- simple (maybe (return ()) userFileSelectionPreview (tcmpFileTestCase tm)) -- zipped userFileSelectionPreview uf = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (==uf) (map keyValue ((Left ()):map Right fs)) H.pre $ testCaseFileName tc Bootstrap.helpBlock $ fromString $ printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File") Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue l@(Left ()) = (l, msg $ msg_NewAssignment_DoNotOverwrite "No changes") keyValue r@(Right uf) = (r, usersFile id id uf) overwriteTestCaseArea fs ts tc = maybe (return ()) (selectionOrTextArea) (testScriptType' ts) where selectionOrTextArea = testScriptTypeCata (textArea (testCaseText tc)) -- simple usersFileSelection -- zipped usersFileSelection = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (const False) (map keyValue ((Left ()):map Right fs)) H.pre $ testCaseFileName tc Bootstrap.helpBlock $ printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File") Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue l@(Left ()) = (l, msg $ msg_NewAssignment_DoNotOverwrite "No changes") keyValue r@(Right uf) = (r, usersFile id id uf) testScriptType' Nothing = Nothing testScriptType' (Just []) = Nothing testScriptType' (Just ((_tk,tsi):_)) = Just $ tsiType tsi testScriptType'' = fmap tsiType pagePreview :: PageData -> PageDesc pagePreview = pageDataCata (\_tz _t (key,_course) _tsType _fs -> newCourseAssignmentPreview key) (\_tz _t (key,_group) _tsType _fs -> newGroupAssignmentPreview key) (\_timezone key _asg _tsType _files _testcase _ev -> modifyAssignmentPreview key) (\_tz k _a _ts _tc -> viewAssignment k) (\_tz _t (key,_course) _tsType _fs _a _tc -> newCourseAssignmentPreview key) (\_tz _t (key,_group) _tsType _fs _a _tc -> newGroupAssignmentPreview key) (\_timezone key _asg _tsType _files _testcase _tc _ev -> modifyAssignmentPreview key) page :: PageData -> PageDesc page = pageDataCata (\_tz _t (key,_course) _tsType _fs -> newCourseAssignment key) (\_tz _t (key,_group) _tsType _fs -> newGroupAssignment key) (\_tz ak _asg _tsType _files _testcase _ev -> modifyAssignment ak) (\_tz k _a _ts _tc -> viewAssignment k) (\_tz _t (key,_course) _tsType _fs _a _tc -> newCourseAssignment key) (\_tz _t (key,_group) _tsType _fs _a _tc -> newGroupAssignment key) (\_tz k _a _fs _ts _tc _tm _ev -> modifyAssignment k) showEvaluationType msg e = Bootstrap.readOnlyTextInputWithDefault "" (msg $ msg_NewAssignment_EvaluationType "Evaluation Type") (evConfigCata (fromString . msg $ msg_NewAssignment_BinaryEvaluation "Binary Evaluation") (const . fromString . msg $ msg_NewAssignment_PercentageEvaluation "Percent") (fromString . msg $ msg_NewAssignment_FreeFormEvaluation "Free Form Evaluation") e) [txtSubmission, zipSubmission] = [Assignment.TextSubmission, Assignment.ZipSubmission] currentSubmissionType = if Assignment.isZippedSubmissions aas then zipSubmission else txtSubmission -- Pages constants newCourseAssignment k = Pages.newCourseAssignment k () newGroupAssignment k = Pages.newGroupAssignment k () modifyAssignment k = Pages.modifyAssignment k () newCourseAssignmentPreview k = Pages.newCourseAssignmentPreview k () newGroupAssignmentPreview k = Pages.newGroupAssignmentPreview k () modifyAssignmentPreview k = Pages.modifyAssignmentPreview k () viewAssignment k = Pages.viewAssignment k () uploadFile = Pages.uploadFile () -- Boostrap bootstrapCheckbox tag = H.div ! A.class_ "checkbox" $ H.label $ tag
andorp/bead
src/Bead/View/Content/Assignment/View.hs
bsd-3-clause
32,216
37
28
12,156
7,155
3,629
3,526
525
32
{-#LANGUAGE OverloadedStrings#-} {- Project name: Merge XLS files Min Zhang Date: Oct 13, 2015 Version: v.0.1.0 README: Merge columns from excel files. This program aims for more general file merging situations. However, for the time being, only merge files with exact same first column (row names), have same length (row number), and only take second column. Such as htcount output, and new Ion Proton platform RNA-seq read count output. -} import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as TextIO import qualified Data.Char as C import Control.Applicative import qualified Data.List as L import Control.Monad (fmap) import Data.Ord (comparing) import Data.Function (on) import qualified Safe as S import qualified Data.Maybe as Maybe import qualified Data.Foldable as F (all) import Data.Traversable (sequenceA) import qualified Data.ByteString.Lazy.Char8 as Bl import qualified System.IO as IO import System.Environment import System.Directory import MyText import MyTable import Util main :: IO() main = do preludeInformation paths <- getArgs let inputPaths = init paths -- print input path names into the first column of the file, to avoid confusion of samples let inputPathNames = T.concat ["samples", "\t", untab (map T.pack inputPaths), "\n"] let outputPath = S.lastDef "./outputMergeXls.txt.default" paths -- remove first column header; transpose columns to lists -- TODO: checkHeader is an automation to check if first line contains numbers or letters; if former is the case, delete first line; ducktape here now, need to make this function more reliable. inputFiles <- map (L.transpose . checkHeader) <$> mapM smartTable inputPaths -- check row names of each sample are the same checkRowNames inputFiles -- by default, use the row name of the first sample, if it is false in checkRowNames, the output will be mismatched, although it will still print the output let body = mergeColumns inputFiles let result = T.concat [inputPathNames, body] TextIO.writeFile outputPath result preludeInformation :: IO () preludeInformation = do putStrLn "mergeXls: merge columns from excel files. Note: The first row will be automatically removed." putStrLn "Usage: mergeXls input1 input2 input3 outputpath\n" -- TODO: check if first line is header or numbers checkHeader :: [a] -> [a] checkHeader [] = [] checkHeader (x:xs) = if isHeader x then xs else (x:xs) where isHeader x = True -- samples are long form (eg: [[rowname1, rowname2, rowname3, ...], [readnumber1, rn2, rn3, ...]]) checkRowNames :: Eq a => [[a]] -> IO () checkRowNames samples = do let rownames = map (S.headNote "checkRowName head, take first colunm") samples if and [a==b|a<- rownames, b<-rownames] then print "All samples have same rownames. Merged output will be printed." else print "Samples with different row names. The merged output is printed, but likely to be mismatched. Check inputs." mergeColumns :: [[[T.Text]]] -> T.Text mergeColumns inputFiles = let rownames = S.headNote "mergeColumns head call" (S.headNote "mergeColumns head call of first sample" inputFiles) counts = map (S.lastNote "mergeColumns last call") inputFiles in T.unlines $ map untab $ L.transpose $ rownames : counts
Min-/fourseq
src/utils/MergeXls.hs
bsd-3-clause
3,324
0
15
612
618
336
282
53
2
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveFunctor #-} {-| TT is the core language of Idris. The language has: * Full dependent types * A hierarchy of universes, with cumulativity: Type : Type1, Type1 : Type2, ... * Pattern matching letrec binding * (primitive types defined externally) Some technical stuff: * Typechecker is kept as simple as possible - no unification, just a checker for incomplete terms. * We have a simple collection of tactics which we use to elaborate source programs with implicit syntax into fully explicit terms. -} module Idris.Core.TT(module Idris.Core.TT, module Idris.Core.TC) where import Idris.Core.TC import Control.Monad.State.Strict import Control.Monad.Trans.Error (Error(..)) import Debug.Trace import qualified Data.Map.Strict as Map import Data.Char import Numeric (showIntAtBase) import qualified Data.Text as T import Data.List hiding (insert) import Data.Set(Set, member, fromList, insert) import Data.Maybe (listToMaybe) import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V import qualified Data.Binary as B import Data.Binary hiding (get, put) import Foreign.Storable (sizeOf) import Util.Pretty hiding (Str) data Option = TTypeInTType | CheckConv deriving Eq -- | Source location. These are typically produced by the parser 'Idris.Parser.getFC' data FC = FC { fc_fname :: String, -- ^ Filename fc_start :: (Int, Int), -- ^ Line and column numbers for the start of the location span fc_end :: (Int, Int) -- ^ Line and column numbers for the end of the location span } -- | Ignore source location equality (so deriving classes do not compare FCs) instance Eq FC where _ == _ = True -- | FC with equality newtype FC' = FC' { unwrapFC :: FC } instance Eq FC' where FC' fc == FC' fc' = fcEq fc fc' where fcEq (FC n s e) (FC n' s' e') = n == n' && s == s' && e == e' -- | Empty source location emptyFC :: FC emptyFC = fileFC "" -- |Β Source location with file only fileFC :: String -> FC fileFC s = FC s (0, 0) (0, 0) {-! deriving instance Binary FC deriving instance NFData FC !-} instance Sized FC where size (FC f s e) = 4 + length f instance Show FC where show (FC f s e) = f ++ ":" ++ showLC s e where showLC (sl, sc) (el, ec) | sl == el && sc == ec = show sl ++ ":" ++ show sc | sl == el = show sl ++ ":" ++ show sc ++ "-" ++ show ec | otherwise = show sl ++ ":" ++ show sc ++ "-" ++ show el ++ ":" ++ show ec -- | Output annotation for pretty-printed name - decides colour data NameOutput = TypeOutput | FunOutput | DataOutput | MetavarOutput | PostulateOutput -- | Text formatting output data TextFormatting = BoldText | ItalicText | UnderlineText -- | Output annotations for pretty-printing data OutputAnnotation = AnnName Name (Maybe NameOutput) (Maybe String) (Maybe String) -- ^^ The name, classification, docs overview, and pretty-printed type | AnnBoundName Name Bool -- ^^ The name and whether it is implicit | AnnConst Const | AnnData String String -- ^ type, doc overview | AnnType String String -- ^ name, doc overview | AnnKeyword | AnnFC FC | AnnTextFmt TextFormatting | AnnTerm [(Name, Bool)] (TT Name) -- ^ pprint bound vars, original term | AnnSearchResult Ordering -- ^ more general, isomorphic, or more specific | AnnErr Err -- | Used for error reflection data ErrorReportPart = TextPart String | NamePart Name | TermPart Term | SubReport [ErrorReportPart] deriving (Show, Eq) -- Please remember to keep Err synchronised with -- Language.Reflection.Errors.Err in the stdlib! -- | Idris errors. Used as exceptions in the compiler, but reported to users -- if they reach the top level. data Err' t = Msg String | InternalMsg String | CantUnify Bool t t (Err' t) [(Name, t)] Int -- Int is 'score' - how much we did unify -- Bool indicates recoverability, True indicates more info may make -- unification succeed | InfiniteUnify Name t [(Name, t)] | CantConvert t t [(Name, t)] | CantSolveGoal t [(Name, t)] | UnifyScope Name Name t [(Name, t)] | CantInferType String | NonFunctionType t t | NotEquality t t | TooManyArguments Name | CantIntroduce t | NoSuchVariable Name | WithFnType t | NoTypeDecl Name | NotInjective t t t | CantResolve t | CantResolveAlts [Name] | IncompleteTerm t | UniverseError | UniqueError Universe Name | UniqueKindError Universe Name | ProgramLineComment | Inaccessible Name | NonCollapsiblePostulate Name | AlreadyDefined Name | ProofSearchFail (Err' t) | NoRewriting t | At FC (Err' t) | Elaborating String Name (Err' t) | ElaboratingArg Name Name [(Name, Name)] (Err' t) | ProviderError String | LoadingFailed String (Err' t) | ReflectionError [[ErrorReportPart]] (Err' t) | ReflectionFailed String (Err' t) deriving (Eq, Functor) type Err = Err' Term {-! deriving instance NFData Err !-} instance Sized ErrorReportPart where size (TextPart msg) = 1 + length msg size (TermPart t) = 1 + size t size (NamePart n) = 1 + size n size (SubReport rs) = 1 + size rs instance Sized Err where size (Msg msg) = length msg size (InternalMsg msg) = length msg size (CantUnify _ left right err _ score) = size left + size right + size err size (InfiniteUnify _ right _) = size right size (CantConvert left right _) = size left + size right size (UnifyScope _ _ right _) = size right size (NoSuchVariable name) = size name size (NoTypeDecl name) = size name size (NotInjective l c r) = size l + size c + size r size (CantResolve trm) = size trm size (NoRewriting trm) = size trm size (CantResolveAlts _) = 1 size (IncompleteTerm trm) = size trm size UniverseError = 1 size ProgramLineComment = 1 size (At fc err) = size fc + size err size (Elaborating _ n err) = size err size (ElaboratingArg _ _ _ err) = size err size (ProviderError msg) = length msg size (LoadingFailed fn e) = 1 + length fn + size e size _ = 1 score :: Err -> Int score (CantUnify _ _ _ m _ s) = s + score m score (CantResolve _) = 20 score (NoSuchVariable _) = 1000 score (ProofSearchFail e) = score e score (CantSolveGoal _ _) = 100000 score (InternalMsg _) = -1 score (At _ e) = score e score (ElaboratingArg _ _ _ e) = score e score (Elaborating _ _ e) = score e score _ = 0 instance Show Err where show (Msg s) = s show (InternalMsg s) = "Internal error: " ++ show s show (CantUnify rec l r e sc i) = "CantUnify " ++ show rec ++ " " ++ show l ++ " " ++ show r ++ " " ++ show e ++ " in " ++ show sc ++ " " ++ show i show (CantSolveGoal g _) = "CantSolve " ++ show g show (Inaccessible n) = show n ++ " is not an accessible pattern variable" show (ProviderError msg) = "Type provider error: " ++ msg show (LoadingFailed fn e) = "Loading " ++ fn ++ " failed: (TT) " ++ show e show ProgramLineComment = "Program line next to comment" show (At f e) = show f ++ ":" ++ show e show (ElaboratingArg f x prev e) = "Elaborating " ++ show f ++ " arg " ++ show x ++ ": " ++ show e show (Elaborating what n e) = "Elaborating " ++ what ++ show n ++ ":" ++ show e show (ProofSearchFail e) = "Proof search fail: " ++ show e show _ = "Error" instance Pretty Err OutputAnnotation where pretty (Msg m) = text m pretty (CantUnify _ l r e _ i) = text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r <+> nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i)) pretty (ProviderError msg) = text msg pretty err@(LoadingFailed _ _) = text (show err) pretty _ = text "Error" instance Error Err where strMsg = InternalMsg type TC = TC' Err instance (Pretty a OutputAnnotation) => Pretty (TC a) OutputAnnotation where pretty (OK ok) = pretty ok pretty (Error err) = text "Error" <+> colon <+> pretty err instance Show a => Show (TC a) where show (OK x) = show x show (Error str) = "Error: " ++ show str tfail :: Err -> TC a tfail e = Error e failMsg :: String -> TC a failMsg str = Error (Msg str) trun :: FC -> TC a -> TC a trun fc (OK a) = OK a trun fc (Error e) = Error (At fc e) discard :: Monad m => m a -> m () discard f = f >> return () showSep :: String -> [String] -> String showSep sep [] = "" showSep sep [x] = x showSep sep (x:xs) = x ++ sep ++ showSep sep xs pmap f (x, y) = (f x, f y) traceWhen True msg a = trace msg a traceWhen False _ a = a -- RAW TERMS ---------------------------------------------------------------- -- | Names are hierarchies of strings, describing scope (so no danger of -- duplicate names, but need to be careful on lookup). data Name = UN T.Text -- ^ User-provided name | NS Name [T.Text] -- ^ Root, namespaces | MN Int T.Text -- ^ Machine chosen names | NErased -- ^ Name of something which is never used in scope | SN SpecialName -- ^ Decorated function names | SymRef Int -- ^ Reference to IBC file symbol table (used during serialisation) deriving (Eq, Ord) txt :: String -> T.Text txt = T.pack str :: T.Text -> String str = T.unpack tnull :: T.Text -> Bool tnull = T.null thead :: T.Text -> Char thead = T.head -- Smart constructors for names, using old String style sUN :: String -> Name sUN s = UN (txt s) sNS :: Name -> [String] -> Name sNS n ss = NS n (map txt ss) sMN :: Int -> String -> Name sMN i s = MN i (txt s) {-! deriving instance Binary Name deriving instance NFData Name !-} data SpecialName = WhereN Int Name Name | WithN Int Name | InstanceN Name [T.Text] | ParentN Name T.Text | MethodN Name | CaseN Name | ElimN Name | InstanceCtorN Name deriving (Eq, Ord) {-! deriving instance Binary SpecialName deriving instance NFData SpecialName !-} sInstanceN :: Name -> [String] -> SpecialName sInstanceN n ss = InstanceN n (map T.pack ss) sParentN :: Name -> String -> SpecialName sParentN n s = ParentN n (T.pack s) instance Sized Name where size (UN n) = 1 size (NS n els) = 1 + length els size (MN i n) = 1 size _ = 1 instance Pretty Name OutputAnnotation where pretty n@(UN n') = annotate (AnnName n Nothing Nothing Nothing) $ text (T.unpack n') pretty n@(NS un s) = annotate (AnnName n Nothing Nothing Nothing) . noAnnotate $ pretty un pretty n@(MN i s) = annotate (AnnName n Nothing Nothing Nothing) $ lbrace <+> text (T.unpack s) <+> (text . show $ i) <+> rbrace pretty n@(SN s) = annotate (AnnName n Nothing Nothing Nothing) $ text (show s) instance Pretty [Name] OutputAnnotation where pretty = encloseSep empty empty comma . map pretty instance Show Name where show (UN n) = str n show (NS n s) = showSep "." (map T.unpack (reverse s)) ++ "." ++ show n show (MN _ u) | u == txt "underscore" = "_" show (MN i s) = "{" ++ str s ++ show i ++ "}" show (SN s) = show s show NErased = "_" instance Show SpecialName where show (WhereN i p c) = show p ++ ", " ++ show c show (WithN i n) = "with block in " ++ show n show (InstanceN cl inst) = showSep ", " (map T.unpack inst) ++ " instance of " ++ show cl show (MethodN m) = "method " ++ show m show (ParentN p c) = show p ++ "#" ++ T.unpack c show (CaseN n) = "case block in " ++ show n show (ElimN n) = "<<" ++ show n ++ " eliminator>>" show (InstanceCtorN n) = "constructor of " ++ show n -- Show a name in a way decorated for code generation, not human reading showCG :: Name -> String showCG (UN n) = T.unpack n showCG (NS n s) = showSep "." (map T.unpack (reverse s)) ++ "." ++ showCG n showCG (MN _ u) | u == txt "underscore" = "_" showCG (MN i s) = "{" ++ T.unpack s ++ show i ++ "}" showCG (SN s) = showCG' s where showCG' (WhereN i p c) = showCG p ++ ":" ++ showCG c ++ ":" ++ show i showCG' (WithN i n) = "_" ++ showCG n ++ "_with_" ++ show i showCG' (InstanceN cl inst) = '@':showCG cl ++ '$':showSep ":" (map T.unpack inst) showCG' (MethodN m) = '!':showCG m showCG' (ParentN p c) = showCG p ++ "#" ++ show c showCG' (CaseN c) = showCG c ++ "_case" showCG' (ElimN sn) = showCG sn ++ "_elim" showCG NErased = "_" -- |Contexts allow us to map names to things. A root name maps to a collection -- of things in different namespaces with that name. type Ctxt a = Map.Map Name (Map.Map Name a) emptyContext = Map.empty mapCtxt :: (a -> b) -> Ctxt a -> Ctxt b mapCtxt = fmap . fmap -- |Return True if the argument 'Name' should be interpreted as the name of a -- typeclass. tcname (UN xs) | T.null xs = False | otherwise = T.head xs == '@' tcname (NS n _) = tcname n tcname (SN (InstanceN _ _)) = True tcname (SN (MethodN _)) = True tcname (SN (ParentN _ _)) = True tcname _ = False implicitable (NS n _) = implicitable n implicitable (UN xs) | T.null xs = False | otherwise = isLower (T.head xs) || T.head xs == '_' implicitable (MN _ x) = not (tnull x) && thead x /= '_' implicitable _ = False nsroot (NS n _) = n nsroot n = n -- this will overwrite already existing definitions addDef :: Name -> a -> Ctxt a -> Ctxt a addDef n v ctxt = case Map.lookup (nsroot n) ctxt of Nothing -> Map.insert (nsroot n) (Map.insert n v Map.empty) ctxt Just xs -> Map.insert (nsroot n) (Map.insert n v xs) ctxt {-| Look up a name in the context, given an optional namespace. The name (n) may itself have a (partial) namespace given. Rules for resolution: - if an explicit namespace is given, return the names which match it. If none match, return all names. - if the name has has explicit namespace given, return the names which match it and ignore the given namespace. - otherwise, return all names. -} lookupCtxtName :: Name -> Ctxt a -> [(Name, a)] lookupCtxtName n ctxt = case Map.lookup (nsroot n) ctxt of Just xs -> filterNS (Map.toList xs) Nothing -> [] where filterNS [] = [] filterNS ((found, v) : xs) | nsmatch n found = (found, v) : filterNS xs | otherwise = filterNS xs nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps nsmatch (NS _ _) _ = False nsmatch looking found = True lookupCtxt :: Name -> Ctxt a -> [a] lookupCtxt n ctxt = map snd (lookupCtxtName n ctxt) lookupCtxtExact :: Name -> Ctxt a -> Maybe a lookupCtxtExact n ctxt = listToMaybe [ v | (nm, v) <- lookupCtxtName n ctxt, nm == n] deleteDefExact :: Name -> Ctxt a -> Ctxt a deleteDefExact n = Map.adjust (Map.delete n) (nsroot n) updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a updateDef n f ctxt = let ds = lookupCtxtName n ctxt in foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds toAlist :: Ctxt a -> [(Name, a)] toAlist ctxt = let allns = map snd (Map.toList ctxt) in concatMap (Map.toList) allns addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a addAlist [] ctxt = ctxt addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt) data NativeTy = IT8 | IT16 | IT32 | IT64 deriving (Show, Eq, Ord, Enum) instance Pretty NativeTy OutputAnnotation where pretty IT8 = text "Bits8" pretty IT16 = text "Bits16" pretty IT32 = text "Bits32" pretty IT64 = text "Bits64" data IntTy = ITFixed NativeTy | ITNative | ITBig | ITChar | ITVec NativeTy Int deriving (Show, Eq, Ord) intTyName :: IntTy -> String intTyName ITNative = "Int" intTyName ITBig = "BigInt" intTyName (ITFixed sized) = "B" ++ show (nativeTyWidth sized) intTyName (ITChar) = "Char" intTyName (ITVec ity count) = "B" ++ show (nativeTyWidth ity) ++ "x" ++ show count data ArithTy = ATInt IntTy | ATFloat -- TODO: Float vectors https://github.com/idris-lang/Idris-dev/issues/1723 deriving (Show, Eq, Ord) {-! deriving instance NFData IntTy deriving instance NFData NativeTy deriving instance NFData ArithTy !-} instance Pretty ArithTy OutputAnnotation where pretty (ATInt ITNative) = text "Int" pretty (ATInt ITBig) = text "BigInt" pretty (ATInt ITChar) = text "Char" pretty (ATInt (ITFixed n)) = pretty n pretty (ATInt (ITVec e c)) = pretty e <> text "x" <> (text . show $ c) pretty ATFloat = text "Float" nativeTyWidth :: NativeTy -> Int nativeTyWidth IT8 = 8 nativeTyWidth IT16 = 16 nativeTyWidth IT32 = 32 nativeTyWidth IT64 = 64 {-# DEPRECATED intTyWidth "Non-total function, use nativeTyWidth and appropriate casing" #-} intTyWidth :: IntTy -> Int intTyWidth (ITFixed n) = nativeTyWidth n intTyWidth ITNative = 8 * sizeOf (0 :: Int) intTyWidth ITChar = error "IRTS.Lang.intTyWidth: Characters have platform and backend dependent width" intTyWidth ITBig = error "IRTS.Lang.intTyWidth: Big integers have variable width" data Const = I Int | BI Integer | Fl Double | Ch Char | Str String | B8 Word8 | B16 Word16 | B32 Word32 | B64 Word64 | B8V (Vector Word8) | B16V (Vector Word16) | B32V (Vector Word32) | B64V (Vector Word64) | AType ArithTy | StrType | PtrType | ManagedPtrType | BufferType | VoidType | Forgot deriving (Eq, Ord) {-! deriving instance Binary Const deriving instance NFData Const !-} instance Sized Const where size _ = 1 instance Pretty Const OutputAnnotation where pretty (I i) = text . show $ i pretty (BI i) = text . show $ i pretty (Fl f) = text . show $ f pretty (Ch c) = text . show $ c pretty (Str s) = text s pretty (AType a) = pretty a pretty StrType = text "String" pretty BufferType = text "prim__UnsafeBuffer" pretty PtrType = text "Ptr" pretty ManagedPtrType = text "Ptr" pretty VoidType = text "Void" pretty Forgot = text "Forgot" pretty (B8 w) = text . show $ w pretty (B16 w) = text . show $ w pretty (B32 w) = text . show $ w pretty (B64 w) = text . show $ w -- | Determines whether the input constant represents a type constIsType :: Const -> Bool constIsType (I _) = False constIsType (BI _) = False constIsType (Fl _) = False constIsType (Ch _) = False constIsType (Str _) = False constIsType (B8 _) = False constIsType (B16 _) = False constIsType (B32 _) = False constIsType (B64 _) = False constIsType (B8V _) = False constIsType (B16V _) = False constIsType (B32V _) = False constIsType (B64V _) = False constIsType _ = True -- | Get the docstring for a Const constDocs :: Const -> String constDocs c@(AType (ATInt ITBig)) = "Arbitrary-precision integers" constDocs c@(AType (ATInt ITNative)) = "Fixed-precision integers of undefined size" constDocs c@(AType (ATInt ITChar)) = "Characters in some unspecified encoding" constDocs c@(AType ATFloat) = "Double-precision floating-point numbers" constDocs StrType = "Strings in some unspecified encoding" constDocs PtrType = "Foreign pointers" constDocs ManagedPtrType = "Managed pointers" constDocs BufferType = "Copy-on-write buffers" constDocs c@(AType (ATInt (ITFixed IT8))) = "Eight bits (unsigned)" constDocs c@(AType (ATInt (ITFixed IT16))) = "Sixteen bits (unsigned)" constDocs c@(AType (ATInt (ITFixed IT32))) = "Thirty-two bits (unsigned)" constDocs c@(AType (ATInt (ITFixed IT64))) = "Sixty-four bits (unsigned)" constDocs c@(AType (ATInt (ITVec IT8 16))) = "Vectors of sixteen eight-bit values" constDocs c@(AType (ATInt (ITVec IT16 8))) = "Vectors of eight sixteen-bit values" constDocs c@(AType (ATInt (ITVec IT32 4))) = "Vectors of four thirty-two-bit values" constDocs c@(AType (ATInt (ITVec IT64 2))) = "Vectors of two sixty-four-bit values" constDocs (Fl f) = "A float" constDocs (I i) = "A fixed-precision integer" constDocs (BI i) = "An arbitrary-precision integer" constDocs (Str s) = "A string of length " ++ show (length s) constDocs (Ch c) = "A character" constDocs (B8 w) = "The eight-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B16 w) = "The sixteen-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B32 w) = "The thirty-two-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B64 w) = "The sixty-four-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B8V v) = "A vector of eight-bit values" constDocs (B16V v) = "A vector of sixteen-bit values" constDocs (B32V v) = "A vector of thirty-two-bit values" constDocs (B64V v) = "A vector of sixty-four-bit values" constDocs prim = "Undocumented" data Universe = NullType | UniqueType | AllTypes deriving (Eq, Ord) instance Show Universe where show UniqueType = "UniqueType" show NullType = "NullType" show AllTypes = "Type*" data Raw = Var Name | RBind Name (Binder Raw) Raw | RApp Raw Raw | RType | RUType Universe | RForce Raw | RConstant Const deriving (Show, Eq) instance Sized Raw where size (Var name) = 1 size (RBind name bind right) = 1 + size bind + size right size (RApp left right) = 1 + size left + size right size RType = 1 size (RUType _) = 1 size (RForce raw) = 1 + size raw size (RConstant const) = size const instance Pretty Raw OutputAnnotation where pretty = text . show {-! deriving instance Binary Raw deriving instance NFData Raw !-} -- The type parameter `b` will normally be something like `TT Name` or just -- `Raw`. We do not make a type-level distinction between TT terms that happen -- to be TT types and TT terms that are not TT types. -- | All binding forms are represented in a uniform fashion. This type only represents -- the types of bindings (and their values, if any); the attached identifiers are part -- of the 'Bind' constructor for the 'TT' type. data Binder b = Lam { binderTy :: !b {-^ type annotation for bound variable-}} | Pi { binderTy :: !b, binderKind :: !b } {-^ A binding that occurs in a function type expression, e.g. @(x:Int) -> ...@ -} | Let { binderTy :: !b, binderVal :: b {-^ value for bound variable-}} -- ^ A binding that occurs in a @let@ expression | NLet { binderTy :: !b, binderVal :: b } | Hole { binderTy :: !b} | GHole { envlen :: Int, binderTy :: !b} | Guess { binderTy :: !b, binderVal :: b } | PVar { binderTy :: !b } -- ^ A pattern variable | PVTy { binderTy :: !b } deriving (Show, Eq, Ord, Functor, Foldable, Traversable) {-! deriving instance Binary Binder deriving instance NFData Binder !-} instance Sized a => Sized (Binder a) where size (Lam ty) = 1 + size ty size (Pi ty _) = 1 + size ty size (Let ty val) = 1 + size ty + size val size (NLet ty val) = 1 + size ty + size val size (Hole ty) = 1 + size ty size (GHole _ ty) = 1 + size ty size (Guess ty val) = 1 + size ty + size val size (PVar ty) = 1 + size ty size (PVTy ty) = 1 + size ty fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b) fmapMB f (Let t v) = liftM2 Let (f t) (f v) fmapMB f (NLet t v) = liftM2 NLet (f t) (f v) fmapMB f (Guess t v) = liftM2 Guess (f t) (f v) fmapMB f (Lam t) = liftM Lam (f t) fmapMB f (Pi t k) = liftM2 Pi (f t) (f k) fmapMB f (Hole t) = liftM Hole (f t) fmapMB f (GHole i t) = liftM (GHole i) (f t) fmapMB f (PVar t) = liftM PVar (f t) fmapMB f (PVTy t) = liftM PVTy (f t) raw_apply :: Raw -> [Raw] -> Raw raw_apply f [] = f raw_apply f (a : as) = raw_apply (RApp f a) as raw_unapply :: Raw -> (Raw, [Raw]) raw_unapply t = ua [] t where ua args (RApp f a) = ua (a:args) f ua args t = (t, args) -- WELL TYPED TERMS --------------------------------------------------------- -- | Universe expressions for universe checking data UExp = UVar Int -- ^ universe variable | UVal Int -- ^ explicit universe level deriving (Eq, Ord) {-! deriving instance NFData UExp !-} instance Sized UExp where size _ = 1 -- We assume that universe levels have been checked, so anything external -- can just have the same universe variable and we won't get any new -- cycles. instance Binary UExp where put x = return () get = return (UVar (-1)) instance Show UExp where show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')] | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26) show (UVal x) = show x -- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")" -- | Universe constraints data UConstraint = ULT UExp UExp -- ^ Strictly less than | ULE UExp UExp -- ^ Less than or equal to deriving Eq instance Show UConstraint where show (ULT x y) = show x ++ " < " ++ show y show (ULE x y) = show x ++ " <= " ++ show y type UCs = (Int, [UConstraint]) data NameType = Bound | Ref | DCon {nt_tag :: Int, nt_arity :: Int, nt_unique :: Bool} -- ^ Data constructor | TCon {nt_tag :: Int, nt_arity :: Int} -- ^ Type constructor deriving (Show, Ord) {-! deriving instance Binary NameType deriving instance NFData NameType !-} instance Sized NameType where size _ = 1 instance Pretty NameType OutputAnnotation where pretty = text . show instance Eq NameType where Bound == Bound = True Ref == Ref = True DCon _ a _ == DCon _ b _ = (a == b) -- ignore tag TCon _ a == TCon _ b = (a == b) -- ignore tag _ == _ = False -- | Terms in the core language. The type parameter is the type of -- identifiers used for bindings and explicit named references; -- usually we use @TT 'Name'@. data TT n = P NameType n (TT n) -- ^ named references with type -- (P for "Parameter", motivated by McKinna and Pollack's -- Pure Type Systems Formalized) | V !Int -- ^ a resolved de Bruijn-indexed variable | Bind n !(Binder (TT n)) (TT n) -- ^ a binding | App !(TT n) (TT n) -- ^ function, function type, arg | Constant Const -- ^ constant | Proj (TT n) !Int -- ^ argument projection; runtime only -- (-1) is a special case for 'subtract one from BI' | Erased -- ^ an erased term | Impossible -- ^ special case for totality checking | TType UExp -- ^ the type of types at some level | UType Universe -- ^ Uniqueness type universe (disjoint from TType) deriving (Ord, Functor) {-! deriving instance Binary TT deriving instance NFData TT !-} class TermSize a where termsize :: Name -> a -> Int instance TermSize a => TermSize [a] where termsize n [] = 0 termsize n (x : xs) = termsize n x + termsize n xs instance TermSize (TT Name) where termsize n (P _ n' _) | n' == n = 1000000 -- recursive => really big | otherwise = 1 termsize n (V _) = 1 -- for `Bind` terms, we can erroneously declare a term -- "recursive => really big" if the name of the bound -- variable is the same as the name we're using -- So generate a different name in that case. termsize n (Bind n' (Let t v) sc) = let rn = if n == n' then sMN 0 "noname" else n in termsize rn v + termsize rn sc termsize n (Bind n' b sc) = let rn = if n == n' then sMN 0 "noname" else n in termsize rn sc termsize n (App f a) = termsize n f + termsize n a termsize n (Proj t i) = termsize n t termsize n _ = 1 instance Sized a => Sized (TT a) where size (P name n trm) = 1 + size name + size n + size trm size (V v) = 1 size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy size (App l r) = 1 + size l + size r size (Constant c) = size c size Erased = 1 size (TType u) = 1 + size u instance Pretty a o => Pretty (TT a) o where pretty _ = text "test" type EnvTT n = [(n, Binder (TT n))] data Datatype n = Data { d_typename :: n, d_typetag :: Int, d_type :: (TT n), d_unique :: Bool, d_cons :: [(n, TT n)] } deriving (Show, Functor, Eq) instance Eq n => Eq (TT n) where (==) (P xt x _) (P yt y _) = x == y (==) (V x) (V y) = x == y (==) (Bind _ xb xs) (Bind _ yb ys) = xs == ys && xb == yb (==) (App fx ax) (App fy ay) = ax == ay && fx == fy (==) (TType _) (TType _) = True -- deal with constraints later (==) (Constant x) (Constant y) = x == y (==) (Proj x i) (Proj y j) = x == y && i == j (==) Erased _ = True (==) _ Erased = True (==) _ _ = False -- * A few handy operations on well typed terms: -- | A term is injective iff it is a data constructor, type constructor, -- constant, the type Type, pi-binding, or an application of an injective -- term. isInjective :: TT n -> Bool isInjective (P (DCon _ _ _) _ _) = True isInjective (P (TCon _ _) _ _) = True isInjective (Constant _) = True isInjective (TType x) = True isInjective (Bind _ (Pi _ _) sc) = True isInjective (App f a) = isInjective f isInjective _ = False -- | Count the number of instances of a de Bruijn index in a term vinstances :: Int -> TT n -> Int vinstances i (V x) | i == x = 1 vinstances i (App f a) = vinstances i f + vinstances i a vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc where instancesB (Let t v) = vinstances i v instancesB _ = 0 vinstances i t = 0 -- | Replace the outermost (index 0) de Bruijn variable with the given term instantiate :: TT n -> TT n -> TT n instantiate e = subst 0 where subst i (V x) | i == x = e subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc) subst i (App f a) = App (subst i f) (subst i a) subst i (Proj x idx) = Proj (subst i x) idx subst i t = t -- | As 'instantiate', but also decrement the indices of all de Bruijn variables -- remaining in the term, so that there are no more references to the variable -- that has been substituted. substV :: TT n -> TT n -> TT n substV x tm = dropV 0 (instantiate x tm) where dropV i (V x) | x > i = V (x - 1) | otherwise = V x dropV i (Bind x b sc) = Bind x (fmap (dropV i) b) (dropV (i+1) sc) dropV i (App f a) = App (dropV i f) (dropV i a) dropV i (Proj x idx) = Proj (dropV i x) idx dropV i t = t -- | Replace all non-free de Bruijn references in the given term with references -- to the name of their binding. explicitNames :: TT n -> TT n explicitNames (Bind x b sc) = let b' = fmap explicitNames b in Bind x b' (explicitNames (instantiate (P Bound x (binderTy b')) sc)) explicitNames (App f a) = App (explicitNames f) (explicitNames a) explicitNames (Proj x idx) = Proj (explicitNames x) idx explicitNames t = t -- | Replace references to the given 'Name'-like id with references to -- de Bruijn index 0. pToV :: Eq n => n -> TT n -> TT n pToV n = pToV' n 0 pToV' n i (P _ x _) | n == x = V i pToV' n i (Bind x b sc) -- We can assume the inner scope has been pToVed already, so continue to -- resolve names from the *outer* scope which may happen to have the same id. | n == x = Bind x (fmap (pToV' n i) b) sc | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc) pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a) pToV' n i (Proj t idx) = Proj (pToV' n i t) idx pToV' n i t = t -- increase de Bruijn indices, as if a binder has been added addBinder :: TT n -> TT n addBinder t = ab 0 t where ab top (V i) | i >= top = V (i + 1) | otherwise = V i ab top (Bind x b sc) = Bind x (fmap (ab top) b) (ab (top + 1) sc) ab top (App f a) = App (ab top f) (ab top a) ab top (Proj t idx) = Proj (ab top t) idx ab top t = t -- | Convert several names. First in the list comes out as V 0 pToVs :: Eq n => [n] -> TT n -> TT n pToVs ns tm = pToVs' ns tm 0 where pToVs' [] tm i = tm pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1)) -- | Replace de Bruijn indices in the given term with explicit references to -- the names of the bindings they refer to. It is an error if the given term -- contains free de Bruijn indices. vToP :: TT n -> TT n vToP = vToP' [] where vToP' env (V i) = let (n, b) = (env !! i) in P Bound n (binderTy b) vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in Bind n b' (vToP' ((n, b'):env) sc) vToP' env (App f a) = App (vToP' env f) (vToP' env a) vToP' env t = t -- | Replace every non-free reference to the name of a binding in -- the given term with a de Bruijn index. finalise :: Eq n => TT n -> TT n finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc)) finalise (App f a) = App (finalise f) (finalise a) finalise t = t -- Once we've finished checking everything about a term we no longer need -- the type on the 'P' so erase it so save memory pEraseType :: TT n -> TT n pEraseType (P nt t _) = P nt t Erased pEraseType (App f a) = App (pEraseType f) (pEraseType a) pEraseType (Bind n b sc) = Bind n (fmap pEraseType b) (pEraseType sc) pEraseType t = t -- | As 'instantiate', but in addition to replacing @'V' 0@, -- replace references to the given 'Name'-like id. subst :: Eq n => n {-^ The id to replace -} -> TT n {-^ The replacement term -} -> TT n {-^ The term to replace in -} -> TT n -- subst n v tm = instantiate v (pToV n tm) subst n v tm = fst $ subst' 0 tm where -- keep track of updates to save allocations - this is a big win on -- large terms in particular -- ('Maybe' would be neater here, but >>= is not the right combinator. -- Feel free to tidy up, as long as it still saves allocating when no -- substitution happens...) subst' i (V x) | i == x = (v, True) subst' i (P _ x _) | n == x = (v, True) subst' i t@(Bind x b sc) | x /= n = let (b', ub) = substB' i b (sc', usc) = subst' (i+1) sc in if ub || usc then (Bind x b' sc', True) else (t, False) subst' i t@(App f a) = let (f', uf) = subst' i f (a', ua) = subst' i a in if uf || ua then (App f' a', True) else (t, False) subst' i t@(Proj x idx) = let (x', u) = subst' i x in if u then (Proj x' idx, u) else (t, False) subst' i t = (t, False) substB' i b@(Let t v) = let (t', ut) = subst' i t (v', uv) = subst' i v in if ut || uv then (Let t' v', True) else (b, False) substB' i b@(Guess t v) = let (t', ut) = subst' i t (v', uv) = subst' i v in if ut || uv then (Guess t' v', True) else (b, False) substB' i b = let (ty', u) = subst' i (binderTy b) in if u then (b { binderTy = ty' }, u) else (b, False) -- If there are no Vs in the term (i.e. in proof state) psubst :: Eq n => n -> TT n -> TT n -> TT n psubst n v tm = s' 0 tm where s' i (V x) | x > i = V (x - 1) | x == i = v | otherwise = V x s' i (P _ x _) | n == x = v s' i (Bind x b sc) | n == x = Bind x (fmap (s' i) b) sc | otherwise = Bind x (fmap (s' i) b) (s' (i+1) sc) s' i (App f a) = App (s' i f) (s' i a) s' i (Proj t idx) = Proj (s' i t) idx s' i t = t -- | As 'subst', but takes a list of (name, substitution) pairs instead -- of a single name and substitution substNames :: Eq n => [(n, TT n)] -> TT n -> TT n substNames [] t = t substNames ((n, tm) : xs) t = subst n tm (substNames xs t) -- | Replaces all terms equal (in the sense of @(==)@) to -- the old term with the new term. substTerm :: Eq n => TT n {-^ Old term -} -> TT n {-^ New term -} -> TT n {-^ template term -} -> TT n substTerm old new = st where st t | t == old = new st (App f a) = App (st f) (st a) st (Bind x b sc) = Bind x (fmap st b) (st sc) st t = t -- | Return number of occurrences of V 0 or bound name i the term occurrences :: Eq n => n -> TT n -> Int occurrences n t = execState (no' 0 t) 0 where no' i (V x) | i == x = do num <- get; put (num + 1) no' i (P Bound x _) | n == x = do num <- get; put (num + 1) no' i (Bind n b sc) = do noB' i b; no' (i+1) sc where noB' i (Let t v) = do no' i t; no' i v noB' i (Guess t v) = do no' i t; no' i v noB' i b = no' i (binderTy b) no' i (App f a) = do no' i f; no' i a no' i (Proj x _) = no' i x no' i _ = return () -- | Returns true if V 0 and bound name n do not occur in the term noOccurrence :: Eq n => n -> TT n -> Bool noOccurrence n t = no' 0 t where no' i (V x) = not (i == x) no' i (P Bound x _) = not (n == x) no' i (Bind n b sc) = noB' i b && no' (i+1) sc where noB' i (Let t v) = no' i t && no' i v noB' i (Guess t v) = no' i t && no' i v noB' i b = no' i (binderTy b) no' i (App f a) = no' i f && no' i a no' i (Proj x _) = no' i x no' i _ = True -- | Returns all names used free in the term freeNames :: Eq n => TT n -> [n] freeNames (P _ n _) = [n] freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n]) ++ freeNames t freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n]) freeNames (App f a) = nub $ freeNames f ++ freeNames a freeNames (Proj x i) = nub $ freeNames x freeNames _ = [] -- | Return the arity of a (normalised) type arity :: TT n -> Int arity (Bind n (Pi t _) sc) = 1 + arity sc arity _ = 0 -- | Deconstruct an application; returns the function and a list of arguments unApply :: TT n -> (TT n, [TT n]) unApply t = ua [] t where ua args (App f a) = ua (a:args) f ua args t = (t, args) -- | Returns a term representing the application of the first argument -- (a function) to every element of the second argument. mkApp :: TT n -> [TT n] -> TT n mkApp f [] = f mkApp f (a:as) = mkApp (App f a) as unList :: Term -> Maybe [Term] unList tm = case unApply tm of (nil, [_]) -> Just [] (cons, ([_, x, xs])) -> do rest <- unList xs return $ x:rest (f, args) -> Nothing -- | Cast a 'TT' term to a 'Raw' value, discarding universe information and -- the types of named references and replacing all de Bruijn indices -- with the corresponding name. It is an error if there are free de -- Bruijn indices. forget :: TT Name -> Raw forget tm = forgetEnv [] tm forgetEnv :: [Name] -> TT Name -> Raw forgetEnv env (P _ n _) = Var n forgetEnv env (V i) = Var (env !! i) forgetEnv env (Bind n b sc) = let n' = uniqueName n env in RBind n' (fmap (forgetEnv env) b) (forgetEnv (n':env) sc) forgetEnv env (App f a) = RApp (forgetEnv env f) (forgetEnv env a) forgetEnv env (Constant c) = RConstant c forgetEnv env (TType i) = RType forgetEnv env (UType u) = RUType u forgetEnv env Erased = RConstant Forgot -- | Introduce a 'Bind' into the given term for each element of the -- given list of (name, binder) pairs. bindAll :: [(n, Binder (TT n))] -> TT n -> TT n bindAll [] t = t bindAll ((n, b) : bs) t = Bind n b (bindAll bs t) -- | Like 'bindAll', but the 'Binder's are 'TT' terms instead. -- The first argument is a function to map @TT@ terms to @Binder@s. -- This function might often be something like 'Lam', which directly -- constructs a @Binder@ from a @TT@ term. bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs) -- | Return a list of pairs of the names of the outermost 'Pi'-bound -- variables in the given term, together with their types. getArgTys :: TT n -> [(n, TT n)] getArgTys (Bind n (PVar _) sc) = getArgTys sc getArgTys (Bind n (PVTy _) sc) = getArgTys sc getArgTys (Bind n (Pi t _) sc) = (n, t) : getArgTys sc getArgTys _ = [] getRetTy :: TT n -> TT n getRetTy (Bind n (PVar _) sc) = getRetTy sc getRetTy (Bind n (PVTy _) sc) = getRetTy sc getRetTy (Bind n (Pi _ _) sc) = getRetTy sc getRetTy sc = sc uniqueNameFrom :: [Name] -> [Name] -> Name uniqueNameFrom (s : supply) hs | s `elem` hs = uniqueNameFrom supply hs | otherwise = s uniqueName :: Name -> [Name] -> Name uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs | otherwise = n uniqueNameSet :: Name -> Set Name -> Name uniqueNameSet n hs | n `member` hs = uniqueNameSet (nextName n) hs | otherwise = n uniqueBinders :: [Name] -> TT Name -> TT Name uniqueBinders ns = ubSet (fromList ns) where ubSet ns (Bind n b sc) = let n' = uniqueNameSet n ns ns' = insert n' ns in Bind n' (fmap (ubSet ns') b) (ubSet ns' sc) ubSet ns (App f a) = App (ubSet ns f) (ubSet ns a) ubSet ns t = t nextName (NS x s) = NS (nextName x) s nextName (MN i n) = MN (i+1) n nextName (UN x) = let (num', nm') = T.span isDigit (T.reverse x) nm = T.reverse nm' num = readN (T.reverse num') in UN (nm `T.append` txt (show (num+1))) where readN x | not (T.null x) = read (T.unpack x) readN x = 0 nextName (SN x) = SN (nextName' x) where nextName' (WhereN i f x) = WhereN i f (nextName x) nextName' (WithN i n) = WithN i (nextName n) nextName' (InstanceN n ns) = InstanceN (nextName n) ns nextName' (ParentN n ns) = ParentN (nextName n) ns nextName' (CaseN n) = CaseN (nextName n) nextName' (ElimN n) = ElimN (nextName n) nextName' (MethodN n) = MethodN (nextName n) nextName' (InstanceCtorN n) = InstanceCtorN (nextName n) type Term = TT Name type Type = Term type Env = EnvTT Name -- | an environment with de Bruijn indices 'normalised' so that they all refer to -- this environment newtype WkEnvTT n = Wk (EnvTT n) type WkEnv = WkEnvTT Name instance (Eq n, Show n) => Show (TT n) where show t = showEnv [] t itBitsName IT8 = "Bits8" itBitsName IT16 = "Bits16" itBitsName IT32 = "Bits32" itBitsName IT64 = "Bits64" instance Show Const where show (I i) = show i show (BI i) = show i show (Fl f) = show f show (Ch c) = show c show (Str s) = show s show (B8 x) = show x show (B16 x) = show x show (B32 x) = show x show (B64 x) = show x show (B8V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (B16V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (B32V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (B64V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (AType ATFloat) = "Float" show (AType (ATInt ITBig)) = "Integer" show (AType (ATInt ITNative)) = "Int" show (AType (ATInt ITChar)) = "Char" show (AType (ATInt (ITFixed it))) = itBitsName it show (AType (ATInt (ITVec it c))) = itBitsName it ++ "x" ++ show c show StrType = "String" show BufferType = "prim__UnsafeBuffer" show PtrType = "Ptr" show ManagedPtrType = "ManagedPtr" show VoidType = "Void" showEnv :: (Eq n, Show n) => EnvTT n -> TT n -> String showEnv env t = showEnv' env t False showEnvDbg env t = showEnv' env t True prettyEnv env t = prettyEnv' env t False where prettyEnv' env t dbg = prettySe 10 env t dbg bracket outer inner p | inner > outer = lparen <> p <> rparen | otherwise = p prettySe p env (P nt n t) debug = pretty n <+> if debug then lbracket <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbracket else empty prettySe p env (V i) debug | i < length env = if debug then text . show . fst $ env!!i else lbracket <+> text (show i) <+> rbracket | otherwise = text "unbound" <+> text (show i) <+> text "!" prettySe p env (Bind n b@(Pi t _) sc) debug | noOccurrence n sc && not debug = bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug prettySe p env (Bind n b sc) debug = bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug prettySe p env (App f a) debug = bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug prettySe p env (Proj x i) debug = prettySe 1 env x debug <+> text ("!" ++ show i) prettySe p env (Constant c) debug = pretty c prettySe p env Erased debug = text "[_]" prettySe p env (TType i) debug = text "Type" <+> (text . show $ i) -- Render a `Binder` and its name prettySb env n (Lam t) = prettyB env "Ξ»" "=>" n t prettySb env n (Hole t) = prettyB env "?defer" "." n t prettySb env n (Pi t _) = prettyB env "(" ") ->" n t prettySb env n (PVar t) = prettyB env "pat" "." n t prettySb env n (PVTy t) = prettyB env "pty" "." n t prettySb env n (Let t v) = prettyBv env "let" "in" n t v prettySb env n (Guess t v) = prettyBv env "??" "in" n t v -- Use `op` and `sc` to delimit `n` (a binding name) and its type -- declaration -- e.g. "Ξ»x : Int =>" for the Lam case prettyB env op sc n t debug = text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc -- Like `prettyB`, but handle the bindings that have values in addition -- to names and types prettyBv env op sc n t v debug = text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+> prettySe 10 env v debug <> text sc showEnv' env t dbg = se 10 env t where se p env (P nt n t) = show n ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else "" se p env (V i) | i < length env && i >= 0 = (show $ fst $ env!!i) ++ if dbg then "{" ++ show i ++ "}" else "" | otherwise = "!!V " ++ show i ++ "!!" se p env (Bind n b@(Pi t k) sc) | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ arrow k ++ se 10 ((n,b):env) sc where arrow (TType _) = " -> " arrow u = " [" ++ show u ++ "] -> " se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a se p env (Proj x i) = se 1 env x ++ "!" ++ show i se p env (Constant c) = show c se p env Erased = "[__]" se p env Impossible = "[impossible]" se p env (TType i) = "Type " ++ show i se p env (UType u) = show u sb env n (Lam t) = showb env "\\ " " => " n t sb env n (Hole t) = showb env "? " ". " n t sb env n (GHole i t) = showb env "?defer " ". " n t sb env n (Pi t _) = showb env "(" ") -> " n t sb env n (PVar t) = showb env "pat " ". " n t sb env n (PVTy t) = showb env "pty " ". " n t sb env n (Let t v) = showbv env "let " " in " n t v sb env n (Guess t v) = showbv env "?? " " in " n t v showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++ se 10 env v ++ sc bracket outer inner str | inner > outer = "(" ++ str ++ ")" | otherwise = str -- | Check whether a term has any holes in it - impure if so pureTerm :: TT Name -> Bool pureTerm (App f a) = pureTerm f && pureTerm a pureTerm (Bind n b sc) = notClassName n && pureBinder b && pureTerm sc where pureBinder (Hole _) = False pureBinder (Guess _ _) = False pureBinder (Let t v) = pureTerm t && pureTerm v pureBinder t = pureTerm (binderTy t) notClassName (MN _ c) | c == txt "class" = False notClassName _ = True pureTerm _ = True -- | Weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings) weakenTm :: Int -> TT n -> TT n weakenTm i t = wk i 0 t where wk i min (V x) | x >= min = V (i + x) wk i m (App f a) = App (wk i m f) (wk i m a) wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc) wk i m t = t wkb i m t = fmap (wk i m) t -- | Weaken an environment so that all the de Bruijn indices are correct according -- to the latest bound variable weakenEnv :: EnvTT n -> EnvTT n weakenEnv env = wk (length env - 1) env where wk i [] = [] wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v) weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v) weakenTmB i t = t { binderTy = weakenTm i (binderTy t) } -- | Weaken every term in the environment by the given amount weakenTmEnv :: Int -> EnvTT n -> EnvTT n weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b)) -- | Gather up all the outer 'PVar's and 'Hole's in an expression and reintroduce -- them in a canonical order orderPats :: Term -> Term orderPats tm = op [] tm where op [] (App f a) = App f (op [] a) -- for Infer terms op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc op ps (Bind n (Pi t k) sc) = op ((n, Pi t k) : ps) sc op ps sc = bindAll (sortP ps) sc sortP ps = pick [] (reverse ps) pick acc [] = reverse acc pick acc ((n, t) : ps) = pick (insert n t acc) ps insert n t [] = [(n, t)] insert n t ((n',t') : ps) | n `elem` (refsIn (binderTy t') ++ concatMap refsIn (map (binderTy . snd) ps)) = (n', t') : insert n t ps | otherwise = (n,t):(n',t'):ps refsIn :: TT Name -> [Name] refsIn (P _ n _) = [n] refsIn (Bind n b t) = nub $ nb b ++ (refsIn t \\ [n]) where nb (Let t v) = nub (refsIn t) ++ nub (refsIn v) nb (Guess t v) = nub (refsIn t) ++ nub (refsIn v) nb t = refsIn (binderTy t) refsIn (App f a) = nub (refsIn f ++ refsIn a) refsIn _ = [] -- Make sure all the pattern bindings are as far out as possible liftPats :: Term -> Term liftPats tm = let (tm', ps) = runState (getPats tm) [] in orderPats $ bindPats (reverse ps) tm' where bindPats [] tm = tm bindPats ((n, t):ps) tm | n `notElem` map fst ps = Bind n (PVar t) (bindPats ps tm) | otherwise = bindPats ps tm getPats :: Term -> State [(Name, Type)] Term getPats (Bind n (PVar t) sc) = do ps <- get put ((n, t) : ps) getPats sc getPats (Bind n (Guess t v) sc) = do t' <- getPats t v' <- getPats v sc' <- getPats sc return (Bind n (Guess t' v') sc') getPats (Bind n (Let t v) sc) = do t' <- getPats t v' <- getPats v sc' <- getPats sc return (Bind n (Let t' v') sc') getPats (Bind n (Pi t k) sc) = do t' <- getPats t k' <- getPats k sc' <- getPats sc return (Bind n (Pi t' k') sc') getPats (Bind n (Lam t) sc) = do t' <- getPats t sc' <- getPats sc return (Bind n (Lam t') sc') getPats (Bind n (Hole t) sc) = do t' <- getPats t sc' <- getPats sc return (Bind n (Hole t') sc') getPats (App f a) = do f' <- getPats f a' <- getPats a return (App f' a') getPats t = return t allTTNames :: Eq n => TT n -> [n] allTTNames = nub . allNamesIn where allNamesIn (P _ n _) = [n] allNamesIn (Bind n b t) = [n] ++ nb b ++ allNamesIn t where nb (Let t v) = allNamesIn t ++ allNamesIn v nb (Guess t v) = allNamesIn t ++ allNamesIn v nb t = allNamesIn (binderTy t) allNamesIn (App f a) = allNamesIn f ++ allNamesIn a allNamesIn _ = []
andyarvanitis/Idris-dev
src/Idris/Core/TT.hs
bsd-3-clause
54,225
0
17
17,184
20,636
10,367
10,269
-1
-1
-- | Simple but usefull functions, those match no specific module. module Youtan.Utils where -- | Applies a function while the condition are met. while :: ( a -> a -> Bool ) -> ( a -> a ) -> a -> a while con f v = let step x y = if x `con` y then step ( f x ) x else x in step ( f v ) v
triplepointfive/Youtan
src/Youtan/Utils.hs
bsd-3-clause
304
0
12
90
107
57
50
4
2
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeInType #-} module Functor where import Control.Category import Data.Functor.Compose import Data.Kind (Type) import Prelude hiding (Functor (..), id, (.)) type family Cat k :: k -> k -> Type type Catty a = Category (Cat a) class (Catty j, Catty k) => Functor (f :: j -> k) where fmap :: Cat j a b -> Cat k (f a) (f b) type instance Cat Type = (->) instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (f a) instance Functor ((,) a) where fmap f (a, b) = (a, f b) instance Functor [] where fmap = map instance Functor (Either a) where fmap _ (Left a) = Left a fmap f (Right b) = Right $ f b instance Functor ((->) a) where fmap = (.) instance (Functor f, Functor g) => Functor (Compose f g) where fmap f = Compose . fmap (fmap f) . getCompose newtype Natural (cat :: k -> k -> Type) (f :: j -> k) (g :: j -> k) = Natural { runNatural :: forall x. cat (f x) (g x) } type instance Cat (j -> k) = Natural (Cat k) instance Category k => Category (Natural k) where id = Natural id Natural f . Natural g = Natural (f . g) instance Functor (,) where fmap f = Natural $ \(a, x) -> (f a, x) instance Functor Either where fmap f = Natural $ either (Left . f) Right instance Functor f => Functor (Compose f) where fmap f = Natural $ Compose . fmap (runNatural f) . getCompose fmap1 :: (Catty j, Catty k, Functor f) => Cat j a b -> Cat k (f a x) (f b x) fmap1 = runNatural . fmap instance Functor Compose where fmap f = Natural $ Natural $ Compose . runNatural f . getCompose fmap2 :: (Catty j, Catty k, Functor f) => Cat j a b -> Cat k (f a x y) (f b x y) fmap2 = runNatural . runNatural . fmap class (Catty j, Catty k) => Contravariant (f :: j -> k) where contramap :: Cat j a b -> Cat k (f b) (f a) instance Contravariant (->) where contramap g = Natural (. g) instance (Catty k, cat ~ Cat k) => Contravariant (Natural cat) where contramap g = Natural (. g)
isovector/category-theory
src/Functor.hs
bsd-3-clause
2,249
0
10
539
1,010
535
475
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 This module defines interface types and binders -} {-# LANGUAGE CPP, FlexibleInstances, BangPatterns #-} {-# LANGUAGE MultiWayIf #-} -- FlexibleInstances for Binary (DefMethSpec IfaceType) module IfaceType ( IfExtName, IfLclName, IfaceType(..), IfacePredType, IfaceKind, IfaceCoercion(..), IfaceUnivCoProv(..), IfaceTyCon(..), IfaceTyConInfo(..), IfaceTyConSort(..), IsPromoted(..), IfaceTyLit(..), IfaceTcArgs(..), IfaceContext, IfaceBndr(..), IfaceOneShot(..), IfaceLamBndr, IfaceTvBndr, IfaceIdBndr, IfaceTyConBinder, IfaceForAllBndr, ArgFlag(..), ShowForAllFlag(..), ifForAllBndrTyVar, ifForAllBndrName, ifTyConBinderTyVar, ifTyConBinderName, -- Equality testing isIfaceLiftedTypeKind, -- Conversion from IfaceTcArgs -> [IfaceType] tcArgsIfaceTypes, -- Printing pprIfaceType, pprParendIfaceType, pprPrecIfaceType, pprIfaceContext, pprIfaceContextArr, pprIfaceIdBndr, pprIfaceLamBndr, pprIfaceTvBndr, pprIfaceTyConBinders, pprIfaceBndrs, pprIfaceTcArgs, pprParendIfaceTcArgs, pprIfaceForAllPart, pprIfaceForAllPartMust, pprIfaceForAll, pprIfaceSigmaType, pprIfaceTyLit, pprIfaceCoercion, pprParendIfaceCoercion, splitIfaceSigmaTy, pprIfaceTypeApp, pprUserIfaceForAll, pprIfaceCoTcApp, pprTyTcApp, pprIfacePrefixApp, suppressIfaceInvisibles, stripIfaceInvisVars, stripInvisArgs, mkIfaceTySubst, substIfaceTyVar, substIfaceTcArgs, inDomIfaceTySubst ) where #include "HsVersions.h" import GhcPrelude import {-# SOURCE #-} TysWiredIn ( liftedRepDataConTyCon ) import DynFlags import TyCon hiding ( pprPromotionQuote ) import CoAxiom import Var import PrelNames import Name import BasicTypes import Binary import Outputable import FastString import FastStringEnv import Util import Data.Maybe( isJust ) import Data.List (foldl') import qualified Data.Semigroup as Semi {- ************************************************************************ * * Local (nested) binders * * ************************************************************************ -} type IfLclName = FastString -- A local name in iface syntax type IfExtName = Name -- An External or WiredIn Name can appear in IfaceSyn -- (However Internal or System Names never should) data IfaceBndr -- Local (non-top-level) binders = IfaceIdBndr {-# UNPACK #-} !IfaceIdBndr | IfaceTvBndr {-# UNPACK #-} !IfaceTvBndr type IfaceIdBndr = (IfLclName, IfaceType) type IfaceTvBndr = (IfLclName, IfaceKind) ifaceTvBndrName :: IfaceTvBndr -> IfLclName ifaceTvBndrName (n,_) = n type IfaceLamBndr = (IfaceBndr, IfaceOneShot) data IfaceOneShot -- See Note [Preserve OneShotInfo] in CoreTicy = IfaceNoOneShot -- and Note [The oneShot function] in MkId | IfaceOneShot {- %************************************************************************ %* * IfaceType %* * %************************************************************************ -} ------------------------------- type IfaceKind = IfaceType data IfaceType -- A kind of universal type, used for types and kinds = IfaceFreeTyVar TyVar -- See Note [Free tyvars in IfaceType] | IfaceTyVar IfLclName -- Type/coercion variable only, not tycon | IfaceLitTy IfaceTyLit | IfaceAppTy IfaceType IfaceType | IfaceFunTy IfaceType IfaceType | IfaceDFunTy IfaceType IfaceType | IfaceForAllTy IfaceForAllBndr IfaceType | IfaceTyConApp IfaceTyCon IfaceTcArgs -- Not necessarily saturated -- Includes newtypes, synonyms, tuples | IfaceCastTy IfaceType IfaceCoercion | IfaceCoercionTy IfaceCoercion | IfaceTupleTy -- Saturated tuples (unsaturated ones use IfaceTyConApp) TupleSort -- What sort of tuple? IsPromoted -- A bit like IfaceTyCon IfaceTcArgs -- arity = length args -- For promoted data cons, the kind args are omitted type IfacePredType = IfaceType type IfaceContext = [IfacePredType] data IfaceTyLit = IfaceNumTyLit Integer | IfaceStrTyLit FastString deriving (Eq) type IfaceTyConBinder = TyVarBndr IfaceTvBndr TyConBndrVis type IfaceForAllBndr = TyVarBndr IfaceTvBndr ArgFlag -- See Note [Suppressing invisible arguments] -- We use a new list type (rather than [(IfaceType,Bool)], because -- it'll be more compact and faster to parse in interface -- files. Rather than two bytes and two decisions (nil/cons, and -- type/kind) there'll just be one. data IfaceTcArgs = ITC_Nil | ITC_Vis IfaceType IfaceTcArgs -- "Vis" means show when pretty-printing | ITC_Invis IfaceKind IfaceTcArgs -- "Invis" means don't show when pretty-printing -- except with -fprint-explicit-kinds instance Semi.Semigroup IfaceTcArgs where ITC_Nil <> xs = xs ITC_Vis ty rest <> xs = ITC_Vis ty (rest Semi.<> xs) ITC_Invis ki rest <> xs = ITC_Invis ki (rest Semi.<> xs) instance Monoid IfaceTcArgs where mempty = ITC_Nil mappend = (Semi.<>) -- Encodes type constructors, kind constructors, -- coercion constructors, the lot. -- We have to tag them in order to pretty print them -- properly. data IfaceTyCon = IfaceTyCon { ifaceTyConName :: IfExtName , ifaceTyConInfo :: IfaceTyConInfo } deriving (Eq) -- | Is a TyCon a promoted data constructor or just a normal type constructor? data IsPromoted = IsNotPromoted | IsPromoted deriving (Eq) -- | The various types of TyCons which have special, built-in syntax. data IfaceTyConSort = IfaceNormalTyCon -- ^ a regular tycon | IfaceTupleTyCon !Arity !TupleSort -- ^ e.g. @(a, b, c)@ or @(#a, b, c#)@. -- The arity is the tuple width, not the tycon arity -- (which is twice the width in the case of unboxed -- tuples). | IfaceSumTyCon !Arity -- ^ e.g. @(a | b | c)@ | IfaceEqualityTyCon -- ^ A heterogeneous equality TyCon -- (i.e. eqPrimTyCon, eqReprPrimTyCon, heqTyCon) -- that is actually being applied to two types -- of the same kind. This affects pretty-printing -- only: see Note [Equality predicates in IfaceType] deriving (Eq) {- Note [Free tyvars in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nowadays (since Nov 16, 2016) we pretty-print a Type by converting to an IfaceType and pretty printing that. This eliminates a lot of pretty-print duplication, and it matches what we do with pretty-printing TyThings. It works fine for closed types, but when printing debug traces (e.g. when using -ddump-tc-trace) we print a lot of /open/ types. These types are full of TcTyVars, and it's absolutely crucial to print them in their full glory, with their unique, TcTyVarDetails etc. So we simply embed a TyVar in IfaceType with the IfaceFreeTyVar constructor. Note that: * We never expect to serialise an IfaceFreeTyVar into an interface file, nor to deserialise one. IfaceFreeTyVar is used only in the "convert to IfaceType and then pretty-print" pipeline. We do the same for covars, naturally. Note [Equality predicates in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC has several varieties of type equality (see Note [The equality types story] in TysPrim for details). In an effort to avoid confusing users, we suppress the differences during "normal" pretty printing. Specifically we display them like this: Predicate Pretty-printed as Homogeneous case Heterogeneous case ---------------- ----------------- ------------------- (~) eqTyCon ~ N/A (~~) heqTyCon ~ ~~ (~#) eqPrimTyCon ~# ~~ (~R#) eqReprPrimTyCon Coercible Coercible By "homogeneeous case" we mean cases where a hetero-kinded equality (all but the first above) is actually applied to two identical kinds. Unfortunately, determining this from an IfaceType isn't possible since we can't see through type synonyms. Consequently, we need to record whether this particular application is homogeneous in IfaceTyConSort for the purposes of pretty-printing. All this suppresses information. To get the ground truth, use -dppr-debug (see 'print_eqs' in 'ppr_equality'). See Note [The equality types story] in TysPrim. -} data IfaceTyConInfo -- Used to guide pretty-printing -- and to disambiguate D from 'D (they share a name) = IfaceTyConInfo { ifaceTyConIsPromoted :: IsPromoted , ifaceTyConSort :: IfaceTyConSort } deriving (Eq) data IfaceCoercion = IfaceReflCo Role IfaceType | IfaceFunCo Role IfaceCoercion IfaceCoercion | IfaceTyConAppCo Role IfaceTyCon [IfaceCoercion] | IfaceAppCo IfaceCoercion IfaceCoercion | IfaceForAllCo IfaceTvBndr IfaceCoercion IfaceCoercion | IfaceFreeCoVar CoVar -- See Note [Free tyvars in IfaceType] | IfaceCoVarCo IfLclName | IfaceAxiomInstCo IfExtName BranchIndex [IfaceCoercion] | IfaceUnivCo IfaceUnivCoProv Role IfaceType IfaceType | IfaceSymCo IfaceCoercion | IfaceTransCo IfaceCoercion IfaceCoercion | IfaceNthCo Int IfaceCoercion | IfaceLRCo LeftOrRight IfaceCoercion | IfaceInstCo IfaceCoercion IfaceCoercion | IfaceCoherenceCo IfaceCoercion IfaceCoercion | IfaceKindCo IfaceCoercion | IfaceSubCo IfaceCoercion | IfaceAxiomRuleCo IfLclName [IfaceCoercion] data IfaceUnivCoProv = IfaceUnsafeCoerceProv | IfacePhantomProv IfaceCoercion | IfaceProofIrrelProv IfaceCoercion | IfacePluginProv String | IfaceHoleProv Unique -- ^ See Note [Holes in IfaceUnivCoProv] {- Note [Holes in IfaceUnivCoProv] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When typechecking fails the typechecker will produce a HoleProv UnivCoProv to stand in place of the unproven assertion. While we generally don't want to let these unproven assertions leak into interface files, we still need to be able to pretty-print them as we use IfaceType's pretty-printer to render Types. For this reason IfaceUnivCoProv has a IfaceHoleProv constructor; however, we fails when asked to serialize to a IfaceHoleProv to ensure that they don't end up in an interface file. To avoid an import loop between IfaceType and TyCoRep we only keep the hole's Unique, since that is all we need to print. -} {- %************************************************************************ %* * Functions over IFaceTypes * * ************************************************************************ -} ifaceTyConHasKey :: IfaceTyCon -> Unique -> Bool ifaceTyConHasKey tc key = ifaceTyConName tc `hasKey` key isIfaceLiftedTypeKind :: IfaceKind -> Bool isIfaceLiftedTypeKind (IfaceTyConApp tc ITC_Nil) = isLiftedTypeKindTyConName (ifaceTyConName tc) isIfaceLiftedTypeKind (IfaceTyConApp tc (ITC_Vis (IfaceTyConApp ptr_rep_lifted ITC_Nil) ITC_Nil)) = tc `ifaceTyConHasKey` tYPETyConKey && ptr_rep_lifted `ifaceTyConHasKey` liftedRepDataConKey isIfaceLiftedTypeKind _ = False splitIfaceSigmaTy :: IfaceType -> ([IfaceForAllBndr], [IfacePredType], IfaceType) -- Mainly for printing purposes splitIfaceSigmaTy ty = (bndrs, theta, tau) where (bndrs, rho) = split_foralls ty (theta, tau) = split_rho rho split_foralls (IfaceForAllTy bndr ty) = case split_foralls ty of { (bndrs, rho) -> (bndr:bndrs, rho) } split_foralls rho = ([], rho) split_rho (IfaceDFunTy ty1 ty2) = case split_rho ty2 of { (ps, tau) -> (ty1:ps, tau) } split_rho tau = ([], tau) suppressIfaceInvisibles :: DynFlags -> [IfaceTyConBinder] -> [a] -> [a] suppressIfaceInvisibles dflags tys xs | gopt Opt_PrintExplicitKinds dflags = xs | otherwise = suppress tys xs where suppress _ [] = [] suppress [] a = a suppress (k:ks) (x:xs) | isInvisibleTyConBinder k = suppress ks xs | otherwise = x : suppress ks xs stripIfaceInvisVars :: DynFlags -> [IfaceTyConBinder] -> [IfaceTyConBinder] stripIfaceInvisVars dflags tyvars | gopt Opt_PrintExplicitKinds dflags = tyvars | otherwise = filterOut isInvisibleTyConBinder tyvars -- | Extract an 'IfaceTvBndr' from an 'IfaceForAllBndr'. ifForAllBndrTyVar :: IfaceForAllBndr -> IfaceTvBndr ifForAllBndrTyVar = binderVar -- | Extract the variable name from an 'IfaceForAllBndr'. ifForAllBndrName :: IfaceForAllBndr -> IfLclName ifForAllBndrName fab = ifaceTvBndrName (ifForAllBndrTyVar fab) -- | Extract an 'IfaceTvBndr' from an 'IfaceTyConBinder'. ifTyConBinderTyVar :: IfaceTyConBinder -> IfaceTvBndr ifTyConBinderTyVar = binderVar -- | Extract the variable name from an 'IfaceTyConBinder'. ifTyConBinderName :: IfaceTyConBinder -> IfLclName ifTyConBinderName tcb = ifaceTvBndrName (ifTyConBinderTyVar tcb) ifTypeIsVarFree :: IfaceType -> Bool -- Returns True if the type definitely has no variables at all -- Just used to control pretty printing ifTypeIsVarFree ty = go ty where go (IfaceTyVar {}) = False go (IfaceFreeTyVar {}) = False go (IfaceAppTy fun arg) = go fun && go arg go (IfaceFunTy arg res) = go arg && go res go (IfaceDFunTy arg res) = go arg && go res go (IfaceForAllTy {}) = False go (IfaceTyConApp _ args) = go_args args go (IfaceTupleTy _ _ args) = go_args args go (IfaceLitTy _) = True go (IfaceCastTy {}) = False -- Safe go (IfaceCoercionTy {}) = False -- Safe go_args ITC_Nil = True go_args (ITC_Vis arg args) = go arg && go_args args go_args (ITC_Invis arg args) = go arg && go_args args {- Note [Substitution on IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Substitutions on IfaceType are done only during pretty-printing to construct the result type of a GADT, and does not deal with binders (eg IfaceForAll), so it doesn't need fancy capture stuff. -} type IfaceTySubst = FastStringEnv IfaceType -- Note [Substitution on IfaceType] mkIfaceTySubst :: [(IfLclName,IfaceType)] -> IfaceTySubst -- See Note [Substitution on IfaceType] mkIfaceTySubst eq_spec = mkFsEnv eq_spec inDomIfaceTySubst :: IfaceTySubst -> IfaceTvBndr -> Bool -- See Note [Substitution on IfaceType] inDomIfaceTySubst subst (fs, _) = isJust (lookupFsEnv subst fs) substIfaceType :: IfaceTySubst -> IfaceType -> IfaceType -- See Note [Substitution on IfaceType] substIfaceType env ty = go ty where go (IfaceFreeTyVar tv) = IfaceFreeTyVar tv go (IfaceTyVar tv) = substIfaceTyVar env tv go (IfaceAppTy t1 t2) = IfaceAppTy (go t1) (go t2) go (IfaceFunTy t1 t2) = IfaceFunTy (go t1) (go t2) go (IfaceDFunTy t1 t2) = IfaceDFunTy (go t1) (go t2) go ty@(IfaceLitTy {}) = ty go (IfaceTyConApp tc tys) = IfaceTyConApp tc (substIfaceTcArgs env tys) go (IfaceTupleTy s i tys) = IfaceTupleTy s i (substIfaceTcArgs env tys) go (IfaceForAllTy {}) = pprPanic "substIfaceType" (ppr ty) go (IfaceCastTy ty co) = IfaceCastTy (go ty) (go_co co) go (IfaceCoercionTy co) = IfaceCoercionTy (go_co co) go_co (IfaceReflCo r ty) = IfaceReflCo r (go ty) go_co (IfaceFunCo r c1 c2) = IfaceFunCo r (go_co c1) (go_co c2) go_co (IfaceTyConAppCo r tc cos) = IfaceTyConAppCo r tc (go_cos cos) go_co (IfaceAppCo c1 c2) = IfaceAppCo (go_co c1) (go_co c2) go_co (IfaceForAllCo {}) = pprPanic "substIfaceCoercion" (ppr ty) go_co (IfaceFreeCoVar cv) = IfaceFreeCoVar cv go_co (IfaceCoVarCo cv) = IfaceCoVarCo cv go_co (IfaceAxiomInstCo a i cos) = IfaceAxiomInstCo a i (go_cos cos) go_co (IfaceUnivCo prov r t1 t2) = IfaceUnivCo (go_prov prov) r (go t1) (go t2) go_co (IfaceSymCo co) = IfaceSymCo (go_co co) go_co (IfaceTransCo co1 co2) = IfaceTransCo (go_co co1) (go_co co2) go_co (IfaceNthCo n co) = IfaceNthCo n (go_co co) go_co (IfaceLRCo lr co) = IfaceLRCo lr (go_co co) go_co (IfaceInstCo c1 c2) = IfaceInstCo (go_co c1) (go_co c2) go_co (IfaceCoherenceCo c1 c2) = IfaceCoherenceCo (go_co c1) (go_co c2) go_co (IfaceKindCo co) = IfaceKindCo (go_co co) go_co (IfaceSubCo co) = IfaceSubCo (go_co co) go_co (IfaceAxiomRuleCo n cos) = IfaceAxiomRuleCo n (go_cos cos) go_cos = map go_co go_prov IfaceUnsafeCoerceProv = IfaceUnsafeCoerceProv go_prov (IfacePhantomProv co) = IfacePhantomProv (go_co co) go_prov (IfaceProofIrrelProv co) = IfaceProofIrrelProv (go_co co) go_prov (IfacePluginProv str) = IfacePluginProv str go_prov (IfaceHoleProv h) = IfaceHoleProv h substIfaceTcArgs :: IfaceTySubst -> IfaceTcArgs -> IfaceTcArgs substIfaceTcArgs env args = go args where go ITC_Nil = ITC_Nil go (ITC_Vis ty tys) = ITC_Vis (substIfaceType env ty) (go tys) go (ITC_Invis ty tys) = ITC_Invis (substIfaceType env ty) (go tys) substIfaceTyVar :: IfaceTySubst -> IfLclName -> IfaceType substIfaceTyVar env tv | Just ty <- lookupFsEnv env tv = ty | otherwise = IfaceTyVar tv {- ************************************************************************ * * Functions over IFaceTcArgs * * ************************************************************************ -} stripInvisArgs :: DynFlags -> IfaceTcArgs -> IfaceTcArgs stripInvisArgs dflags tys | gopt Opt_PrintExplicitKinds dflags = tys | otherwise = suppress_invis tys where suppress_invis c = case c of ITC_Invis _ ts -> suppress_invis ts _ -> c tcArgsIfaceTypes :: IfaceTcArgs -> [IfaceType] tcArgsIfaceTypes ITC_Nil = [] tcArgsIfaceTypes (ITC_Invis t ts) = t : tcArgsIfaceTypes ts tcArgsIfaceTypes (ITC_Vis t ts) = t : tcArgsIfaceTypes ts ifaceVisTcArgsLength :: IfaceTcArgs -> Int ifaceVisTcArgsLength = go 0 where go !n ITC_Nil = n go n (ITC_Vis _ rest) = go (n+1) rest go n (ITC_Invis _ rest) = go n rest {- Note [Suppressing invisible arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use the IfaceTcArgs to specify which of the arguments to a type constructor should be displayed when pretty-printing, under the control of -fprint-explicit-kinds. See also Type.filterOutInvisibleTypes. For example, given T :: forall k. (k->*) -> k -> * -- Ordinary kind polymorphism 'Just :: forall k. k -> 'Maybe k -- Promoted we want T * Tree Int prints as T Tree Int 'Just * prints as Just * ************************************************************************ * * Pretty-printing * * ************************************************************************ -} if_print_coercions :: SDoc -- ^ if printing coercions -> SDoc -- ^ otherwise -> SDoc if_print_coercions yes no = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> if gopt Opt_PrintExplicitCoercions dflags || dumpStyle style || debugStyle style then yes else no pprIfaceInfixApp :: TyPrec -> SDoc -> SDoc -> SDoc -> SDoc pprIfaceInfixApp ctxt_prec pp_tc pp_ty1 pp_ty2 = maybeParen ctxt_prec TyOpPrec $ sep [pp_ty1, pp_tc <+> pp_ty2] pprIfacePrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc pprIfacePrefixApp ctxt_prec pp_fun pp_tys | null pp_tys = pp_fun | otherwise = maybeParen ctxt_prec TyConPrec $ hang pp_fun 2 (sep pp_tys) -- ----------------------------- Printing binders ------------------------------------ instance Outputable IfaceBndr where ppr (IfaceIdBndr bndr) = pprIfaceIdBndr bndr ppr (IfaceTvBndr bndr) = char '@' <+> pprIfaceTvBndr False bndr pprIfaceBndrs :: [IfaceBndr] -> SDoc pprIfaceBndrs bs = sep (map ppr bs) pprIfaceLamBndr :: IfaceLamBndr -> SDoc pprIfaceLamBndr (b, IfaceNoOneShot) = ppr b pprIfaceLamBndr (b, IfaceOneShot) = ppr b <> text "[OneShot]" pprIfaceIdBndr :: IfaceIdBndr -> SDoc pprIfaceIdBndr (name, ty) = parens (ppr name <+> dcolon <+> ppr ty) pprIfaceTvBndr :: Bool -> IfaceTvBndr -> SDoc pprIfaceTvBndr use_parens (tv, ki) | isIfaceLiftedTypeKind ki = ppr tv | otherwise = maybe_parens (ppr tv <+> dcolon <+> ppr ki) where maybe_parens | use_parens = parens | otherwise = id pprIfaceTyConBinders :: [IfaceTyConBinder] -> SDoc pprIfaceTyConBinders = sep . map go where go tcb = pprIfaceTvBndr True (ifTyConBinderTyVar tcb) instance Binary IfaceBndr where put_ bh (IfaceIdBndr aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceTvBndr ab) = do putByte bh 1 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceIdBndr aa) _ -> do ab <- get bh return (IfaceTvBndr ab) instance Binary IfaceOneShot where put_ bh IfaceNoOneShot = do putByte bh 0 put_ bh IfaceOneShot = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return IfaceNoOneShot _ -> do return IfaceOneShot -- ----------------------------- Printing IfaceType ------------------------------------ --------------------------------- instance Outputable IfaceType where ppr ty = pprIfaceType ty pprIfaceType, pprParendIfaceType :: IfaceType -> SDoc pprIfaceType = pprPrecIfaceType TopPrec pprParendIfaceType = pprPrecIfaceType TyConPrec pprPrecIfaceType :: TyPrec -> IfaceType -> SDoc pprPrecIfaceType prec ty = eliminateRuntimeRep (ppr_ty prec) ty ppr_ty :: TyPrec -> IfaceType -> SDoc ppr_ty _ (IfaceFreeTyVar tyvar) = ppr tyvar -- This is the main reson for IfaceFreeTyVar! ppr_ty _ (IfaceTyVar tyvar) = ppr tyvar -- See Note [TcTyVars in IfaceType] ppr_ty ctxt_prec (IfaceTyConApp tc tys) = pprTyTcApp ctxt_prec tc tys ppr_ty _ (IfaceTupleTy i p tys) = pprTuple i p tys ppr_ty _ (IfaceLitTy n) = pprIfaceTyLit n -- Function types ppr_ty ctxt_prec (IfaceFunTy ty1 ty2) = -- We don't want to lose synonyms, so we mustn't use splitFunTys here. maybeParen ctxt_prec FunPrec $ sep [ppr_ty FunPrec ty1, sep (ppr_fun_tail ty2)] where ppr_fun_tail (IfaceFunTy ty1 ty2) = (arrow <+> ppr_ty FunPrec ty1) : ppr_fun_tail ty2 ppr_fun_tail other_ty = [arrow <+> pprIfaceType other_ty] ppr_ty ctxt_prec (IfaceAppTy ty1 ty2) = if_print_coercions ppr_app_ty ppr_app_ty_no_casts where ppr_app_ty = maybeParen ctxt_prec TyConPrec $ ppr_ty FunPrec ty1 <+> ppr_ty TyConPrec ty2 -- Strip any casts from the head of the application ppr_app_ty_no_casts = case split_app_tys ty1 (ITC_Vis ty2 ITC_Nil) of (IfaceCastTy head _, args) -> ppr_ty ctxt_prec (mk_app_tys head args) _ -> ppr_app_ty split_app_tys :: IfaceType -> IfaceTcArgs -> (IfaceType, IfaceTcArgs) split_app_tys (IfaceAppTy t1 t2) args = split_app_tys t1 (t2 `ITC_Vis` args) split_app_tys head args = (head, args) mk_app_tys :: IfaceType -> IfaceTcArgs -> IfaceType mk_app_tys (IfaceTyConApp tc tys1) tys2 = IfaceTyConApp tc (tys1 `mappend` tys2) mk_app_tys t1 tys2 = foldl' IfaceAppTy t1 (tcArgsIfaceTypes tys2) ppr_ty ctxt_prec (IfaceCastTy ty co) = if_print_coercions (parens (ppr_ty TopPrec ty <+> text "|>" <+> ppr co)) (ppr_ty ctxt_prec ty) ppr_ty ctxt_prec (IfaceCoercionTy co) = if_print_coercions (ppr_co ctxt_prec co) (text "<>") ppr_ty ctxt_prec ty = maybeParen ctxt_prec FunPrec (pprIfaceSigmaType ShowForAllMust ty) {- Note [Defaulting RuntimeRep variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RuntimeRep variables are considered by many (most?) users to be little more than syntactic noise. When the notion was introduced there was a signficant and understandable push-back from those with pedagogy in mind, which argued that RuntimeRep variables would throw a wrench into nearly any teach approach since they appear in even the lowly ($) function's type, ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b which is significantly less readable than its non RuntimeRep-polymorphic type of ($) :: (a -> b) -> a -> b Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell programs, so it makes little sense to make all users pay this syntactic overhead. For this reason it was decided that we would hide RuntimeRep variables for now (see #11549). We do this by defaulting all type variables of kind RuntimeRep to PtrLiftedRep. This is done in a pass right before pretty-printing (defaultRuntimeRepVars, controlled by -fprint-explicit-runtime-reps) -} -- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g. -- -- @ -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). -- (a -> b) -> a -> b -- @ -- -- turns in to, -- -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @ -- -- We do this to prevent RuntimeRep variables from incurring a significant -- syntactic overhead in otherwise simple type signatures (e.g. ($)). See -- Note [Defaulting RuntimeRep variables] and #11549 for further discussion. -- defaultRuntimeRepVars :: IfaceType -> IfaceType defaultRuntimeRepVars = go emptyFsEnv where go :: FastStringEnv () -> IfaceType -> IfaceType go subs (IfaceForAllTy bndr ty) | isRuntimeRep var_kind , isInvisibleArgFlag (binderArgFlag bndr) -- don't default *visible* quantification -- or we get the mess in #13963 = let subs' = extendFsEnv subs var () in go subs' ty | otherwise = IfaceForAllTy (TvBndr (var, go subs var_kind) (binderArgFlag bndr)) (go subs ty) where var :: IfLclName (var, var_kind) = binderVar bndr go subs (IfaceTyVar tv) | tv `elemFsEnv` subs = IfaceTyConApp liftedRep ITC_Nil go subs (IfaceFunTy kind ty) = IfaceFunTy (go subs kind) (go subs ty) go subs (IfaceAppTy x y) = IfaceAppTy (go subs x) (go subs y) go subs (IfaceDFunTy x y) = IfaceDFunTy (go subs x) (go subs y) go subs (IfaceCastTy x co) = IfaceCastTy (go subs x) co go _ other = other liftedRep :: IfaceTyCon liftedRep = IfaceTyCon dc_name (IfaceTyConInfo IsPromoted IfaceNormalTyCon) where dc_name = getName liftedRepDataConTyCon isRuntimeRep :: IfaceType -> Bool isRuntimeRep (IfaceTyConApp tc _) = tc `ifaceTyConHasKey` runtimeRepTyConKey isRuntimeRep _ = False eliminateRuntimeRep :: (IfaceType -> SDoc) -> IfaceType -> SDoc eliminateRuntimeRep f ty = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitRuntimeReps dflags then f ty else f (defaultRuntimeRepVars ty) instance Outputable IfaceTcArgs where ppr tca = pprIfaceTcArgs tca pprIfaceTcArgs, pprParendIfaceTcArgs :: IfaceTcArgs -> SDoc pprIfaceTcArgs = ppr_tc_args TopPrec pprParendIfaceTcArgs = ppr_tc_args TyConPrec ppr_tc_args :: TyPrec -> IfaceTcArgs -> SDoc ppr_tc_args ctx_prec args = let pprTys t ts = ppr_ty ctx_prec t <+> ppr_tc_args ctx_prec ts in case args of ITC_Nil -> empty ITC_Vis t ts -> pprTys t ts ITC_Invis t ts -> pprTys t ts ------------------- pprIfaceForAllPart :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPart tvs ctxt sdoc = ppr_iface_forall_part ShowForAllWhen tvs ctxt sdoc -- | Like 'pprIfaceForAllPart', but always uses an explicit @forall@. pprIfaceForAllPartMust :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPartMust tvs ctxt sdoc = ppr_iface_forall_part ShowForAllMust tvs ctxt sdoc pprIfaceForAllCoPart :: [(IfLclName, IfaceCoercion)] -> SDoc -> SDoc pprIfaceForAllCoPart tvs sdoc = sep [ pprIfaceForAllCo tvs, sdoc ] ppr_iface_forall_part :: ShowForAllFlag -> [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc ppr_iface_forall_part show_forall tvs ctxt sdoc = sep [ case show_forall of ShowForAllMust -> pprIfaceForAll tvs ShowForAllWhen -> pprUserIfaceForAll tvs , pprIfaceContextArr ctxt , sdoc] -- | Render the "forall ... ." or "forall ... ->" bit of a type. pprIfaceForAll :: [IfaceForAllBndr] -> SDoc pprIfaceForAll [] = empty pprIfaceForAll bndrs@(TvBndr _ vis : _) = add_separator (forAllLit <+> doc) <+> pprIfaceForAll bndrs' where (bndrs', doc) = ppr_itv_bndrs bndrs vis add_separator stuff = case vis of Required -> stuff <+> arrow _inv -> stuff <> dot -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@. -- Returns both the list of not-yet-rendered binders and the doc. -- No anonymous binders here! ppr_itv_bndrs :: [IfaceForAllBndr] -> ArgFlag -- ^ visibility of the first binder in the list -> ([IfaceForAllBndr], SDoc) ppr_itv_bndrs all_bndrs@(bndr@(TvBndr _ vis) : bndrs) vis1 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_itv_bndrs bndrs vis1 in (bndrs', pprIfaceForAllBndr bndr <+> doc) | otherwise = (all_bndrs, empty) ppr_itv_bndrs [] _ = ([], empty) pprIfaceForAllCo :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCo [] = empty pprIfaceForAllCo tvs = text "forall" <+> pprIfaceForAllCoBndrs tvs <> dot pprIfaceForAllCoBndrs :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCoBndrs bndrs = hsep $ map pprIfaceForAllCoBndr bndrs pprIfaceForAllBndr :: IfaceForAllBndr -> SDoc pprIfaceForAllBndr (TvBndr tv Inferred) = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitForalls dflags then braces $ pprIfaceTvBndr False tv else pprIfaceTvBndr True tv pprIfaceForAllBndr (TvBndr tv _) = pprIfaceTvBndr True tv pprIfaceForAllCoBndr :: (IfLclName, IfaceCoercion) -> SDoc pprIfaceForAllCoBndr (tv, kind_co) = parens (ppr tv <+> dcolon <+> pprIfaceCoercion kind_co) -- | Show forall flag -- -- Unconditionally show the forall quantifier with ('ShowForAllMust') -- or when ('ShowForAllWhen') the names used are free in the binder -- or when compiling with -fprint-explicit-foralls. data ShowForAllFlag = ShowForAllMust | ShowForAllWhen pprIfaceSigmaType :: ShowForAllFlag -> IfaceType -> SDoc pprIfaceSigmaType show_forall ty = ppr_iface_forall_part show_forall tvs theta (ppr tau) where (tvs, theta, tau) = splitIfaceSigmaTy ty pprUserIfaceForAll :: [IfaceForAllBndr] -> SDoc pprUserIfaceForAll tvs = sdocWithDynFlags $ \dflags -> ppWhen (any tv_has_kind_var tvs || gopt Opt_PrintExplicitForalls dflags) $ pprIfaceForAll tvs where tv_has_kind_var (TvBndr (_,kind) _) = not (ifTypeIsVarFree kind) ------------------- -- See equivalent function in TyCoRep.hs pprIfaceTyList :: TyPrec -> IfaceType -> IfaceType -> SDoc -- Given a type-level list (t1 ': t2), see if we can print -- it in list notation [t1, ...]. -- Precondition: Opt_PrintExplicitKinds is off pprIfaceTyList ctxt_prec ty1 ty2 = case gather ty2 of (arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma (map (ppr_ty TopPrec) (ty1:arg_tys)))) (arg_tys, Just tl) -> maybeParen ctxt_prec FunPrec $ hang (ppr_ty FunPrec ty1) 2 (fsep [ colon <+> ppr_ty FunPrec ty | ty <- arg_tys ++ [tl]]) where gather :: IfaceType -> ([IfaceType], Maybe IfaceType) -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn] -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl gather (IfaceTyConApp tc tys) | tc `ifaceTyConHasKey` consDataConKey , (ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil))) <- tys , (args, tl) <- gather ty2 = (ty1:args, tl) | tc `ifaceTyConHasKey` nilDataConKey = ([], Nothing) gather ty = ([], Just ty) pprIfaceTypeApp :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> SDoc pprIfaceTypeApp prec tc args = pprTyTcApp prec tc args pprTyTcApp :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> SDoc pprTyTcApp ctxt_prec tc tys = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> pprTyTcApp' ctxt_prec tc tys dflags style pprTyTcApp' :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> DynFlags -> PprStyle -> SDoc pprTyTcApp' ctxt_prec tc tys dflags style | ifaceTyConName tc `hasKey` ipClassKey , ITC_Vis (IfaceLitTy (IfaceStrTyLit n)) (ITC_Vis ty ITC_Nil) <- tys = maybeParen ctxt_prec FunPrec $ char '?' <> ftext n <> text "::" <> ppr_ty TopPrec ty | IfaceTupleTyCon arity sort <- ifaceTyConSort info , not (debugStyle style) , arity == ifaceVisTcArgsLength tys = pprTuple sort (ifaceTyConIsPromoted info) tys | IfaceSumTyCon arity <- ifaceTyConSort info = pprSum arity (ifaceTyConIsPromoted info) tys | tc `ifaceTyConHasKey` consDataConKey , not (gopt Opt_PrintExplicitKinds dflags) , ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil)) <- tys = pprIfaceTyList ctxt_prec ty1 ty2 | tc `ifaceTyConHasKey` tYPETyConKey , ITC_Vis (IfaceTyConApp rep ITC_Nil) ITC_Nil <- tys , rep `ifaceTyConHasKey` liftedRepDataConKey = kindStar | otherwise = getPprDebug $ \dbg -> if | not dbg && tc `ifaceTyConHasKey` errorMessageTypeErrorFamKey -- Suppress detail unles you _really_ want to see -> text "(TypeError ...)" | Just doc <- ppr_equality ctxt_prec tc (tcArgsIfaceTypes tys) -> doc | otherwise -> ppr_iface_tc_app ppr_ty ctxt_prec tc tys_wo_kinds where info = ifaceTyConInfo tc tys_wo_kinds = tcArgsIfaceTypes $ stripInvisArgs dflags tys -- | Pretty-print a type-level equality. -- Returns (Just doc) if the argument is a /saturated/ application -- of eqTyCon (~) -- eqPrimTyCon (~#) -- eqReprPrimTyCon (~R#) -- hEqTyCon (~~) -- -- See Note [Equality predicates in IfaceType] -- and Note [The equality types story] in TysPrim ppr_equality :: TyPrec -> IfaceTyCon -> [IfaceType] -> Maybe SDoc ppr_equality ctxt_prec tc args | hetero_eq_tc , [k1, k2, t1, t2] <- args = Just $ print_equality (k1, k2, t1, t2) | hom_eq_tc , [k, t1, t2] <- args = Just $ print_equality (k, k, t1, t2) | otherwise = Nothing where homogeneous = case ifaceTyConSort $ ifaceTyConInfo tc of IfaceEqualityTyCon -> True _other -> False -- True <=> a heterogeneous equality whose arguments -- are (in this case) of the same kind tc_name = ifaceTyConName tc pp = ppr_ty hom_eq_tc = tc_name `hasKey` eqTyConKey -- (~) hetero_eq_tc = tc_name `hasKey` eqPrimTyConKey -- (~#) || tc_name `hasKey` eqReprPrimTyConKey -- (~R#) || tc_name `hasKey` heqTyConKey -- (~~) print_equality args = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> print_equality' args style dflags print_equality' (ki1, ki2, ty1, ty2) style dflags | print_eqs -- No magic, just print the original TyCon = ppr_infix_eq (ppr tc) | hetero_eq_tc , print_kinds || not homogeneous = ppr_infix_eq (text "~~") | otherwise = if tc_name `hasKey` eqReprPrimTyConKey then pprIfacePrefixApp ctxt_prec (text "Coercible") [pp TyConPrec ty1, pp TyConPrec ty2] else pprIfaceInfixApp ctxt_prec (char '~') (pp TyOpPrec ty1) (pp TyOpPrec ty2) where ppr_infix_eq eq_op = pprIfaceInfixApp ctxt_prec eq_op (parens (pp TopPrec ty1 <+> dcolon <+> pp TyOpPrec ki1)) (parens (pp TopPrec ty2 <+> dcolon <+> pp TyOpPrec ki2)) print_kinds = gopt Opt_PrintExplicitKinds dflags print_eqs = gopt Opt_PrintEqualityRelations dflags || dumpStyle style || debugStyle style pprIfaceCoTcApp :: TyPrec -> IfaceTyCon -> [IfaceCoercion] -> SDoc pprIfaceCoTcApp ctxt_prec tc tys = ppr_iface_tc_app ppr_co ctxt_prec tc tys ppr_iface_tc_app :: (TyPrec -> a -> SDoc) -> TyPrec -> IfaceTyCon -> [a] -> SDoc ppr_iface_tc_app pp _ tc [ty] | tc `ifaceTyConHasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty) | tc `ifaceTyConHasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty) ppr_iface_tc_app pp ctxt_prec tc tys | tc `ifaceTyConHasKey` starKindTyConKey || tc `ifaceTyConHasKey` liftedTypeKindTyConKey || tc `ifaceTyConHasKey` unicodeStarKindTyConKey = kindStar -- Handle unicode; do not wrap * in parens | not (isSymOcc (nameOccName (ifaceTyConName tc))) = pprIfacePrefixApp ctxt_prec (ppr tc) (map (pp TyConPrec) tys) | [ty1,ty2] <- tys -- Infix, two arguments; -- we know nothing of precedence though = pprIfaceInfixApp ctxt_prec (ppr tc) (pp TyOpPrec ty1) (pp TyOpPrec ty2) | otherwise = pprIfacePrefixApp ctxt_prec (parens (ppr tc)) (map (pp TyConPrec) tys) pprSum :: Arity -> IsPromoted -> IfaceTcArgs -> SDoc pprSum _arity is_promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = tcArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI is_promoted <> sumParens (pprWithBars (ppr_ty TopPrec) args') pprTuple :: TupleSort -> IsPromoted -> IfaceTcArgs -> SDoc pprTuple ConstraintTuple IsNotPromoted ITC_Nil = text "() :: Constraint" -- All promoted constructors have kind arguments pprTuple sort IsPromoted args = let tys = tcArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI IsPromoted <> tupleParens sort (pprWithCommas pprIfaceType args') pprTuple sort promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = tcArgsIfaceTypes args args' = case sort of UnboxedTuple -> drop (length tys `div` 2) tys _ -> tys in pprPromotionQuoteI promoted <> tupleParens sort (pprWithCommas pprIfaceType args') pprIfaceTyLit :: IfaceTyLit -> SDoc pprIfaceTyLit (IfaceNumTyLit n) = integer n pprIfaceTyLit (IfaceStrTyLit n) = text (show n) pprIfaceCoercion, pprParendIfaceCoercion :: IfaceCoercion -> SDoc pprIfaceCoercion = ppr_co TopPrec pprParendIfaceCoercion = ppr_co TyConPrec ppr_co :: TyPrec -> IfaceCoercion -> SDoc ppr_co _ (IfaceReflCo r ty) = angleBrackets (ppr ty) <> ppr_role r ppr_co ctxt_prec (IfaceFunCo r co1 co2) = maybeParen ctxt_prec FunPrec $ sep (ppr_co FunPrec co1 : ppr_fun_tail co2) where ppr_fun_tail (IfaceFunCo r co1 co2) = (arrow <> ppr_role r <+> ppr_co FunPrec co1) : ppr_fun_tail co2 ppr_fun_tail other_co = [arrow <> ppr_role r <+> pprIfaceCoercion other_co] ppr_co _ (IfaceTyConAppCo r tc cos) = parens (pprIfaceCoTcApp TopPrec tc cos) <> ppr_role r ppr_co ctxt_prec (IfaceAppCo co1 co2) = maybeParen ctxt_prec TyConPrec $ ppr_co FunPrec co1 <+> pprParendIfaceCoercion co2 ppr_co ctxt_prec co@(IfaceForAllCo {}) = maybeParen ctxt_prec FunPrec $ pprIfaceForAllCoPart tvs (pprIfaceCoercion inner_co) where (tvs, inner_co) = split_co co split_co (IfaceForAllCo (name, _) kind_co co') = let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'') split_co co' = ([], co') -- Why these two? See Note [TcTyVars in IfaceType] ppr_co _ (IfaceFreeCoVar covar) = ppr covar ppr_co _ (IfaceCoVarCo covar) = ppr covar ppr_co ctxt_prec (IfaceUnivCo IfaceUnsafeCoerceProv r ty1 ty2) = maybeParen ctxt_prec TyConPrec $ text "UnsafeCo" <+> ppr r <+> pprParendIfaceType ty1 <+> pprParendIfaceType ty2 ppr_co _ctxt_prec (IfaceUnivCo (IfaceHoleProv u) _ _ _) = braces $ ppr u ppr_co _ (IfaceUnivCo _ _ ty1 ty2) = angleBrackets ( ppr ty1 <> comma <+> ppr ty2 ) ppr_co ctxt_prec (IfaceInstCo co ty) = maybeParen ctxt_prec TyConPrec $ text "Inst" <+> pprParendIfaceCoercion co <+> pprParendIfaceCoercion ty ppr_co ctxt_prec (IfaceAxiomRuleCo tc cos) = maybeParen ctxt_prec TyConPrec $ ppr tc <+> parens (interpp'SP cos) ppr_co ctxt_prec (IfaceAxiomInstCo n i cos) = ppr_special_co ctxt_prec (ppr n <> brackets (ppr i)) cos ppr_co ctxt_prec (IfaceSymCo co) = ppr_special_co ctxt_prec (text "Sym") [co] ppr_co ctxt_prec (IfaceTransCo co1 co2) = maybeParen ctxt_prec TyOpPrec $ ppr_co TyOpPrec co1 <+> semi <+> ppr_co TyOpPrec co2 ppr_co ctxt_prec (IfaceNthCo d co) = ppr_special_co ctxt_prec (text "Nth:" <> int d) [co] ppr_co ctxt_prec (IfaceLRCo lr co) = ppr_special_co ctxt_prec (ppr lr) [co] ppr_co ctxt_prec (IfaceSubCo co) = ppr_special_co ctxt_prec (text "Sub") [co] ppr_co ctxt_prec (IfaceCoherenceCo co1 co2) = ppr_special_co ctxt_prec (text "Coh") [co1,co2] ppr_co ctxt_prec (IfaceKindCo co) = ppr_special_co ctxt_prec (text "Kind") [co] ppr_special_co :: TyPrec -> SDoc -> [IfaceCoercion] -> SDoc ppr_special_co ctxt_prec doc cos = maybeParen ctxt_prec TyConPrec (sep [doc, nest 4 (sep (map pprParendIfaceCoercion cos))]) ppr_role :: Role -> SDoc ppr_role r = underscore <> pp_role where pp_role = case r of Nominal -> char 'N' Representational -> char 'R' Phantom -> char 'P' ------------------- instance Outputable IfaceTyCon where ppr tc = pprPromotionQuote tc <> ppr (ifaceTyConName tc) pprPromotionQuote :: IfaceTyCon -> SDoc pprPromotionQuote tc = pprPromotionQuoteI $ ifaceTyConIsPromoted $ ifaceTyConInfo tc pprPromotionQuoteI :: IsPromoted -> SDoc pprPromotionQuoteI IsNotPromoted = empty pprPromotionQuoteI IsPromoted = char '\'' instance Outputable IfaceCoercion where ppr = pprIfaceCoercion instance Binary IfaceTyCon where put_ bh (IfaceTyCon n i) = put_ bh n >> put_ bh i get bh = do n <- get bh i <- get bh return (IfaceTyCon n i) instance Binary IsPromoted where put_ bh IsNotPromoted = putByte bh 0 put_ bh IsPromoted = putByte bh 1 get bh = do n <- getByte bh case n of 0 -> return IsNotPromoted 1 -> return IsPromoted _ -> fail "Binary(IsPromoted): fail)" instance Binary IfaceTyConSort where put_ bh IfaceNormalTyCon = putByte bh 0 put_ bh (IfaceTupleTyCon arity sort) = putByte bh 1 >> put_ bh arity >> put_ bh sort put_ bh (IfaceSumTyCon arity) = putByte bh 2 >> put_ bh arity put_ bh IfaceEqualityTyCon = putByte bh 3 get bh = do n <- getByte bh case n of 0 -> return IfaceNormalTyCon 1 -> IfaceTupleTyCon <$> get bh <*> get bh 2 -> IfaceSumTyCon <$> get bh _ -> return IfaceEqualityTyCon instance Binary IfaceTyConInfo where put_ bh (IfaceTyConInfo i s) = put_ bh i >> put_ bh s get bh = IfaceTyConInfo <$> get bh <*> get bh instance Outputable IfaceTyLit where ppr = pprIfaceTyLit instance Binary IfaceTyLit where put_ bh (IfaceNumTyLit n) = putByte bh 1 >> put_ bh n put_ bh (IfaceStrTyLit n) = putByte bh 2 >> put_ bh n get bh = do tag <- getByte bh case tag of 1 -> do { n <- get bh ; return (IfaceNumTyLit n) } 2 -> do { n <- get bh ; return (IfaceStrTyLit n) } _ -> panic ("get IfaceTyLit " ++ show tag) instance Binary IfaceTcArgs where put_ bh tk = case tk of ITC_Vis t ts -> putByte bh 0 >> put_ bh t >> put_ bh ts ITC_Invis t ts -> putByte bh 1 >> put_ bh t >> put_ bh ts ITC_Nil -> putByte bh 2 get bh = do c <- getByte bh case c of 0 -> do t <- get bh ts <- get bh return $! ITC_Vis t ts 1 -> do t <- get bh ts <- get bh return $! ITC_Invis t ts 2 -> return ITC_Nil _ -> panic ("get IfaceTcArgs " ++ show c) ------------------- -- Some notes about printing contexts -- -- In the event that we are printing a singleton context (e.g. @Eq a@) we can -- omit parentheses. However, we must take care to set the precedence correctly -- to TyOpPrec, since something like @a :~: b@ must be parenthesized (see -- #9658). -- -- When printing a larger context we use 'fsep' instead of 'sep' so that -- the context doesn't get displayed as a giant column. Rather than, -- instance (Eq a, -- Eq b, -- Eq c, -- Eq d, -- Eq e, -- Eq f, -- Eq g, -- Eq h, -- Eq i, -- Eq j, -- Eq k, -- Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- -- we want -- -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, -- Eq j, Eq k, Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- | Prints "(C a, D b) =>", including the arrow. -- Used when we want to print a context in a type, so we -- use FunPrec to decide whether to parenthesise a singleton -- predicate; e.g. Num a => a -> a pprIfaceContextArr :: [IfacePredType] -> SDoc pprIfaceContextArr [] = empty pprIfaceContextArr [pred] = ppr_ty FunPrec pred <+> darrow pprIfaceContextArr preds = ppr_parend_preds preds <+> darrow -- | Prints a context or @()@ if empty -- You give it the context precedence pprIfaceContext :: TyPrec -> [IfacePredType] -> SDoc pprIfaceContext _ [] = text "()" pprIfaceContext prec [pred] = ppr_ty prec pred pprIfaceContext _ preds = ppr_parend_preds preds ppr_parend_preds :: [IfacePredType] -> SDoc ppr_parend_preds preds = parens (fsep (punctuate comma (map ppr preds))) instance Binary IfaceType where put_ _ (IfaceFreeTyVar tv) = pprPanic "Can't serialise IfaceFreeTyVar" (ppr tv) put_ bh (IfaceForAllTy aa ab) = do putByte bh 0 put_ bh aa put_ bh ab put_ bh (IfaceTyVar ad) = do putByte bh 1 put_ bh ad put_ bh (IfaceAppTy ae af) = do putByte bh 2 put_ bh ae put_ bh af put_ bh (IfaceFunTy ag ah) = do putByte bh 3 put_ bh ag put_ bh ah put_ bh (IfaceDFunTy ag ah) = do putByte bh 4 put_ bh ag put_ bh ah put_ bh (IfaceTyConApp tc tys) = do { putByte bh 5; put_ bh tc; put_ bh tys } put_ bh (IfaceCastTy a b) = do { putByte bh 6; put_ bh a; put_ bh b } put_ bh (IfaceCoercionTy a) = do { putByte bh 7; put_ bh a } put_ bh (IfaceTupleTy s i tys) = do { putByte bh 8; put_ bh s; put_ bh i; put_ bh tys } put_ bh (IfaceLitTy n) = do { putByte bh 9; put_ bh n } get bh = do h <- getByte bh case h of 0 -> do aa <- get bh ab <- get bh return (IfaceForAllTy aa ab) 1 -> do ad <- get bh return (IfaceTyVar ad) 2 -> do ae <- get bh af <- get bh return (IfaceAppTy ae af) 3 -> do ag <- get bh ah <- get bh return (IfaceFunTy ag ah) 4 -> do ag <- get bh ah <- get bh return (IfaceDFunTy ag ah) 5 -> do { tc <- get bh; tys <- get bh ; return (IfaceTyConApp tc tys) } 6 -> do { a <- get bh; b <- get bh ; return (IfaceCastTy a b) } 7 -> do { a <- get bh ; return (IfaceCoercionTy a) } 8 -> do { s <- get bh; i <- get bh; tys <- get bh ; return (IfaceTupleTy s i tys) } _ -> do n <- get bh return (IfaceLitTy n) instance Binary IfaceCoercion where put_ bh (IfaceReflCo a b) = do putByte bh 1 put_ bh a put_ bh b put_ bh (IfaceFunCo a b c) = do putByte bh 2 put_ bh a put_ bh b put_ bh c put_ bh (IfaceTyConAppCo a b c) = do putByte bh 3 put_ bh a put_ bh b put_ bh c put_ bh (IfaceAppCo a b) = do putByte bh 4 put_ bh a put_ bh b put_ bh (IfaceForAllCo a b c) = do putByte bh 5 put_ bh a put_ bh b put_ bh c put_ _ (IfaceFreeCoVar cv) = pprPanic "Can't serialise IfaceFreeCoVar" (ppr cv) put_ bh (IfaceCoVarCo a) = do putByte bh 6 put_ bh a put_ bh (IfaceAxiomInstCo a b c) = do putByte bh 7 put_ bh a put_ bh b put_ bh c put_ bh (IfaceUnivCo a b c d) = do putByte bh 8 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfaceSymCo a) = do putByte bh 9 put_ bh a put_ bh (IfaceTransCo a b) = do putByte bh 10 put_ bh a put_ bh b put_ bh (IfaceNthCo a b) = do putByte bh 11 put_ bh a put_ bh b put_ bh (IfaceLRCo a b) = do putByte bh 12 put_ bh a put_ bh b put_ bh (IfaceInstCo a b) = do putByte bh 13 put_ bh a put_ bh b put_ bh (IfaceCoherenceCo a b) = do putByte bh 14 put_ bh a put_ bh b put_ bh (IfaceKindCo a) = do putByte bh 15 put_ bh a put_ bh (IfaceSubCo a) = do putByte bh 16 put_ bh a put_ bh (IfaceAxiomRuleCo a b) = do putByte bh 17 put_ bh a put_ bh b get bh = do tag <- getByte bh case tag of 1 -> do a <- get bh b <- get bh return $ IfaceReflCo a b 2 -> do a <- get bh b <- get bh c <- get bh return $ IfaceFunCo a b c 3 -> do a <- get bh b <- get bh c <- get bh return $ IfaceTyConAppCo a b c 4 -> do a <- get bh b <- get bh return $ IfaceAppCo a b 5 -> do a <- get bh b <- get bh c <- get bh return $ IfaceForAllCo a b c 6 -> do a <- get bh return $ IfaceCoVarCo a 7 -> do a <- get bh b <- get bh c <- get bh return $ IfaceAxiomInstCo a b c 8 -> do a <- get bh b <- get bh c <- get bh d <- get bh return $ IfaceUnivCo a b c d 9 -> do a <- get bh return $ IfaceSymCo a 10-> do a <- get bh b <- get bh return $ IfaceTransCo a b 11-> do a <- get bh b <- get bh return $ IfaceNthCo a b 12-> do a <- get bh b <- get bh return $ IfaceLRCo a b 13-> do a <- get bh b <- get bh return $ IfaceInstCo a b 14-> do a <- get bh b <- get bh return $ IfaceCoherenceCo a b 15-> do a <- get bh return $ IfaceKindCo a 16-> do a <- get bh return $ IfaceSubCo a 17-> do a <- get bh b <- get bh return $ IfaceAxiomRuleCo a b _ -> panic ("get IfaceCoercion " ++ show tag) instance Binary IfaceUnivCoProv where put_ bh IfaceUnsafeCoerceProv = putByte bh 1 put_ bh (IfacePhantomProv a) = do putByte bh 2 put_ bh a put_ bh (IfaceProofIrrelProv a) = do putByte bh 3 put_ bh a put_ bh (IfacePluginProv a) = do putByte bh 4 put_ bh a put_ _ (IfaceHoleProv _) = pprPanic "Binary(IfaceUnivCoProv) hit a hole" empty -- See Note [Holes in IfaceUnivCoProv] get bh = do tag <- getByte bh case tag of 1 -> return $ IfaceUnsafeCoerceProv 2 -> do a <- get bh return $ IfacePhantomProv a 3 -> do a <- get bh return $ IfaceProofIrrelProv a 4 -> do a <- get bh return $ IfacePluginProv a _ -> panic ("get IfaceUnivCoProv " ++ show tag) instance Binary (DefMethSpec IfaceType) where put_ bh VanillaDM = putByte bh 0 put_ bh (GenericDM t) = putByte bh 1 >> put_ bh t get bh = do h <- getByte bh case h of 0 -> return VanillaDM _ -> do { t <- get bh; return (GenericDM t) }
ezyang/ghc
compiler/iface/IfaceType.hs
bsd-3-clause
54,462
2
17
15,872
13,307
6,625
6,682
997
32
module Lab3 where ----------------------------------------------------------------------------------------------------------------------------- -- LIST COMPREHENSIONS ------------------------------------------------------------------------------------------------------------------------------ -- =================================== -- Ex. 0 - 2 -- =================================== evens :: [Integer] -> [Integer] evens xs = [x | x<-xs, x `mod` 2 == 0] -- =================================== -- Ex. 3 - 4 -- =================================== -- complete the following line with the correct type signature for this function -- squares :: ... squares :: Integer -> [Integer] squares n = [x*x | x<-[1..n]] sumSquares :: Integer -> Integer sumSquares n = sum (squares n) -- =================================== -- Ex. 5 - 7 -- =================================== -- complete the following line with the correct type signature for this function -- squares' :: ... squares' m n = [x*x | x<-[n+1..m+n]] sumSquares' :: Integer -> Integer sumSquares' x = sum . uncurry squares' $ (x, x) -- =================================== -- Ex. 8 -- =================================== coords :: Integer -> Integer -> [(Integer,Integer)] coords x y = [(x',y') | x'<-[0..x], y'<-[0..y]]
javier-alvarez/myhaskell
lab3.hs
bsd-3-clause
1,282
0
9
164
276
160
116
12
1
module Core.Pretty where import Text.PrettyPrint import Core.AST import Core.Parser prettyProgram :: CoreProgram -> String prettyProgram = render . semiSep . map prettyDefn semiSep :: [Doc] -> Doc semiSep = vcat . punctuate semi spaceSep :: [String] -> Doc spaceSep = sep . map text prettyDefn :: CoreDefn -> Doc prettyDefn (name, args, e) = text name <+> spaceSep args <+> equals <+> prettyExp e prettyExp :: CoreExpr -> Doc prettyExp (Var n) = text n prettyExp (Num n) = int n prettyExp (Constr i j) = text "Pack" <> braces (int i <> text "," <> int j) prettyExp (App e1 e2) = prettyExp e1 <+> parensIf (isAtomic e2) (prettyExp e2) where parensIf p doc | p = parens doc | otherwise = doc prettyExp (Let isRec defs e) = text (if isRec then "letrec" else "let") <+> nest 1 (prettyDefs defs) $$ text "in" <+> prettyExp e prettyExp (Case e alts) = text "case" <+> prettyExp e <+> text "of" <+> nest 1 (prettyAlts alts) prettyExp (Lam args e) = parens $ text "\\" <> spaceSep args <> dot <+> prettyExp e where dot = text "." prettyDefs :: [(Name, CoreExpr)] -> Doc prettyDefs = semiSep . map prettyDef prettyDef :: (Name, CoreExpr) -> Doc prettyDef (name, e) = text name <+> equals <+> prettyExp e prettyAlts :: [CoreAlt] -> Doc prettyAlts = semiSep . map prettyAlt prettyAlt :: CoreAlt -> Doc prettyAlt (i, args, e) = carots (int i) <+> spaceSep args <+> text "->" <+> prettyExp e where carots x = text "<" <> x <> text ">"
WraithM/CoreCompiler
src/Core/Pretty.hs
bsd-3-clause
1,463
0
10
302
637
318
319
36
2
-- | Addable ------------------------------------------------------------------------------ {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} module Constraint.Addable where ------------------------------------------------------------------------------ import Structure ------------------------------------------------------------------------------ -- | The Class class (Value a, Value b, Value c) => Addable a b c | a b -> c where add :: Guard a -> Guard b -> Guard c -- the return type of add is known ------------------------------------------------------------------------------ -- | The Operator data Addition a b c where Addition :: (Expression a n, Expression b m, Addable n m c) => a -> b -> Addition a b c -- a & b determine n & m which determine c ------------------------------------------------------------------------------ -- ALL OPERATORS ARE EXPRESSIONS instance (Value c) => Expression (Addition a b c) c where evaluate (Addition a b) = add (evaluate a) (evaluate b) -- ALL EXPRESSIONS ARE SHOWABLE instance Show (Addition a b c) where show (Addition a b) = "(" ++ show a ++ "+" ++ show b ++ ")" ------------------------------------------------------------------------------ -- EXTENSIONS TO ALREADY DEFINED VALUES
Conflagrationator/HMath
src/Constraint/Addable.hs
bsd-3-clause
1,356
0
10
209
264
145
119
14
0
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} module Games.Melee ( Melee (..), PlayerState (..), ) where import Lib import Vector import Types import Network import Network.Label import Layers import Data.Singletons.Prelude.List import Data.List.Split import Control.Monad import System.FilePath.Posix import Buffer -- | Game definition for SSBM. data Melee = Menu | Ingame !PlayerState !Int !PlayerState !Int | Win !PlayerState !Int deriving (Eq, Show) -- | The state of a player in a game data PlayerState = PlayerState { stocks :: !Int -- ^ Stocks , percent :: !Int -- ^ Percentage } deriving (Eq, Show) instance Pretty PlayerState where pretty (PlayerState s p) = stockstring s ++ " " ++ show p ++ "%" where stockstring n = replicate n 'O' ++ replicate (4-n) ' ' instance Transitions PlayerState where PlayerState s p ->? PlayerState s' p' | s' == s && p' >= p && p' - p < 80 = True | p > 0 && p' == 0 = s' == s - 1 | otherwise = False instance Transitions Melee where a ->? b | a == b = True Menu ->? Menu = True Menu ->? Ingame (PlayerState 4 0) _ (PlayerState 4 0) _ = True Win _ _ ->? Menu = True Ingame p1 q1 p2 q2 ->? Win p q | stocks p1 == 1 && p == p2 && q == q2 = True | stocks p2 == 1 && p == p1 && q == q1 = True Ingame p1 q1 p2 q2 ->? Ingame p1' q1' p2' q2' = and [ q1 == q1', q2 == q2' , p1 ->? p1', p2 ->? p2' ] _ ->? _ = False instance GameState Melee where type Title Melee = "Melee" type ScreenWidth Melee = 584 type ScreenHeight Melee = 480 type Widgets Melee = '[Melee] label st = LabelVec$ toLabel st :- Nil delabel (LabelVec (WLabel l :- Nil)) = case parseLabel l (fromLabel :: LabelParser Melee) of Left err -> error err Right s -> s rootDir = Path "/Users/joni/tmp/" parse = fromFilename instance Pretty Melee where pretty Menu = "Menu" pretty (Win p q) = "Player " ++ show q ++ " wins with " ++ pretty p pretty (Ingame p1 q1 p2 q2) = "P" ++ show q1 ++ ": " ++ pretty p1 ++ "\t\tP" ++ show q2 ++ ": " ++ pretty p2 instance Widget Melee where type Width Melee = 140 type Height Melee = 120 type Parent Melee = Melee type DataShape Melee = '[ 10, 10, 10, 5 ] type Positions Melee = '[ '(16, 356) , '(156, 356) , '(294, 356) , '(432, 356) ] type SampleWidth Melee = 42 type SampleHeight Melee = 42 type NetConfig Melee = '[ Convolution 12 3 5 5 38 38 , Pool , ReLU , Convolution 32 12 8 8 12 12 , ReLU , Flatten , FC 4608 1024 , ReLU , FC 1024 (Sum (DataShape Melee)) , MultiSoftMax (DataShape Melee) ] params = Params (LearningParameters 1e-4 0.9 1e-7) toLabel Menu = WLabel$ fill 0 toLabel (Win p q) = WLabel$ get 1 <-> get 2 <-> get 3 <-> get 4 where get n | n == q = playerLabel p | otherwise = fill 0 toLabel (Ingame p1 q1 p2 q2) = WLabel$ get 1 <-> get 2 <-> get 3 <-> get 4 where get n | n == q1 = playerLabel p1 | n == q2 = playerLabel p2 | otherwise = fill 0 fromLabel = do players <- replicateM 4 playerParser case count ingame players of 2 -> let [(p1, q1), (p2, q2)] = filter (ingame.fst) $ zip players [1..] in return$! Ingame p1 q1 p2 q2 1 -> return$! let (p,q) = head (filter (ingame.fst) $ zip players [1..]) in Win p q _ -> return Menu ingame :: PlayerState -> Bool ingame (PlayerState 0 _) = False ingame _ = True playerLabel :: PlayerState -> LabelComposite 1 '[10, 10, 10, 5] playerLabel (PlayerState 0 _) = fill 0 playerLabel (PlayerState stocks percent) = singleton d100 <|> singleton d10 <|> singleton d1 <|> singleton stocks where (d100, d10, d1) = splitDigits percent playerParser :: LabelParser PlayerState playerParser = do d100 <- pop d10 <- pop d1 <- pop stocks <- pop let dmg = 100 * d100 + 10 * d10 + 1 * d1 return $! mkPlayerState stocks dmg mkPlayerState :: Int -> Int -> PlayerState mkPlayerState 0 _ = PlayerState 0 0 mkPlayerState s p | s < 0 || s > 4 = error$ "PlayerState with " ++ show s ++ " stocks" | p < 0 || p > 999 = error$ "PlayerState with " ++ show p ++ " percent" | otherwise = PlayerState s p fromFilename :: Path a -> LabelVec Melee fromFilename (Path (wordsBy (=='_') . takeWhile (/='.') . takeBaseName -> [ "shot", _, "psd", psd, "st", st , "p1", "g", g1, "c", _, "s", read' -> s1, "p", read' -> p1 , "p2", "g", g2, "c", _, "s", read' -> s2, "p", read' -> p2 , "p3", "g", g3, "c", _, "s", read' -> s3, "p", read' -> p3 , "p4", "g", g4, "c", _, "s", read' -> s4, "p", read' -> p4 ] )) | psd == "1" || st == "0" = LabelVec$ WLabel (fill 0) :- Nil | otherwise = LabelVec$ WLabel (get g1 s1 p1 <-> get g2 s2 p2 <-> get g3 s3 p3 <-> get g4 s4 p4) :- Nil where get "0" _ _ = fill 0 get "1" s p = playerLabel $ mkPlayerState s p get _ _ _ = error "Error while parsing filename" fromFilename (Path p) = error$ "Invalid filename: " ++ p
jonascarpay/visor
src/Games/Melee.hs
bsd-3-clause
5,931
0
21
2,120
2,168
1,101
1,067
161
3
{-# LANGUAGE OverloadedStrings #-} -- | Module : Network.MPD.Util -- Copyright : (c) Ben Sinclair 2005-2009, Joachim Fasting 2010 -- License : MIT (see LICENSE) -- Maintainer : Joachim Fasting <[email protected]> -- Stability : alpha -- -- Utilities. module Network.MPD.Util ( parseDate, parseIso8601, formatIso8601, parseNum, parseFrac, parseBool, showBool, breakChar, parseTriple, toAssoc, toAssocList, splitGroups, read ) where import Control.Arrow import Data.Time.Format (ParseTime, parseTime, FormatTime, formatTime) import System.Locale (defaultTimeLocale) import qualified Prelude import Prelude hiding (break, take, drop, dropWhile, read) import Data.ByteString.Char8 (break, drop, dropWhile, ByteString) import qualified Data.ByteString.UTF8 as UTF8 import Data.String import Control.Applicative import qualified Data.Attoparsec.ByteString.Char8 as A -- | Like Prelude.read, but works with ByteString. read :: Read a => ByteString -> a read = Prelude.read . UTF8.toString -- Break a string by character, removing the separator. breakChar :: Char -> ByteString -> (ByteString, ByteString) breakChar c = second (drop 1) . break (== c) -- Parse a date value. -- > parseDate "2008" = Just 2008 -- > parseDate "2008-03-01" = Just 2008 parseDate :: ByteString -> Maybe Int parseDate = parseMaybe p where p = A.decimal <* A.skipMany (A.char '-' <|> A.digit) -- Parse date in iso 8601 format parseIso8601 :: (ParseTime t) => ByteString -> Maybe t parseIso8601 = parseTime defaultTimeLocale iso8601Format . UTF8.toString formatIso8601 :: FormatTime t => t -> String formatIso8601 = formatTime defaultTimeLocale iso8601Format iso8601Format :: String iso8601Format = "%FT%TZ" -- Parse a positive or negative integer value, returning 'Nothing' on failure. parseNum :: (Read a, Integral a) => ByteString -> Maybe a parseNum = parseMaybe (A.signed A.decimal) -- Parse C style floating point value, returning 'Nothing' on failure. parseFrac :: (Fractional a, Read a) => ByteString -> Maybe a parseFrac = parseMaybe p where p = A.string "nan" *> pure (Prelude.read "NaN") <|> A.string "inf" *> pure (Prelude.read "Infinity") <|> A.string "-inf" *> pure (Prelude.read "-Infinity") <|> A.rational -- Inverts 'parseBool'. showBool :: IsString a => Bool -> a -- FIXME: can we change the type to (Bool -> ByteString)? showBool x = if x then "1" else "0" -- Parse a boolean response value. parseBool :: ByteString -> Maybe Bool parseBool = parseMaybe p where p = A.char '1' *> pure True <|> A.char '0' *> pure False -- Break a string into triple. parseTriple :: Char -> (ByteString -> Maybe a) -> ByteString -> Maybe (a, a, a) parseTriple c f s = let (u, u') = breakChar c s (v, w) = breakChar c u' in case (f u, f v, f w) of (Just a, Just b, Just c') -> Just (a, b, c') _ -> Nothing -- Break a string into a key-value pair, separating at the first ':'. toAssoc :: ByteString -> (ByteString, ByteString) toAssoc = second (dropWhile (== ' ') . drop 1) . break (== ':') toAssocList :: [ByteString] -> [(ByteString, ByteString)] toAssocList = map toAssoc -- Takes an association list with recurring keys and groups each cycle of keys -- with their values together. There can be several keys that begin cycles, -- (the elements of the first parameter). splitGroups :: [ByteString] -> [(ByteString, ByteString)] -> [[(ByteString, ByteString)]] splitGroups groupHeads = go where go [] = [] go (x:xs) = let (ys, zs) = Prelude.break isGroupHead xs in (x:ys) : go zs isGroupHead = (`elem` groupHeads) . fst -- A helper for running a Parser, turning errors into Nothing. parseMaybe :: A.Parser a -> ByteString -> Maybe a parseMaybe p s = either (const Nothing) Just $ A.parseOnly (p <* A.endOfInput) s
beni55/libmpd-haskell
src/Network/MPD/Util.hs
mit
4,001
0
16
892
1,056
582
474
61
2
module XML.GPRReader.GXLReaderSpec where import Data.List import Data.Matrix hiding ((<|>)) import Test.Hspec import Abstract.Category import Abstract.Rewriting.DPO import Analysis.CriticalPairs import Analysis.CriticalSequence import Analysis.EssentialCriticalPairs import Category.TypedGraphRule import qualified XML.GGXReader as XML import qualified XML.GPRReader.GXLReader as GPR fileName1 = "tests/grammars/pacman2.ggx" fileName2 = "tests/grammars/pacman.gps" fileName3 = "tests/grammars/mutex2.ggx" fileName4 = "tests/grammars/mutex.gps" fileName5 = "tests/grammars/elevator.ggx" fileName6 = "tests/grammars/elevator.gps" fileName7 = "tests/grammars/elevatorWithFlags.gps" dpoConf :: Category morph => MorphismsConfig morph dpoConf = MorphismsConfig monic spec :: Spec spec = context "GPR Reader Test - CPA/CSA analysis is equal on GGX and GPR files" gprTest gprTest :: Spec gprTest = do it "Pacman grammar" $ do (ggGGX,_,_) <- XML.readGrammar fileName1 False dpoConf (ggGPR,_) <- GPR.readGrammar fileName2 let (pacmanRulesGGX,pacmanRulesGPR,_) = getRules ggGGX ggGPR undefined runAnalysis findCriticalPairs pacmanRulesGPR pacmanRulesGGX runAnalysis findCriticalSequences pacmanRulesGPR pacmanRulesGGX it "Mutex grammar" $ do (ggGGX,_,_) <- XML.readGrammar fileName3 False dpoConf (ggGPR,_) <- GPR.readGrammar fileName4 let (mutexRulesGGX,mutexRulesGPR,_) = getRules ggGGX ggGPR undefined runAnalysis findCriticalPairs mutexRulesGPR mutexRulesGGX runAnalysis findCriticalSequences mutexRulesGPR mutexRulesGGX it "Elevator grammar" $ do (ggGGX,_,_) <- XML.readGrammar fileName5 False dpoConf (ggGPR,_) <- GPR.readGrammar fileName6 (ggGPRFlag,_) <- GPR.readGrammar fileName7 let (elevatorRulesGGX,elevatorRulesGPR,elevatorRulesGPRFlag) = getRules ggGGX ggGPR ggGPRFlag runAnalysis (\conf _ -> findAllEssentialDeleteUse conf) elevatorRulesGPRFlag elevatorRulesGGX runAnalysis findCriticalPairs elevatorRulesGPR elevatorRulesGGX runAnalysis findCriticalSequences elevatorRulesGPR elevatorRulesGGX runAnalysis algorithm rules1 rules2 = pairwise (algorithm dpoConf []) rules1 `shouldBe` pairwise (algorithm dpoConf []) rules2 getRules a b c = (f a, f b, f c) where f g = map snd (sortRules (productions g)) sortRules = sortBy (\(a,_) (b,_) -> compare a b) pairwise :: (a -> a -> [b]) -> [a] -> Matrix Int pairwise f items = matrix (length items) (length items) $ \(i,j) -> length (f (items !! (i-1)) (items !! (j-1)))
rodrigo-machado/verigraph
tests/XML/GPRReader/GXLReaderSpec.hs
gpl-3.0
2,663
0
13
515
753
392
361
54
1
module Spark.Core.ContextSpec where import Test.Hspec import Spark.Core.Functions spec :: Spec spec = do describe "Basic routines to get something out" $ do it "should print a node" $ do let x = dataset ([1 ,2, 3, 4]::[Int]) x `shouldBe` x -- b = nodeToBundle (untyped x) in -- trace (pretty b) $ -- 1 `shouldBe` 1
krapsh/kraps-haskell
test/Spark/Core/ContextSpec.hs
apache-2.0
366
0
18
107
93
53
40
9
1
{-# LANGUAGE TransformListComp #-} oldest :: [Int] -> [String] oldest tbl = [ "str" | n <- tbl , then id ]
mpickering/ghc-exactprint
tests/examples/ghc710/TransformListComp.hs
bsd-3-clause
147
0
7
62
42
23
19
5
1
module Blockchain.Mining ( nonceIsValid' ) where import Control.Monad.IO.Class import Control.Monad.Trans.State import qualified Data.Array.IO as A import qualified Data.Binary as Bin import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Word import Blockchain.Context import Blockchain.Data.BlockDB import Blockchain.ExtWord import Blockchain.Util import Numeric import Cache import Constants import Dataset import Hashimoto import Debug.Trace word32Unpack::B.ByteString->[Word32] word32Unpack s | B.null s = [] word32Unpack s | B.length s >= 4 = Bin.decode (BL.fromStrict $ B.take 4 s) : word32Unpack (B.drop 4 s) word32Unpack s = error "word32Unpack called for ByteString of length not a multiple of 4" powFunc'::B.ByteString->Block->IO Integer powFunc' dataset b = --trace (show $ headerHashWithoutNonce b) $ fmap (byteString2Integer . snd) $ hashimoto (headerHashWithoutNonce b) (B.pack $ word64ToBytes $ blockDataNonce $ blockBlockData b) (fromInteger $ fullSize 0) -- (fromInteger . (calcDataset 0 !)) (A.newListArray (0,15) . word32Unpack . B.take 64 . (flip B.drop dataset) . (64 *) . fromIntegral) nonceIsValid'::Block->ContextM Bool nonceIsValid' b = do cxt <- get val <- liftIO $ powFunc' (miningDataset cxt) b {- liftIO $ putStrLn (showHex val "") liftIO $ putStrLn (showHex ( val * blockDataDifficulty (blockBlockData b) ) "") -} return $ val * blockDataDifficulty (blockBlockData b) < (2::Integer)^(256::Integer)
jamshidh/ethereum-client-haskell
src/Blockchain/Mining.hs
bsd-3-clause
1,605
0
14
331
444
240
204
36
1
module Utils where -- | -- -- >>> split "foo bar baz" -- ["foo","bar baz"] -- >>> split "foo bar baz" -- ["foo","bar baz"] split :: String -> [String] split xs = [ys, dropWhile isSpace zs] where isSpace = (== ' ') (ys,zs) = break isSpace xs -- | -- -- >>> splitN 0 "foo bar baz" -- ["foo","bar baz"] -- >>> splitN 2 "foo bar baz" -- ["foo","bar baz"] -- >>> splitN 3 "foo bar baz" -- ["foo","bar","baz"] splitN :: Int -> String -> [String] splitN n xs | n <= 2 = split xs | otherwise = let [ys,zs] = split xs in ys : splitN (n - 1) zs
cabrera/ghc-mod
src/Utils.hs
bsd-3-clause
581
0
11
158
162
91
71
10
1
module Bead.Persistence.SQL.FileSystem where import Control.Applicative ((<$>)) import Control.DeepSeq (deepseq) import Control.Monad import Control.Monad.IO.Class import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as BS import Data.List (isSuffixOf) import Data.Maybe import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import System.Directory import qualified System.Directory as Dir import System.FilePath import System.IO import System.Posix.Types (COff(..)) import System.Posix.Files (getFileStatus, fileSize, modificationTime) import Bead.Domain.Entities import Bead.Domain.Relationships import Bead.Domain.Types datadir = "data" testOutgoingDir = "test-outgoing" testIncomingDir = "test-incoming" userDir = "user" testOutgoingDataDir = joinPath [datadir, testOutgoingDir] testIncomingDataDir = joinPath [datadir, testIncomingDir] userDataDir = joinPath [datadir, userDir] fsDirs = [ datadir , testOutgoingDataDir , testIncomingDataDir , userDataDir ] class DirName d where dirName :: d -> FilePath instance DirName Username where dirName = usernameCata ((datadir </> "user") </>) instance DirName TestJobKey where dirName (TestJobKey k) = joinPath [datadir, testOutgoingDir, k] fileLoad :: (MonadIO io) => FilePath -> io String fileLoad fname = liftIO $ do h <- openFile fname ReadMode hSetEncoding h utf8 s <- hGetContents h s `deepseq` hClose h return s fileSave :: (MonadIO io) => FilePath -> String -> io () fileSave fname s = liftIO $ do handler <- openFile fname WriteMode hSetEncoding handler utf8 hPutStr handler s hClose handler fileSaveBS :: (MonadIO io) => FilePath -> ByteString -> io () fileSaveBS fname s = liftIO $ do handler <- openFile fname WriteMode hSetEncoding handler utf8 BS.hPutStr handler s hClose handler filterDirContents :: (MonadIO io) => (FilePath -> IO Bool) -> FilePath -> io [FilePath] filterDirContents f p = liftIO $ do content <- liftM (filter (\d -> not $ or [d == ".", d == ".."])) $ getDirectoryContents p filterM f $ map jp content where jp x = joinPath [p, x] getSubDirectories :: (MonadIO io) => FilePath -> io [FilePath] getSubDirectories = filterDirContents doesDirectoryExist getFilesInFolder :: (MonadIO io) => FilePath -> io [FilePath] getFilesInFolder = filterDirContents doesFileExist -- * initFS :: (MonadIO io) => io () initFS = liftIO $ mapM_ createDirWhenDoesNotExist fsDirs where createDirWhenDoesNotExist d = do existDir <- doesDirectoryExist d unless existDir . createDirectory $ d removeFS :: (MonadIO io) => io () removeFS = liftIO $ removeDirectoryRecursive datadir isSetUpFS :: (MonadIO io) => io Bool isSetUpFS = liftIO . fmap and $ mapM doesDirectoryExist fsDirs createDirectoryLocked :: FilePath -> (FilePath -> IO ()) -> IO () createDirectoryLocked d m = do let d' = d <.> "locked" createDirectory d' m d' renameDirectory d' d createUserFileDir :: (MonadIO io) => Username -> io () createUserFileDir u = liftIO $ forM_ ["private-files", "public-files" ] $ \d -> do let dir = dirName u </> d exists <- doesDirectoryExist dir unless exists $ createDirectoryIfMissing True dir copyUsersFile :: (MonadIO io) => Username -> FilePath -> UsersFile -> io () copyUsersFile username tmpPath userfile = liftIO $ do createUserFileDir username let dirname = dirName username publicDir = dirname </> "public-files" privateDir = dirname </> "private-files" Dir.copyFile tmpPath $ usersFile (publicDir </>) (privateDir </>) userfile -- Calculates the file modification time in UTC time from the File status fileModificationInUTCTime = posixSecondsToUTCTime . realToFrac . modificationTime listFiles :: (MonadIO io) => Username -> io [(UsersFile, FileInfo)] listFiles username = liftIO $ do createUserFileDir username let dirname = dirName username privateFiles <- f (dirname </> "private-files") UsersPrivateFile publicFiles <- f (dirname </> "public-files") UsersPublicFile return $ privateFiles ++ publicFiles where f dir typ = do paths <- getFilesInFolder dir forM paths $ \path -> do status <- getFileStatus path let info = FileInfo (fileOffsetToInt $ fileSize status) (fileModificationInUTCTime status) return (typ $ takeFileName path, info) fileOffsetToInt (COff x) = fromIntegral x getFile :: (MonadIO io) => Username -> UsersFile -> io FilePath getFile username userfile = liftIO $ do createUserFileDir username let dirname = dirName username publicDir = dirname </> "public-files" privateDir = dirname </> "private-files" usersFile (f publicDir) (f privateDir) userfile where f dir fn = do let fname = dir </> fn exists <- doesFileExist fname unless exists $ error $ concat [ "File (", fn, ") does not exist in users folder (" , show username, ")" ] return fname -- Collects the test script, test case and the submission and copies them to the -- the directory named after the submission key placed in the test-outgoing directory saveTestJob :: (MonadIO io) => SubmissionKey -> Submission -> TestScript -> TestCase -> io () saveTestJob sk submission testScript testCase = liftIO $ do -- If there is a test case, we copy the information to the desired let tjk = submissionKeyToTestJobKey sk tjPath = dirName tjk exists <- doesDirectoryExist tjPath when exists $ error $ concat ["Test job directory already exist:", show tjk] createDirectoryLocked tjPath $ \p -> do fileSave (p </> "script") (tsScript testScript) -- Save Simple or Zipped Submission withSubmissionValue (solution submission) (flip fileSave) (flip fileSaveBS) (p </> "submission") -- Save Simple or Zipped Test Case withTestCaseValue (tcValue testCase) (flip fileSave) (flip fileSaveBS) (p </> "tests") -- Insert the feedback info for the file system part of the database. This method is -- used by the tests only, and serves as a model for interfacing with the outside world. insertTestFeedback :: (MonadIO io) => SubmissionKey -> FeedbackInfo -> io () insertTestFeedback sk info = liftIO $ do let sDir = submissionKeyMap (testIncomingDataDir </>) sk <.> "locked" createDirectoryIfMissing True sDir let student comment = fileSave (sDir </> "public") comment admin comment = fileSave (sDir </> "private") comment result bool = fileSave (sDir </> "result") (show bool) feedbackInfo result student admin evaluated info where evaluated _ _ = error "insertTestComment: Evaluation should not be inserted by test." finalizeTestFeedback :: (MonadIO io) => SubmissionKey -> io () finalizeTestFeedback sk = liftIO $ do let sDir = submissionKeyMap (testIncomingDataDir </>) sk renameDirectory (sDir <.> "locked") sDir -- Test Feedbacks are stored in the persistence layer, in the test-incomming directory -- each one in a file, named after an existing submission in the system testFeedbacks :: (MonadIO io) => io [(SubmissionKey, Feedback)] testFeedbacks = liftIO (createFeedbacks =<< processables) where processables = filter (not . (`isSuffixOf` ".locked")) <$> getSubDirectories testIncomingDataDir createFeedbacks = fmap join . mapM createFeedback createFeedback path = do let sk = SubmissionKey . last $ splitDirectories path addKey x = (sk, x) files <- getFilesInFolder path fmap (map addKey . catMaybes) $ forM files $ \file -> do fileDate <- fileModificationInUTCTime <$> getFileStatus file let (_dir,fname) = splitFileName file feedback f = Feedback f fileDate case fname of "private" -> Just . feedback . MessageForAdmin <$> fileLoad file "public" -> Just . feedback . MessageForStudent <$> fileLoad file "result" -> Just . feedback . TestResult . readMaybeErr file <$> fileLoad file _ -> return Nothing where readMaybeErr :: (Read a) => FilePath -> String -> a readMaybeErr fp = fromMaybe (error $ "Non-parseable data in file: " ++ fp) . readMaybe -- Deletes the comments (test-agent and message as well) -- contained file from the test-incomming directory, named after -- an existing submission deleteTestFeedbacks :: (MonadIO io) => SubmissionKey -> io () deleteTestFeedbacks = liftIO . submissionKeyMap (removeDirectoryRecursive . (testIncomingDataDir </>)) -- Removes the file if exists, otherwise do nothing removeFileIfExists :: FilePath -> IO () removeFileIfExists path = do exists <- doesFileExist path when exists $ removeFile path
pgj/bead
src/Bead/Persistence/SQL/FileSystem.hs
bsd-3-clause
8,847
0
19
1,922
2,491
1,255
1,236
175
4
-- | Support for basic table drawing. module Brick.Widgets.Table ( -- * Types Table , ColumnAlignment(..) , RowAlignment(..) , TableException(..) -- * Construction , table -- * Configuration , alignLeft , alignRight , alignCenter , alignTop , alignMiddle , alignBottom , setColAlignment , setRowAlignment , setDefaultColAlignment , setDefaultRowAlignment , surroundingBorder , rowBorders , columnBorders -- * Rendering , renderTable ) where import Control.Monad (forM) import qualified Control.Exception as E import Data.List (transpose, intersperse, nub) import qualified Data.Map as M import Graphics.Vty (imageHeight, imageWidth) import Brick.Types import Brick.Widgets.Core import Brick.Widgets.Center import Brick.Widgets.Border -- | Column alignment modes. data ColumnAlignment = AlignLeft -- ^ Align all cells to the left. | AlignCenter -- ^ Center the content horizontally in all cells in the column. | AlignRight -- ^ Align all cells to the right. deriving (Eq, Show, Read) -- | Row alignment modes. data RowAlignment = AlignTop -- ^ Align all cells to the top. | AlignMiddle -- ^ Center the content vertically in all cells in the row. | AlignBottom -- ^ Align all cells to the bottom. deriving (Eq, Show, Read) -- | A table creation exception. data TableException = TEUnequalRowSizes -- ^ Rows did not all have the same number of cells. | TEInvalidCellSizePolicy -- ^ Some cells in the table did not use the 'Fixed' size policy for -- both horizontal and vertical sizing. deriving (Eq, Show, Read) instance E.Exception TableException where -- | A table data structure. data Table n = Table { columnAlignments :: M.Map Int ColumnAlignment , rowAlignments :: M.Map Int RowAlignment , tableRows :: [[Widget n]] , defaultColumnAlignment :: ColumnAlignment , defaultRowAlignment :: RowAlignment , drawSurroundingBorder :: Bool , drawRowBorders :: Bool , drawColumnBorders :: Bool } -- | Construct a new table. -- -- The argument is the list of rows, with each element of the argument -- list being the columns of the respective row. -- -- By default, all columns are left-aligned. Use the alignment functions -- in this module to change that behavior. -- -- By default, all rows are top-aligned. Use the alignment functions in -- this module to change that behavior. -- -- By default, the table will draw borders between columns, between -- rows, and around the outside of the table. Border-drawing behavior -- can be configured with the API in this module. Note that tables -- always draw with 'joinBorders' enabled. -- -- All cells of all rows MUST use the 'Fixed' growth policy for both -- horizontal and vertical growth. If the argument list contains -- any cells that use the 'Greedy' policy, this will raise a -- 'TableException'. -- -- All rows must have the same number of cells. If not, this will raise -- a 'TableException'. table :: [[Widget n]] -> Table n table rows = if not allFixed then E.throw TEInvalidCellSizePolicy else if not allSameLength then E.throw TEUnequalRowSizes else t where allSameLength = length (nub (length <$> rows)) <= 1 allFixed = all fixedRow rows fixedRow = all fixedCell fixedCell w = hSize w == Fixed && vSize w == Fixed t = Table { columnAlignments = mempty , rowAlignments = mempty , tableRows = rows , drawSurroundingBorder = True , drawRowBorders = True , drawColumnBorders = True , defaultColumnAlignment = AlignLeft , defaultRowAlignment = AlignTop } -- | Configure whether the table draws a border on its exterior. surroundingBorder :: Bool -> Table n -> Table n surroundingBorder b t = t { drawSurroundingBorder = b } -- | Configure whether the table draws borders between its rows. rowBorders :: Bool -> Table n -> Table n rowBorders b t = t { drawRowBorders = b } -- | Configure whether the table draws borders between its columns. columnBorders :: Bool -> Table n -> Table n columnBorders b t = t { drawColumnBorders = b } -- | Align the specified column to the right. The argument is the column -- index, starting with zero. alignRight :: Int -> Table n -> Table n alignRight = setColAlignment AlignRight -- | Align the specified column to the left. The argument is the column -- index, starting with zero. alignLeft :: Int -> Table n -> Table n alignLeft = setColAlignment AlignLeft -- | Align the specified column to center. The argument is the column -- index, starting with zero. alignCenter :: Int -> Table n -> Table n alignCenter = setColAlignment AlignCenter -- | Align the specified row to the top. The argument is the row index, -- starting with zero. alignTop :: Int -> Table n -> Table n alignTop = setRowAlignment AlignTop -- | Align the specified row to the middle. The argument is the row -- index, starting with zero. alignMiddle :: Int -> Table n -> Table n alignMiddle = setRowAlignment AlignMiddle -- | Align the specified row to bottom. The argument is the row index, -- starting with zero. alignBottom :: Int -> Table n -> Table n alignBottom = setRowAlignment AlignBottom -- | Set the alignment for the specified column index (starting at -- zero). setColAlignment :: ColumnAlignment -> Int -> Table n -> Table n setColAlignment a col t = t { columnAlignments = M.insert col a (columnAlignments t) } -- | Set the alignment for the specified row index (starting at -- zero). setRowAlignment :: RowAlignment -> Int -> Table n -> Table n setRowAlignment a row t = t { rowAlignments = M.insert row a (rowAlignments t) } -- | Set the default column alignment for columns with no explicitly -- configured alignment. setDefaultColAlignment :: ColumnAlignment -> Table n -> Table n setDefaultColAlignment a t = t { defaultColumnAlignment = a } -- | Set the default row alignment for rows with no explicitly -- configured alignment. setDefaultRowAlignment :: RowAlignment -> Table n -> Table n setDefaultRowAlignment a t = t { defaultRowAlignment = a } -- | Render the table. renderTable :: Table n -> Widget n renderTable t = joinBorders $ (if drawSurroundingBorder t then border else id) $ Widget Fixed Fixed $ do let rows = tableRows t cellResults <- forM rows $ mapM render let rowHeights = rowHeight <$> cellResults colWidths = colWidth <$> byColumn allRowAligns = (\i -> M.findWithDefault (defaultRowAlignment t) i (rowAlignments t)) <$> [0..length rowHeights - 1] allColAligns = (\i -> M.findWithDefault (defaultColumnAlignment t) i (columnAlignments t)) <$> [0..length byColumn - 1] rowHeight = maximum . fmap (imageHeight . image) colWidth = maximum . fmap (imageWidth . image) byColumn = transpose cellResults toW = Widget Fixed Fixed . return totalHeight = sum rowHeights applyColAlignment align width w = Widget Fixed Fixed $ do result <- render w case align of AlignLeft -> return result AlignCenter -> render $ hLimit width $ hCenter $ toW result AlignRight -> render $ padLeft (Pad (width - imageWidth (image result))) $ toW result applyRowAlignment rHeight align result = case align of AlignTop -> toW result AlignMiddle -> vLimit rHeight $ vCenter $ toW result AlignBottom -> vLimit rHeight $ padTop Max $ toW result mkColumn (hAlign, width, colCells) = do let paddedCells = flip map (zip3 allRowAligns rowHeights colCells) $ \(vAlign, rHeight, cell) -> applyColAlignment hAlign width $ applyRowAlignment rHeight vAlign cell maybeRowBorders = if drawRowBorders t then intersperse (hLimit width hBorder) else id render $ vBox $ maybeRowBorders paddedCells columns <- mapM mkColumn $ zip3 allColAligns colWidths byColumn let maybeColumnBorders = if drawColumnBorders t then let rowBorderHeight = if drawRowBorders t then length rows - 1 else 0 in intersperse (vLimit (totalHeight + rowBorderHeight) vBorder) else id render $ hBox $ maybeColumnBorders $ toW <$> columns
sjakobi/brick
src/Brick/Widgets/Table.hs
bsd-3-clause
8,997
0
26
2,601
1,720
932
788
155
9
----------------------------------------------------------------------------- -- | -- Module : Plugins.StdinReader -- Copyright : (c) Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <[email protected]> -- Stability : unstable -- Portability : unportable -- -- A plugin for reading from `stdin`. -- -- Exports: -- - `StdinReader` to safely display stdin content (striping actions). -- - `UnsafeStdinReader` to display stdin content as-is. -- ----------------------------------------------------------------------------- module Plugins.StdinReader (StdinReader(..)) where import Prelude import System.Posix.Process import System.Exit import System.IO import Control.Exception (SomeException(..), handle) import Plugins import Actions (stripActions) data StdinReader = StdinReader | UnsafeStdinReader deriving (Read, Show) instance Exec StdinReader where start stdinReader cb = do s <- handle (\(SomeException e) -> do hPrint stderr e; return "") (hGetLineSafe stdin) cb $ escape stdinReader s eof <- isEOF if eof then exitImmediately ExitSuccess else start stdinReader cb escape :: StdinReader -> String -> String escape StdinReader = stripActions escape UnsafeStdinReader = id
dragosboca/xmobar
src/Plugins/StdinReader.hs
bsd-3-clause
1,286
0
14
225
232
132
100
22
1
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Mezzo.Compose.Harmony -- Description : Harmony composition units -- Copyright : (c) Dima Szamozvancev -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Literals for chords and progressions. -- ----------------------------------------------------------------------------- module Mezzo.Compose.Harmony where import Mezzo.Model import Mezzo.Compose.Types import Mezzo.Compose.Builder import Mezzo.Compose.Templates import Mezzo.Compose.Basic import GHC.TypeLits infixr 5 :+ -- * Functional harmony terms -- | Type of harmonic terms in some key. type InKey k v = KeyS k -> v toProg :: InKey k (PhraseList p) -> InKey k (Prog p) toProg _ = const Prog -- ** Progressions -- | Create a new musical progression from the given time signature and progression schema. prog :: ValidProg r t p => InKey k (PhraseList p) -> Music (Sig :: Signature t k r) (FromProg p t) prog ik = Progression ((toProg ik) KeyS) -- ** Phrases -- | List of phrases in a progression parameterised by the key, ending with a cadence. data PhraseList (p :: ProgType k l) where -- | A cadential phrase, ending the progression. Cdza :: Cad c -> KeyS k -> PhraseList (CadPhrase c) -- | Add a new phrase to the beginning of the progression. (:+) :: InKey k (Phr p) -> InKey k (PhraseList ps) -> KeyS k -> PhraseList (p := ps) -- | Create a new cadential phrase. cadence :: InKey k (Cad c) -> InKey k (PhraseList (CadPhrase c)) cadence c = \k -> Cdza (c k) k -- | Dominant-tonic phrase. ph_I :: InKey k (Ton (t :: Tonic k l)) -> InKey k (Phr (PhraseI t :: Phrase k l)) ph_I _ = const Phr -- | Dominant-tonic phrase. ph_VI :: InKey k (Dom (d :: Dominant k l1)) -> InKey k (Ton (t :: Tonic k (l - l1))) -> InKey k (Phr (PhraseVI d t :: Phrase k l)) ph_VI _ _ = const Phr -- | Tonic-dominant-tonic phrase. ph_IVI :: InKey k (Ton (t1 :: Tonic k (l2 - l1))) -> InKey k (Dom (d :: Dominant k l1)) -> InKey k (Ton (t2 :: Tonic k (l - l2))) -> InKey k (Phr (PhraseIVI t1 d t2 :: Phrase k l)) ph_IVI _ _ _ = const Phr -- ** Cadences -- | Authentic V-I dominant cadence. auth_V_I :: InKey k (Cad (AuthCad (DegChord :: DegreeC V MajQ k Inv1 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) auth_V_I = const Cad -- | Authentic V7-I dominant seventh cadence. auth_V7_I :: InKey k (Cad (AuthCad7 (DegChord :: DegreeC V DomQ k Inv2 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) auth_V7_I = const Cad -- | Authentic vii-I leading tone cadence. auth_vii_I :: InKey k (Cad (AuthCadVii (DegChord :: DegreeC VII DimQ k Inv1 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) auth_vii_I = const Cad -- | Authentic cadential 6-4 cadence. auth_64_V7_I :: InKey k (Cad (AuthCad64 (DegChord :: DegreeC I (KeyToQual k) k Inv2 Oct3) (DegChord :: DegreeC V DomQ k Inv3 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv1 Oct3))) auth_64_V7_I = const Cad -- | Deceptive V-iv cadence. decept_V_iv :: InKey k (Cad (DeceptCad (DegChord :: DegreeC V DomQ k Inv2 Oct2) (DegChord :: DegreeC VI (KeyToOtherQual k) k Inv1 Oct2))) decept_V_iv = const Cad -- | Full cadence, starting with a subdominant. full :: InKey k (Sub s) -> InKey k (Cad c) -> InKey k (Cad (FullCad s c)) full _ _ = const Cad -- | End progression without an explicit cadence. end :: InKey k (PhraseList (CadPhrase NoCad)) end = cadence $ const Cad -- ** Tonic chords -- | Tonic chord. ton :: InKey k (Ton (TonT (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) ton = const Ton -- | Doubled tonics. ton_T_T :: InKey k (Ton ton1) -> InKey k (Ton ton2) -> InKey k (Ton (TonTT ton1 ton2)) ton_T_T _ _ = const Ton -- ** Dominants -- | Dominant (V) chord. dom_V :: InKey k (Dom (DomVM (DegChord :: DegreeC V MajQ k Inv2 Oct2))) dom_V = const Dom -- | Dominant seventh (V7) chord. dom_V7 :: InKey k (Dom (DomV7 (DegChord :: DegreeC V DomQ k Inv2 Oct2))) dom_V7 = const Dom -- | Dominant leading tone (vii) chord. dom_vii0 :: InKey k (Dom (DomVii0 (DegChord :: DegreeC VII DimQ k Inv1 Oct2))) dom_vii0 = const Dom -- | Secondary dominant - dominant (V/V-V7) chord. dom_II_V7 :: InKey k (Dom (DomSecD (DegChord :: DegreeC II DomQ k Inv0 Oct3) (DegChord :: DegreeC V DomQ k Inv2 Oct2))) dom_II_V7 = const Dom -- | Subdominant followed by a dominant. dom_S_D :: InKey k (Sub subdom) -> InKey k (Dom dom) -> InKey k (Dom (DomSD subdom dom)) dom_S_D _ _ = const Dom -- | Dominant followed by another dominant. dom_D_D :: InKey k (Dom dom1) -> InKey k (Dom dom2) -> InKey k (Dom (DomDD dom1 dom2)) dom_D_D _ _ = const Dom -- ** Subdominants -- | Subdominant fourth (IV) chord. subdom_IV :: InKey k (Sub (SubIV (DegChord :: DegreeC IV (KeyToQual k) k Inv2 Oct2))) subdom_IV = const Sub -- | Subdominant minor second (ii) chord. subdom_ii :: IsMajor k "ii subdominant" => InKey k (Sub (SubIIm (DegChord :: DegreeC II MinQ k Inv0 Oct3))) subdom_ii = const Sub -- | Subdominant third-fourth (iii-IV) progression. subdom_iii_IV :: IsMajor k "iii-IV subdominant" => InKey k (Sub (SubIIImIVM (DegChord :: DegreeC III MinQ k Inv0 Oct3) (DegChord :: DegreeC IV MajQ k Inv3 Oct2))) subdom_iii_IV = const Sub -- | Doubled subdominants. subdom_S_S :: InKey k (Sub sub1) -> InKey k (Sub sub2) -> InKey k (Sub (SubSS sub1 sub2)) subdom_S_S _ _ = const Sub -- * Time signatures -- | Duple meter (2/4). duple :: TimeSig 2 duple = TimeSig -- | Triple meter (3/4). triple :: TimeSig 3 triple = TimeSig -- | Quadruple meter (4/4). quadruple :: TimeSig 4 quadruple = TimeSig -- * Key literals mkKeyLits
DimaSamoz/mezzo
src/Mezzo/Compose/Harmony.hs
mit
5,690
95
12
1,100
1,937
1,012
925
-1
-1
module Mockups.Parsers.Element where import Control.Applicative import Data.Attoparsec.Char8 import Mockups.Elements.Element import Mockups.Parsers.Common import Mockups.Parsers.Img import Mockups.Parsers.Txt import Mockups.Parsers.Box eltParser :: IndentLevel -> Parser Element eltParser lvl = do simpleEltParser lvl <|> containerParser lvl containerParser :: IndentLevel -> Parser Element containerParser lvl = do indentParser lvl containerAttr <- boxParser endOfLine children <- many $ eltParser (lvl + 1) return $ Container containerAttr children simpleEltParser:: IndentLevel -> Parser Element simpleEltParser lvl = do indentParser lvl simpleAttr <- imgParser <|> txtParser endOfLine return $ SimpleElement simpleAttr
ostapneko/tiny-mockups
src/main/Mockups/Parsers/Element.hs
mit
863
0
11
222
200
100
100
25
1
module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Yesod.Auth.OAuth2.Github (oauth2Github) import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import Yesod.Form.I18n.Russian (russianFormMessage) data App = App { appSettings :: AppSettings , appStatic :: Static , appConnPool :: ConnectionPool , appHttpManager :: Manager , appLogger :: Logger } instance HasHttpManager App where getHttpManager = appHttpManager mkYesodData "App" $(parseRoutesFile "config/routes") mkMessage "App" "messages" "ru" type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) instance Yesod App where approot = ApprootMaster $ appRoot . appSettings makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 120 "config/client_session_key.aes" defaultLayout widget = do mmsg <- getMessage mauth <- maybeAuth pc <- widgetToPageContent $ do addStylesheetRemote "http://fonts.googleapis.com/css?family=PT+Sans:400,700&subset=cyrillic,latin" addStylesheetRemote "http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700&subset=latin,cyrillic" addStylesheetRemote "https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" addStylesheetRemote "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" addStylesheet $ StaticR css_default_css $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") authRoute _ = Just $ AuthR LoginR isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized isAuthorized BlogPostsR True = authenticated isAuthorized NewBlogPostR _ = authenticated isAuthorized (EditBlogPostR id') _ = authorizeBlogPost id' isAuthorized (BlogPostR id') True = authorizeBlogPost id' isAuthorized CategoriesR True = authorizeAdmin isAuthorized NewCategoryR _ = authorizeAdmin isAuthorized (EditCategoryR _) _ = authorizeAdmin isAuthorized (CategoryR _) True = authorizeAdmin isAuthorized TagsR True = authorizeAdmin isAuthorized NewTagR _ = authorizeAdmin isAuthorized (EditTagR _) _ = authorizeAdmin isAuthorized (TagR _) True = authorizeAdmin isAuthorized UsersR True = authorizeAdmin isAuthorized NewUserR _ = authorizeAdmin isAuthorized (EditUserR id') _ = authorizeProfile id' isAuthorized (UserR id') True = authorizeProfile id' isAuthorized _ _ = return Authorized addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger authenticated :: Handler AuthResult authenticated = do mauth <- maybeAuth return $ maybe AuthenticationRequired (const Authorized) mauth authorizeAdmin :: Handler AuthResult authorizeAdmin = do mauth <- maybeAuth case mauth of Nothing -> return AuthenticationRequired Just (Entity _ u) | userAdmin u -> return Authorized | otherwise -> unauthorizedI MsgAuthNotAnAdmin authorizeBlogPost :: BlogPostId -> Handler AuthResult authorizeBlogPost blogPostId = do blogPost <- runDB $ get404 blogPostId let authorId = blogPostAuthorId blogPost mauth <- maybeAuth case mauth of Nothing -> return AuthenticationRequired Just (Entity id' u) | userAdmin u -> return Authorized | id' == authorId -> return Authorized | otherwise -> unauthorizedI MsgAuthNotAnAdmin authorizeProfile :: UserId -> Handler AuthResult authorizeProfile userId = do mauth <- maybeAuth case mauth of Nothing -> return AuthenticationRequired Just (Entity id' u) | userAdmin u -> return Authorized | id' == userId -> return Authorized | otherwise -> unauthorizedI MsgAuthNotAnAdmin instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId loginDest _ = HomeR logoutDest _ = HomeR redirectToReferer _ = False getAuthId creds = runDB $ do $(logDebug) $ "Extra account information: " <> (pack . show $ extra) x <- getBy $ UniqueUser ident case x of Just (Entity uid _) -> return $ Just uid Nothing -> do let name = lookupExtra "login" avatarUrl = lookupExtra "avatar_url" fmap Just $ insert $ User ident name avatarUrl False where ident = credsIdent creds extra = credsExtra creds lookupExtra key = fromMaybe (error "No " <> key <> " in extra credentials") (lookup key extra) authPlugins app = mapMaybe mkPlugin . appOA2Providers $ appSettings app where mkPlugin (OA2Provider{..}) = case (oa2provider, oa2clientId, oa2clientSecret) of (_, _, "not-configured") -> Nothing (_, "not-configured", _) -> Nothing ("github", cid, sec) -> Just $ oauth2Github (pack cid) (pack sec) _ -> Nothing authHttpManager = getHttpManager instance YesodAuthPersist App instance RenderMessage App FormMessage where renderMessage _ _ = russianFormMessage
ruHaskell/ruhaskell-yesod
Foundation.hs
mit
6,464
0
17
1,893
1,523
742
781
-1
-1
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- import Text.Printf import Data.List -- unbiased coin, probability of landing heads is 0.5 -- Expected value is sum(pi*vi) for all i computeExpectedValue :: [Int] -> Double computeExpectedValue = foldl' (\acc n -> (fromIntegral n)* 0.5 + acc) 0.0 main :: IO () main = do nstr <- getContents let ns = map read . tail . lines $ nstr putStrLn . printf "%.1f\n" $ computeExpectedValue ns
cbrghostrider/Hacking
HackerRank/Mathematics/Probability/bdayGift.hs
mit
804
0
13
135
127
67
60
9
1
import Data.Char import Data.List digitize :: Int -> [Int] digitize x = map digitToInt $ show x palindrome :: Eq a => [a] -> Bool palindrome xs = xs == (reverse xs) numdrome :: Int -> Bool numdrome = palindrome . digitize list = [x |a <- [1..999], b <- [1..999], let x = a*b] largestDrome = last $ sort $ filter numdrome list
johnprock/euler
p4.hs
mit
332
0
10
70
162
85
77
10
1
module Main where import Data.ByteString.Char8 as C8 (ByteString(..),readFile,unpack) import Data.List (intercalate) import System.Console.GetOpt (OptDescr(..),ArgDescr(..),ArgOrder(..),getOpt,usageInfo) import System.Environment (getArgs) import System.Exit (ExitCode(..),exitSuccess,exitWith) import Debug.Trace (trace) import Core (CDevice(..),CSequencer(..),CComponent(..),CInst(..),CArgType(..),CFormatAtom(..),SInst(..),SArgType(..)) import Configs (parseSequencersCfg,parseComponentsCfg,parseDeviceCfg) import Compiler (compile) data ClOptions = ClOptions { clOptionsOutFile :: String, clOptionsTextFile :: String, clOptionsSequencersFile :: String, clOptionsComponentsFile :: String, clOptionsDeviceFile :: String} deriving (Show) clHeader :: String clHeader = "seqasm [OPTION..] SOURCEFILE" clOptions :: [OptDescr (ClOptions -> ClOptions)] clOptions = [Option ['o'] ["outfile"] (ReqArg (\x -> (\ opts -> opts {clOptionsOutFile = x})) "File") "Output File", Option ['t'] ["textdebug"] (ReqArg (\x -> (\ opts -> opts {clOptionsTextFile = x})) "File") "Output Debug Text File", Option ['s'] ["sequencers"] (ReqArg (\x -> (\ opts -> opts {clOptionsSequencersFile = x})) "File") "Sequencers File", Option ['c'] ["components"] (ReqArg (\x -> (\ opts -> opts {clOptionsComponentsFile = x})) "File") "Components File", Option ['d'] ["device"] (ReqArg (\x -> (\ opts -> opts {clOptionsDeviceFile = x})) "File") "Device File"] main :: IO () main = do args <- getArgs case getOpt Permute clOptions args of (optArgs,[sourceFile],[]) -> do let options = foldr (\ x i -> x i) (ClOptions "" "" "" "" "") optArgs sequencersText <- C8.readFile $ clOptionsSequencersFile options componentsText <- C8.readFile $ clOptionsComponentsFile options deviceText <- C8.readFile $ clOptionsDeviceFile options sourceText <- C8.readFile $ sourceFile let parseResult = do sequencers <- parseSequencersCfg sequencersText components <- parseComponentsCfg componentsText device <- parseDeviceCfg sequencers components deviceText result <- compile device $ C8.unpack sourceText return result case parseResult of Right (result,resultText) -> do writeFile (clOptionsOutFile options) result writeFile (clOptionsTextFile options) resultText exitSuccess Left errorMessages -> do putStrLn errorMessages exitWith (ExitFailure 1) (_,_,errorMessages) -> do putStrLn $ intercalate "\n" errorMessages ++ usageInfo clHeader clOptions exitWith (ExitFailure 2)
horia141/bachelor-thesis
dev/SeqAsm/Main.hs
mit
2,850
0
20
707
880
487
393
52
3
module GHCJS.DOM.CSSValueList ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/CSSValueList.hs
mit
42
0
3
7
10
7
3
1
0
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE PatternGuards, MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts, FlexibleInstances, TypeSynonymInstances, UndecidableInstances, OverloadedStrings, MultiWayIf #-} module Basic.Eval (run, runProg, Eval(..) )where import Basic.Doub hiding (D) import Basic.AST import Basic.Type import Basic.Parser (parseDoubs) -- for INPUT import Data.Char (isNumber) import Data.Maybe (fromMaybe) import Data.Monoid import Data.List (uncons) import Data.List.Split (splitOn) import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Vector ((!?)) import qualified Data.Vector as V import qualified Data.Vector.Mutable as V (write) import Text.Printf (printf) import Text.Show.Pretty (ppShow, pPrint) import Control.Monad import Control.Monad.State import Control.Monad.Except import Control.Monad.Extra import System.Random import System.IO (hFlush, stdout) data Val = S Text | N Doub | A Dims (Vec Val) instance Eq Val where S a == S b = a == b N a == N b = a == b _ == _ = False instance TC Val where unifies = Yes . typeof typeof (S _) = Stringy typeof (N _) = Numeric typeof (A _ v) = maybe None typeof $ v !? 0 instance Show Val where showsPrec p v = case v of S t -> showString $ T.unpack t N d -> showString $ show d A dim v -> showString $ show v emptyString, zero :: Val emptyString = S T.empty zero = N 0 data VMErr = BadSubscript PC -- | On what line did it happen? Dims -- | What was the index used? Dims -- | What was the upper (inclusive) limit? | BadAddress PC -- | On what line did it happen? Int -- | What was the address? | BadType PC -- | On what line did it happen? Type -- | Expected this Type -- | Got this | NextError -- | Next without For PC -- | On what line did it happen? | ForError -- | For without Next PC -- | On what line did it happen? | WendError -- | Wend without While PC -- | On what line did it happen? | WhileError -- | While without Wend PC -- | On what line did it happen? | RetError -- | RETURN without GOSUB PC -- | On what line did it happen? instance Show VMErr where showsPrec p e = showString $ case e of BadSubscript linum tried real -> printf "on line %d ==> bad subscript: %M, for array with dim %M" linum tried real BadAddress pc targ -> printf "on line $d ==> bad target of a GOTO|GOSUB: %d" pc targ BadType pc expc got -> printf "on line %d ==> type mismatch: expected %T, got %T" pc expc got NextError pc -> printf "on line %d ==> NEXT without FOR" pc ForError pc -> printf "on line %d ==> FOR without NEXT" pc RetError pc -> printf "on line %d ==> RETURN without having called GOSUB" pc WendError pc -> printf "on line %d ==> WEND without WHILE" pc WhileError pc -> printf "on line %d ==> WHILE without WEND" pc type PC = Int data FlowCTX = InFor { lstart :: PC -- | Where to go each iteration repeat , lvar :: Var -- | Variable we loop over , toEnter :: Expr -- | test for entry , mstep :: VMState () -- | What to do each time we come back } | InWhile { lstart :: PC -- | Where to go each iteration repeat , toEnter :: Expr -- | test for loop entry, 0 => don't enter } | InSub { lstart :: PC -- | address to return to on a RET } instance Show FlowCTX where showsPrec p c = case c of InFor s v e _ -> showString $ "FOR start: " ++ show s ++ " var: " ++ show v InWhile s _ -> showString $ "WHILE start: " ++ show s InSub s -> showString $ "SUB start: " ++ show s data EvalState = EV { heap :: Map Var Val , pc :: Int , linumMap :: Map Int Int , flowStack :: [FlowCTX] , prog :: Vec Stmt } pushFlow :: (PC -> FlowCTX) -> VMState() pushFlow mkCtx = do ev <- get let oldStack = flowStack ev ctx = mkCtx $ pc ev put ev{flowStack = ctx : oldStack} logCtx ("new context: " ++ show ctx) st <- flowStack <$> get logCtx ("stack is \n" ++ ppShow st) popFlow :: VMState (Maybe FlowCTX) popFlow = do ev <- get case flowStack ev of [] -> logCtx "popped from empty stack" >> pure Nothing x:xs -> logCtx ("popped " ++ show x) >> put ev{flowStack = xs} >> pure (Just x) peekFlow :: VMState (Maybe FlowCTX) peekFlow = do mctx <- uncons . flowStack <$> get pure $ fst <$> mctx pushRet :: VMState () pushRet = pushFlow (InSub . succ) pushFor :: Var -> Expr -> VMState () -> VMState () pushFor var test step = pushFlow $ \pc -> InFor (1 + pc) var test step pushWhile :: Expr -> VMState() pushWhile e = pushFlow $ \pc -> InWhile (1 + pc) e getLineMap :: VMState (Map Int Int) getLineMap = linumMap <$> get getPC :: VMState PC getPC = pc <$> get getProg :: VMState (Vec Stmt) getProg = prog <$> get setPC :: PC -> VMState () setPC newPC = do ev <- get put ev{pc = newPC} incrPC :: VMState () incrPC = getPC >>= setPC . succ getRealLine :: VMState Int getRealLine = (M.!) <$> getLineMap <*> getPC asIndex :: Val -> VMState Int asIndex (N d) = pure $ floor d asIndex s = badType Numeric $ typeof s badAddr :: Int -> VMState a badAddr i = do l <- getRealLine throwError $ BadAddress l i badIdx :: Dims -> Dims -> VMState a badIdx tried real = do l <- getRealLine throwError $ BadSubscript l tried real badType :: Type -> Type -> VMState a badType expect actual = do l <- getRealLine throwError $ BadType l expect actual forError, nextError, whileError, wendError :: VMState a nextError = getRealLine >>= throwError . NextError forError = getRealLine >>= throwError . ForError wendError = getRealLine >>= throwError . WendError whileError = getRealLine >>= throwError . WhileError retError = getRealLine >>= throwError . RetError getVar :: Var -> VMState Val getVar v = accessVar v Nothing setVar :: Var -> Val -> VMState Val setVar var = accessVar var . Just accessVar :: Var -> Maybe Val -> VMState Val accessVar var mval = do ev <- get let oldHeap = heap ev (new, old) <- validate var mval $ M.lookup var oldHeap whenJust mval $ const (put ev{heap = M.insert var new oldHeap}) pure old -- | Validate does the heavy lifting for variable getting and setting. It -- checks index bounds and returns default values for variables that can -- have them (non-array vars). validate :: Var -- | variable we're accessing -> Maybe Val -- | Maybe we want to change it -> Maybe Val -- | What the heap says we have -> VMState (Val, Val) -- | (new, old) validate var mval Nothing = case var of SArr _ d@(Dims l) -> badIdx d (Dims $ Lit (LNum 0) <$ l) NArr _ d@(Dims l) -> badIdx d (Dims $ Lit (LNum 0) <$ l) SVar _ -> pure $ (fromMaybe emptyString mval, emptyString) NVar _ -> pure $ (fromMaybe zero mval, zero) validate var mval (Just v@(S _)) = pure $ (fromMaybe v mval, v) validate var mval (Just v@(N _)) = pure $ (fromMaybe v mval, v) validate var mval (Just a@(A adim v)) = setAt l a where dim@(Dims l) = dimsOf var idxErr = badIdx dim adim setAt :: [Expr] -> Val -> VMState (Val, Val) setAt [] v@(S _) = pure (fromMaybe v mval, v) setAt [] v@(N _) = pure (fromMaybe v mval, v) setAt (e:es) (A _ vec) = eval e >>= asIndex >>= \idx -> if idx <= V.length vec && idx > 0 then do (new, old) <- setAt es (vec V.! (idx - 1)) pure (A adim $ V.modify (\v -> V.write v (idx - 1) new) vec, old) else idxErr setAt _ _ = idxErr type VMState = ExceptT VMErr (StateT EvalState IO) logExpr, logLine, logStmt, logCtx, logEnd, logFor, logGoto :: String -> VMState () logg :: String -> VMState () loggHelp :: Int -> String -> VMState () logExpr = loggHelp 0 logLine = loggHelp 1 logStmt = loggHelp 2 logCtx = loggHelp 3 logEnd = loggHelp 4 logFor = loggHelp 5 logGoto = loggHelp 6 logg = loggHelp 100 loggHelp n = case n of -- _ -> const (pure ()) -- All 0 -> const (pure ()) -- Expr 1 -> const (pure ()) -- Line 2 -> const (pure ()) -- Stmt 3 -> const (pure ()) -- Ctx 4 -> const (pure ()) -- End 5 -> const (pure ()) -- For 6 -> const (pure ()) -- Goto _ -> liftIO . putStrLn class Eval a b | a -> b where eval :: a -> VMState b runProg :: Vec Stmt -> Map Int Int -> IO () runProg prg lmap = let init = EV { heap = M.empty , pc = 0 , linumMap = lmap , flowStack = [] , prog = prg } in do ret <- runStateT (runExceptT run) init case ret of (Left err, s) -> putStrLn "ERRORS:" >> print err (Right _, s )-> pure () run :: VMState () run = do pc <- getPC logLine $ "running line " ++ show pc prog <- getProg case prog !? pc of Nothing -> logEnd "Done" Just s -> eval s >> run instance Eval Stmt () where eval s = logStmt ("eval Statement : " ++ show s) >> case s of REM t -> incrPC NOP -> incrPC GOTO i -> goto i GOSUB i -> pushRet >> goto i ONGOTO e addrs -> ongoto e addrs ONGOSUB e addrs -> pushRet >> ongoto e addrs LET var e -> eval e >>= setVar var >> incrPC -- NEXT without any vars specified implicitly NEXT vs -> handleNext vs -- This is a doozy FOR var start end mstep -> do N s <- maybe (pure $ N 1) eval mstep N e <- eval end let test = if s < 0 then Prim (Gt (Var var) (Lit $ LNum e)) else Prim (Lte (Var var) (Lit $ LNum e)) let eachLoop = do res <- eval (Prim (Add (Var var) (Lit $ LNum s))) setVar var res >> pure () eval start >>= setVar var N v <- eval test if v /= 0 then pushFor var test eachLoop >> incrPC else do prog <- getProg let isNext (NEXT _) = True isNext _ = False case V.findIndex isNext prog of Nothing -> forError Just i -> setPC i WHILE mexpr -> do let test = fromMaybe (Lit $ LNum 1) mexpr N enter <- eval test if enter /= 0 then pushWhile test >> incrPC else do prog <- getProg let isWend (WEND _) = True isWend _ = False case V.findIndex isWend prog of Nothing -> whileError Just i -> setPC i WEND mexpr -> do N escape <- eval $ fromMaybe (Lit $ LNum 0) mexpr ctx <- popFlow case ctx of Just (InWhile lstart reenter) -> do N goback <- eval reenter if escape /= 0 || goback == 0 then incrPC else setPC lstart _ -> wendError IF _ _ _ -> error "IF statements should have been converted to IFGO by now" IFGO e i _ -> do N choice <- eval e if choice /= 0 then goto i else incrPC DIM dims -> mapM_ mkdim dims where stringName = ("$" `T.isSuffixOf`) mkdim (name, d@(Dims es)) = do ev <- get sizes <- mapM (eval >=> asIndex) es let oldHeap = heap ev (var, baseval) | stringName name = (SArr name d, emptyString) | otherwise = (NArr name d, zero) val = foldr mkArr baseval sizes mkArr size val = A d (V.replicate size val) put ev{heap = M.insert var val oldHeap} incrPC RET -> whileM $ do ctx <- popFlow logCtx ("returning, found ctx: " ++ show ctx) case ctx of Nothing -> retError Just (InSub start) -> setPC start >> pure False Just _ -> pure True END -> getProg >>= setPC . length -- jump to end PRINT [] -> liftIO (putStrLn "") >> incrPC PRINT args -> do foldM printArg 0 args case last args of PSem _ -> incrPC _ -> liftIO (putStrLn "") >> incrPC where printArg l a = case a of PTab e -> do val <- asIndex =<< eval e if val <= l then pure l else liftIO $ putStr (replicate (val - l) ' ') >> pure val PSem e -> printDelim "" " " e l PCom e -> printDelim "\t" "\t" e l PReg e -> printDelim "" " " e l printDelim sdel ndel e len = do v <- eval e case v of S str -> do liftIO $ T.putStr str liftIO $ putStr sdel pure (len + T.length str) N n -> let str = show n ++ ndel in liftIO $ putStr str >> pure (len + length str) INPUT mtext vars -> do whenJust mtext (liftIO . T.putStr) liftIO $ hFlush stdout inputs <- loopM takeInput [] mapM_ (uncurry setVar) $ zip vars inputs incrPC where ty = typeof $ head vars filt = case ty of Stringy -> \line -> pure [S line] Numeric -> \line -> case parseDoubs line of Just vals -> pure $ map N vals Nothing -> do putStrLn $ "Couldn't parse " ++ show line pure [] takeInput ls = do new <- liftIO (filt =<< T.getLine) let acc = ls ++ new if length acc >= length vars then pure (Right acc) else do liftIO $ putStr "\n??" >> hFlush stdout pure (Left acc) goto :: PC -> VMState () goto i = logGoto ("GOing to " ++ show i) >> ifM ((i <) . V.length <$> getProg) (setPC i) (badAddr i) ongoto e addrs = do i <- asIndex =<< eval e if i > 0 && i <= length addrs then goto (addrs !! (i - 1)) else incrPC -- `handleNext`, `matchFors` and `decideFor` manage the logic necessary for -- determining how to respond to a NEXT statement. The argument lets it -- determine whether the NEXT was invoked with variables (e.g. `NEXT I, J`) or -- without. `handlNext` is used with loopM, returning a Right value holding the -- address to goto once it's determined or a Left value if it needs to keep -- popping contexts. There are some opportunities for BASIC runtime errors -- here: If a NEXT references a variable that isn't an iterator of some loop, or -- if we are not, in fact, inside a loop. handleNext [] = loopM matchFors Nothing >>= setPC handleNext vs = loopM matchFors (Just vs) >>= setPC matchFors mvs = do -- We don't necessarily want to pop a context; that only happens -- when the loop terminates. Since that _should_ happen less often, -- we'll peek at it first, and actually pop it later if necessary. ctx <- peekFlow case ctx of -- No loop context on the stack: NEXT without FOR error Nothing -> nextError Just (InFor start lvar test eachLoop) -> do case mvs of -- Implicit NEXT: The InFor we found is the one we use. -- Don't give `decide` more variables to test if the loop -- terminal condition is met. Nothing -> logFor "implicit next" >> decideFor test eachLoop [] start -- Explicit NEXT Just (var:rest) -- The InFor is the one we want if its loop variable is -- the same as the one at the head of the list. We -- give `decide` the `rest` of the variables, in case -- the terminal condition is met and we need to test -- another variable. | lvar == var -> logFor "found the right var" >> decideFor test eachLoop rest start -- If the variables don't match, we keep looking for -- the correct loop context. This means we don't -- change the list of variables NEXT was given. | otherwise -> logFor "popping for missed var" >> popFlow >> pure (Left $ Just (var:rest)) -- Only reached when NEXT invoked with explicit variables. -- If a variable that isn't an iterator of a FOR loop is -- specified, we'll get a "NEXT without FOR" error Just [] -> nextError -- Context is not a For loop: can't invoke NEXT -- when the innermost context is a WHILE or SUB Just _ -> nextError -- We need a lot of context to determine how to proceed once a the -- right InFor context is found. decideFor :: Expr -- Expression to test for loop re-entry -> VMState () -- VMState update -> [Var] -> PC -> VMState (Either (Maybe [Var]) PC) decideFor test loop more start = do -- `loop` is the state-changing update that increments -- or decrements the loop variable. loop N enter <- eval test logFor $ "test is " ++ show test logFor $ "result is " ++ show enter pc <- getPC -- If `enter` is True, we jump back to the loop start if | enter /= 0 -> pure (Right start) -- Else, if there are no more variables to test, we simply move -- on to the next statement | null more -> popFlow >> pure (Right $ pc + 1) -- If there _are_ variables remaining, we need to keep popping -- contexts to determine where to go | otherwise -> popFlow >> pure (Left $ Just more) instance Eval Var Val where eval = getVar -- much nicer than Stmt instance Eval Expr Val where eval e = do logExpr ("evaling " ++ show e) res <- case e of Lit l -> eval l Prim op -> eval op Paren e -> eval e Var v -> eval v logExpr ("got " ++ show res) pure res instance Eval (Op Expr) Val where eval o = case o of Rnd a -> do n <- eval a case n of N d | d < 0 -> error "RND seeding not implemented yet" | d == 1 -> liftIO randomIO >>= pure . N | otherwise -> liftIO (randomRIO (0, d)) >>= pure . N Chp a -> do N d <- eval a pure (N $ fromIntegral $ floor d) Neg a -> do N d <- eval a pure . N $ negate d Not a -> do N d <- eval a pure $ if d == 0 then N 1 else N 0 Add a b -> case typeof a of Stringy -> do S l <- eval a S r <- eval b pure $ S (l <> r) Numeric -> numericOp a b (+) Sub a b -> numericOp a b (-) Div a b -> numericOp a b (/) Mul a b -> numericOp a b (*) Pow a b -> numericOp a b (**) Mod a b -> numericOp a b (%) And a b -> numericOp a b (.&.) Or a b -> numericOp a b (.|.) Xor a b -> numericOp a b xor Eq a b -> overloadedOp a b (fromBool (==)) Neq a b -> overloadedOp a b (fromBool (/=)) Gt a b -> overloadedOp a b (fromBool (>)) Gte a b -> overloadedOp a b (fromBool (>=)) Lt a b -> overloadedOp a b (fromBool (<)) Lte a b -> overloadedOp a b (fromBool (<=)) -- | Turn a comparison operator into a C-like operator, returning 1 for True -- and 0 for False. fromBool :: Ord a => (a -> a -> Bool) -> (a -> a -> Doub) fromBool op a b | a `op` b = 1 | otherwise = 0 numericOp a b op = do N l <- eval a N r <- eval b pure $ N (l `op` r) -- Helper for evaluating operators that work on Numerics and Strings overloadedOp :: Expr -> Expr -- Holy crap! A practical use of RankNTypes -> (forall a . Ord a => a -> a -> Doub) -> VMState Val overloadedOp a b op = do l <- eval a r <- eval b case (l, r) of -- This is why we need RankNTypes. The `op` is valid for any type installed -- in Ord. Without higher rank types, trying to use it here will fail -- unification because it could only be inferred as an operator on Text or Doub (S x, S y) -> pure $ N (x `op` y) (N x, N y) -> pure $ N (x `op` y) (S _, _ ) -> badType Stringy Numeric _ -> badType Numeric Stringy instance Eval Literal Val where eval (LNum d) = pure $ N d eval (LStr d) = pure $ S d
dmringo/pure-basic
src/Basic/Eval.hs
mit
21,557
0
25
8,005
6,590
3,266
3,324
-1
-1
import Data.Maybe (Maybe (..)) import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit hiding (path) import Test.HUnit.Base (Assertion) -- modules we will test import M3U.Common (EXTINF (..), M3U (..), M3UEntry (..)) import M3U.Read (fromFile) import M3U.Write (toOrderedMarkdown, toYAML) -- the first couple items here are hand constructed data used for testing -- purposes. -- data EXTINF = EXTINF { seconds ∷ Int , artist ∷ String , title ∷ String } testEXTINF :: EXTINF testEXTINF = EXTINF { seconds = 60 , artist = "testartist1" , title = "testtitle1" } -- data M3U = M3U { entries ∷ [M3UEntry] } deriving (Eq) testM3U :: M3U testM3U = M3U { entries = [ M3UEntry { info = Nothing , path = "testpath1" } , M3UEntry { info = Just testEXTINF , path = "testpath2" } , M3UEntry { info = Nothing , path = "testpath3" } ] } yamlExpected :: String yamlExpected = "- path: testpath1\n- path: testpath2\n title: testtitle1\n artist: testartist1\n- path: testpath3\n" toYAMLTest :: Assertion toYAMLTest = assertEqual "toYAMLPrefix" yamlExpected (toYAML testM3U) main :: IO () main = defaultMainWithOpts [ testCase "toYAML" toYAMLTest ] mempty
siddharthist/m3u-convert
test/Main.hs
mit
1,796
0
10
812
268
165
103
26
1
module Handler.Home where import Data.Maybe (fromJust) import Import import qualified GitHub as GH getHomeR :: Handler Html getHomeR = maybeAuthId >>= homeHandler _repository :: GH.Repository -> Widget _repository repo = $(widgetFile "_repository") homeHandler :: Maybe UserId -> Handler Html homeHandler Nothing = defaultLayout $ do setTitle "ScrumBut | Sign in" $(widgetFile "sign_in") homeHandler (Just userId) = do user <- runDB $ get userId let token = userToken $ fromJust user client <- GH.newClient token userRepos <- GH.fetchRepos client orgs <- GH.fetchOrgs client orgRepos <- concat <$> mapM (GH.fetchOrgRepos client) orgs defaultLayout $ do setTitle "ScrumBut | Repositories" $(widgetFile "repositories")
jspahrsummers/ScrumBut
Handler/Home.hs
mit
790
0
12
172
238
113
125
-1
-1
module Antiqua.Graphics.Colors( module Antiqua.Graphics.Colors, Color, rgb, dim, mult, mix ) where import Antiqua.Graphics.Color black :: Color black = rgb 0 0 0 white :: Color white = rgb 255 255 255 grey :: Color grey = rgb 128 128 128 darkGrey :: Color darkGrey = rgb 64 64 64 brown :: Color brown = rgb 150 75 0 red :: Color red = rgb 255 0 0 darkRed :: Color darkRed = rgb 128 0 0 green :: Color green = rgb 0 255 0 darkGreen :: Color darkGreen = rgb 0 128 0 blue :: Color blue = rgb 0 0 255 darkBlue :: Color darkBlue = rgb 0 0 128 yellow :: Color yellow = rgb 255 255 0
olive/antiqua-prime
src/Antiqua/Graphics/Colors.hs
mit
614
0
5
158
241
133
108
32
1
module Sing2 where fstString :: [Char] -> [Char] fstString x = x ++ " river" sndString :: [Char] -> [Char] sndString x = x ++ " than a mile" sing = if (x > y) then fstString x else sndString y where x = "Moon" y = "wider"
Numberartificial/workflow
haskell-first-principles/haskell-from-first-principles-master/05/05.08.08-fix-it-2.hs
mit
241
0
7
67
96
54
42
9
2
{- Advent of Code: Day 1 Santa is trying to deliver presents in a large apartment building, but he can't find the right floor. The directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors. For example: (()) and ()() both result in floor 0. ((( and (()(()( both result in floor 3. ))((((( also results in floor 3. ()) and ))( both result in floor -1 (the first basement level). ))) and )())()) both result in floor -3. To what floor do the instructions take Santa? -} -- Part one findFloor :: [Char] -> Int findFloor directions = parseElements directions 0 where parseElements :: [Char] -> Int -> Int parseElements [] floor = floor parseElements (x:xs) floor | x == '(' = parseElements xs (floor+1) | x == ')' = parseElements xs (floor-1) | otherwise = error ("Invalid element: " ++ (show x)) {- - --- Part Two --- Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on. For example: ) causes him to enter the basement at character position 1. ()()) causes him to enter the basement at character position 5. What is the position of the character that causes Santa to first enter the basement? -} findBasementEntryPosition :: [Char] -> Int findBasementEntryPosition directions = findPosition directions 0 1 where findPosition :: [Char] -> Int -> Int -> Int findPosition [] floor position = error ("Santa never enters the basement") findPosition (x:xs) floor position | x == ')' && floor == 0 = position | x == '(' = findPosition xs (floor+1) (position+1) | x == ')' = findPosition xs (floor-1) (position+1) | otherwise = error ("Invalid element: " ++ (show x))
samueljackson92/advent-of-code
day1/day1.hs
mit
2,109
0
12
419
347
175
172
17
2
module Control.Process( idP, (<.>), next, recursively, module Control.Process.Show, module Control.Process.Update, module Control.Process.Class ) where import Control.Process.Show import Control.Process.Update import Control.Process.Class import Types.Synonyms import Types.TextlunkyCommand import Types.GameState import Control.Monad.Trans.Free -- NB. if we change the type to: -- type Process state cmd r = -- FreeF cmd r () (FreeT cmd (state) r) -> StateT state IO r -- then the current Process is: -- Process GameState TextlunkyCommand () -- which is interesting because we might be able to form something new from it, -- but this is on the backburner because I don't really care that much. -- Just think it's interesting for discussion later. -- process Id idP :: Process idP = const $ return () infixr 9 <.> (<.>) :: Process -> Process -> Process pA <.> pB = \cmd -> pA cmd >> pB cmd recursively :: (Textlunky () -> Global GameState ()) -> Process -> UnwrappedCommand -> Global GameState () recursively f g cmd = do g cmd f (next cmd) next :: UnwrappedCommand -> Textlunky () next (Pure _) = return () next (Free End) = return () next (Free (Move d x)) = x next (Free (MoveTo e x)) = x next (Free (Pickup _ x)) = x next (Free (DropItem x)) = x next (Free (Jump _ x)) = x next (Free (Attack _ x)) = x next (Free (ShootD _ x)) = x next (Free (ShootE _ x)) = x next (Free (ShootSelf x)) = x next (Free (Throw _ x)) = x next (Free (Rope x)) = x next (Free (Bomb _ x)) = x next (Free (OpenGoldChest x)) = x next (Free (OpenChest x)) = x next (Free (ExitLevel x)) = x next (Free (DropDown x)) = x next (Free (Look _ x)) = x next (Free (Walls x)) = x next (Free (ShowEntities x)) = x next (Free (ShowFull x)) = x next (Free (ShowMe x)) = x next (Free (YOLO x)) = x
5outh/textlunky
src/Control/Process.hs
mit
1,980
0
9
541
742
388
354
52
1
----------------------------------------------------------------------- -- -- Haskell: The Craft of Functional Programming, 3e -- Simon Thompson -- (c) Addison-Wesley, 1996-2011. -- -- PicturesSVG -- -- The Pictures functionality implemented by translation -- SVG (Scalable Vector Graphics) -- -- These Pictures could be rendered by conversion to ASCII art, -- but instead are rendered into SVG, which can then be viewed in -- a browser: google chrome does a good job. -- ----------------------------------------------------------------------- module PicturesSVG where import System.IO import Test.QuickCheck import Control.Monad (liftM, liftM2) -- Pictures represened by a type of trees, so this is a deep -- embedding. data Picture = Img Image | Above Picture Picture | Beside Picture Picture | Over Picture Picture | FlipH Picture | FlipV Picture | Invert Picture | Empty deriving (Eq,Show) -- Coordinates are pairs (x,y) of integers -- -- o------> x axis -- | -- | -- V -- y axis type Point = (Int,Int) -- The Point in an Image gives the dimensions of the image in pixels. data Image = Image Name Point deriving (Eq,Show) data Name = Name String deriving (Eq,Show) -- -- The functions over Pictures -- above, beside, over :: Picture -> Picture -> Picture above x Empty = x above Empty x = x above x y = Above x y beside Empty x = x beside x Empty = x beside x y = Beside x y over x Empty = x over Empty x = x over x y = Over x y -- flipH is flip in a horizontal axis -- flipV is flip in a vertical axis -- negative negates each pixel -- The definitions of flipH, flipV, negative push the -- constructors through the binary operations to the images -- at the leaves. -- Original implementation incorrect: it pushed the -- flipH and flipV through all constructors ... -- Now it distributes appropriately over Above, Beside and Over. flipH, flipV, invert :: Picture -> Picture flipH (Above pic1 pic2) = (flipH pic2) `Above` (flipH pic1) flipH (Beside pic1 pic2) = (flipH pic1) `Beside` (flipH pic2) flipH (Over pic1 pic2) = (flipH pic1) `Over` (flipH pic2) flipH pic = FlipH pic flipV (Above pic1 pic2) = (flipV pic1) `Above` (flipV pic2) flipV (Beside pic1 pic2) = (flipV pic2) `Beside` (flipV pic1) flipV (Over pic1 pic2) = (flipV pic1) `Over` (flipV pic2) flipV pic = FlipV pic invert = Invert invertColour = Invert -- Convert an Image to a Picture img :: Image -> Picture img = Img -- -- Library functions -- -- Dimensions of pictures width,height :: Picture -> Int width (Img (Image _ (x,_))) = x width (Above pic1 pic2) = max (width pic1) (width pic2) width (Beside pic1 pic2) = (width pic1) + (width pic2) width (Over pic1 pic2) = max (width pic1) (width pic2) width (FlipH pic) = width pic width (FlipV pic) = width pic width (Invert pic) = width pic height (Img (Image _ (x,y))) = y height (Above pic1 pic2) = (height pic1) + (height pic2) height (Beside pic1 pic2) = max (height pic1) (height pic2) height (Over pic1 pic2) = max (height pic1) (height pic2) height (FlipH pic) = height pic height (FlipV pic) = height pic height (Invert pic) = height pic -- -- Converting pictures to a list of basic images. -- -- A Filter represents which of the actions of flipH, flipV -- and invert is to be applied to an image in forming a -- Basic picture. data Filter = Filter {fH, fV, neg :: Bool} deriving (Show) newFilter = Filter False False False data Basic = Basic Image Point Filter deriving (Show) -- Flatten a picture into a list of Basic pictures. -- The Point argument gives the origin for the coversion of the -- argument. flatten :: Point -> Picture -> [Basic] flatten (x,y) (Img image) = [Basic image (x,y) newFilter] flatten (x,y) (Above pic1 pic2) = flatten (x,y) pic1 ++ flatten (x, y + height pic1) pic2 flatten (x,y) (Beside pic1 pic2) = flatten (x,y) pic1 ++ flatten (x + width pic1 , y) pic2 flatten (x,y) (Over pic1 pic2) = flatten (x,y) pic2 ++ flatten (x,y) pic1 flatten (x,y) (FlipH pic) = map flipFH $ flatten (x,y) pic flatten (x,y) (FlipV pic) = map flipFV $ flatten (x,y) pic flatten (x,y) (Invert pic) = map flipNeg $ flatten (x,y) pic flatten (x,y) Empty = [] -- flip one of the flags for transforms / filter flipFH (Basic img (x,y) f@(Filter {fH=boo})) = Basic img (x,y) f{fH = not boo} flipFV (Basic img (x,y) f@(Filter {fV=boo})) = Basic img (x,y) f{fV = not boo} flipNeg (Basic img (x,y) f@(Filter {neg=boo})) = Basic img (x,y) f{neg = not boo} -- -- Convert a Basic picture to an SVG image, represented by a String. -- convert :: Basic -> String convert (Basic (Image (Name name) (width, height)) (x,y) (Filter fH fV neg)) = "\n <image x=\"" ++ show x ++ "\" y=\"" ++ show y ++ "\" width=\"" ++ show width ++ "\" height=\"" ++ show height ++ "\" xlink:href=\"" ++ name ++ "\"" ++ flipPart ++ negPart ++ "/>\n" where flipPart = if fH && not fV then " transform=\"translate(0," ++ show (2*y + height) ++ ") scale(1,-1)\" " else if fV && not fH then " transform=\"translate(" ++ show (2*x + width) ++ ",0) scale(-1,1)\" " else if fV && fH then " transform=\"translate(" ++ show (2*x + width) ++ "," ++ show (2*y + height) ++ ") scale(-1,-1)\" " else "" negPart = if neg then " filter=\"url(#negative)\"" else "" -- Outputting a picture. -- The effect of this is to write the SVG code into a file -- whose path is hardwired into the code. Could easily modify so -- that it is an argument of the call, and indeed could also call -- the browser to update on output. render :: Picture -> IO () render pic = let picList = flatten (0,0) pic svgString = concat (map convert picList) newFile = preamble ++ svgString ++ postamble in do outh <- openFile "svgOut.xml" WriteMode hPutStrLn outh newFile hClose outh -- Preamble and postamble: boilerplate XML code. preamble = "<svg width=\"100%\" height=\"100%\" version=\"1.1\"\n" ++ "xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n" ++ "<filter id=\"negative\">\n" ++ "<feColorMatrix type=\"matrix\"\n"++ "values=\"-1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 1 1 1 0 0\" />\n" ++ "</filter>\n" postamble = "\n</svg>\n" -- -- Examples -- whiteSquare = Img $ Image (Name "images/white.jpg") (50,50) blackSquare = Img $ Image (Name "images/black.jpg") (50,50) king = Img $ Image (Name "images/king.png") (50,50) queen = Img $ Image (Name "images/queen.png") (50,50) bishop = Img $ Image (Name "images/bishop.png") (50,50) knight = Img $ Image (Name "images/knight.png") (50,50) rook = Img $ Image (Name "images/rook.png") (50,50) pawn = Img $ Image (Name "images/pawn.png") (50,50) clear = Img $ Image (Name "images/clear.png") (50,50) horse = Img $ Image (Name "images/blk_horse_head.jpg") (150, 200) repeatH n img | n > 0 = foldl1 beside (replicate n img) | otherwise = error "The first argument to repeatH should be greater than 1" repeatV n img | n > 0 = foldl1 above (replicate n img) | otherwise = error "The first argument to repeatV should be greater than 1"
PavelClaudiuStefan/FMI
An_3_Semestru_1/ProgramareDeclarativa/Laboratoare/Laborator2/PicturesSVG.hs
cc0-1.0
7,699
0
18
2,038
2,314
1,246
1,068
124
5
{-Main.hs-} module Main where -------------------------------------------------------------------------------- -- |Import import LispVal import LispEval import LispConsole import System.Environment import Control.Monad -- |End Import -------------------------------------------------------------------------------- -- |This is the main function main :: IO () main = do args <- getArgs if null args then runRepl else runOne $ args
pennetti/scheme-repl
src/Main.hs
gpl-2.0
440
0
8
56
69
41
28
10
2
-- -- Copyright (c) 2013-2019 Nicola Bonelli <[email protected]> -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- {-# LANGUAGE FlexibleInstances #-} module CGrep.Token ( Token , MatchLine , tokens , tokenizer) where import qualified Data.ByteString.Char8 as C import qualified Data.DList as DL import Data.Char ( isSpace, isAlphaNum, isDigit, isAlpha, isHexDigit ) import Data.Array.Unboxed ( (!), listArray, UArray ) import CGrep.Types ( Text8, OffsetLine, Offset ) type Token = (Offset, String) type MatchLine = (OffsetLine, [Token]) type DString = DL.DList Char data TokenState = StateSpace | StateAlpha | StateDigit | StateBracket | StateOther deriving (Eq, Enum, Show) data TokenAccum = TokenAccum !TokenState !Offset DString (DL.DList Token) isCharNumberLT :: UArray Char Bool isCharNumberLT = listArray ('\0', '\255') (map (\c -> isHexDigit c || c `elem` ".xX") ['\0'..'\255']) {-# INLINE isCharNumberLT #-} isSpaceLT :: UArray Char Bool isSpaceLT = listArray ('\0', '\255') (map isSpace ['\0'..'\255']) {-# INLINE isSpaceLT #-} isAlphaLT :: UArray Char Bool isAlphaLT = listArray ('\0', '\255') (map (\c -> isAlpha c || c == '_') ['\0'..'\255']) {-# INLINE isAlphaLT #-} isAlphaNumLT :: UArray Char Bool isAlphaNumLT = listArray ('\0', '\255') (map (\c -> isAlphaNum c || c == '_' || c == '\'') ['\0'..'\255']) {-# INLINE isAlphaNumLT #-} isDigitLT :: UArray Char Bool isDigitLT = listArray ('\0', '\255') (map isDigit ['\0'..'\255']) {-# INLINE isDigitLT #-} isBracketLT :: UArray Char Bool isBracketLT = listArray ('\0', '\255') (map (`elem` "{[()]}") ['\0'..'\255']) {-# INLINE isBracketLT #-} mkToken :: Offset -> DString -> Token mkToken off ds = (off - length str, str) where str = DL.toList ds {-# INLINE mkToken #-} tokens :: Text8 -> [String] tokens = map snd . tokenizer {-# INLINE tokens #-} tokenizer :: Text8 -> [Token] tokenizer xs = (\(TokenAccum _ off acc out) -> DL.toList (if null (DL.toList acc) then out else out `DL.snoc` mkToken off acc)) $ C.foldl' tokens' (TokenAccum StateSpace 0 DL.empty DL.empty) xs where tokens' :: TokenAccum -> Char -> TokenAccum tokens' (TokenAccum StateSpace off _ out) x = case () of _ | isSpaceLT ! x -> TokenAccum StateSpace (off+1) DL.empty out | isAlphaLT ! x -> TokenAccum StateAlpha (off+1) (DL.singleton x) out | isDigitLT ! x -> TokenAccum StateDigit (off+1) (DL.singleton x) out | isBracketLT ! x -> TokenAccum StateBracket (off+1) (DL.singleton x) out | otherwise -> TokenAccum StateOther (off+1) (DL.singleton x) out tokens' (TokenAccum StateAlpha off acc out) x = case () of _ | isAlphaNumLT ! x -> TokenAccum StateAlpha (off+1) (acc `DL.snoc` x) out | isSpaceLT ! x -> TokenAccum StateSpace (off+1) DL.empty (out `DL.snoc` mkToken off acc) | isBracketLT ! x -> TokenAccum StateBracket (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | otherwise -> TokenAccum StateOther (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) tokens' (TokenAccum StateDigit off acc out) x = case () of _ | isCharNumberLT ! x -> TokenAccum StateDigit (off+1) (acc `DL.snoc` x) out | isSpaceLT ! x -> TokenAccum StateSpace (off+1) DL.empty (out `DL.snoc` mkToken off acc) | isAlphaLT ! x -> TokenAccum StateAlpha (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | isBracketLT ! x -> TokenAccum StateBracket (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | otherwise -> TokenAccum StateOther (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) tokens' (TokenAccum StateBracket off acc out) x = case () of _ | isSpaceLT ! x -> TokenAccum StateSpace (off+1) DL.empty (out `DL.snoc` mkToken off acc) | isAlphaLT ! x -> TokenAccum StateAlpha (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | isDigitLT ! x -> TokenAccum StateDigit (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | isBracketLT ! x -> TokenAccum StateBracket (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | otherwise -> TokenAccum StateOther (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) tokens' (TokenAccum StateOther off acc out) x = case () of _ | isSpaceLT ! x -> TokenAccum StateSpace (off+1) DL.empty (out `DL.snoc` mkToken off acc) | isAlphaLT ! x -> TokenAccum StateAlpha (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | isDigitLT ! x -> if DL.toList acc == "." then TokenAccum StateDigit (off+1) (acc `DL.snoc` x) out else TokenAccum StateDigit (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | isBracketLT ! x -> TokenAccum StateBracket (off+1) (DL.singleton x) (out `DL.snoc` mkToken off acc) | otherwise -> TokenAccum StateOther (off+1) (acc `DL.snoc` x) out
awgn/cgrep
src/CGrep/Token.hs
gpl-2.0
6,452
0
15
2,038
2,010
1,068
942
105
7
-- ProblemaDelViajante.hs -- Problema del viajante. -- JosΓ© A. Alonso JimΓ©nez https://jaalonso.github.com -- ===================================================================== module Tema_24.ProblemaDelViajante where -- --------------------------------------------------------------------- -- DescripciΓ³n del problema -- -- --------------------------------------------------------------------- -- Dado un grafo no dirigido con pesos encontrar una camino en el grafo -- que visite todos los nodos exactamente una vez y cuyo coste sea -- mΓ­nimo. -- -- Notaciones: -- + Los vΓ©rtices del grafo son 1,2,...,n. -- + p(i,j) es el peso del arco que une i con j. Se supone que p(i,j)=0, -- si i=j y que p(i,j)=infinito si no hay ningΓΊn arco que una i con -- j. -- + El vΓ©rtice inicial y final es el n. -- + c(i,S) es el camino mΓ‘s corto que comienza en i, termina en n y -- pasa exactamente una vez por cada uno de los vΓ©rtices del conjunto -- S. -- -- RelaciΓ³n de recurrencia: -- + c(i,vacio) = p(i,n), si i != n -- + c(i,S) = min {p(i,j)+c(j,S-{j} |j en S}, si i != n, i no en S. -- -- La soluciΓ³n es c(n,{1,...,n-1}. -- --------------------------------------------------------------------- -- LibrerΓ­as auxiliares -- -- --------------------------------------------------------------------- -- Nota: Elegir una implementaciΓ³n de Dinamica. -- import Tema_24.Dinamica import I1M.Dinamica -- Nota: Elegir una implementaciΓ³n de los grafos. -- import Tema_22.GrafoConVectorDeAdyacencia -- import Tema_22.GrafoConMatrizDeAdyacencia import I1M.Grafo -- --------------------------------------------------------------------- -- ImplementaciΓ³n de conjuntos de enteros como nΓΊmeros enteros -- -- --------------------------------------------------------------------- -- Los conjuntos se representan por nΓΊmeros enteros. type Conj = Int -- (conj2Lista c) es la lista de los elementos del conjunto c. Por -- ejemplo, -- conj2Lista 24 == [3,4] -- conj2Lista 30 == [1,2,3,4] -- conj2Lista 22 == [1,2,4] conj2Lista :: Conj -> [Int] conj2Lista s = c2l s 0 where c2l 0 _ = [] c2l n i | odd n = i : c2l (n `div` 2) (i+1) | otherwise = c2l (n `div` 2) (i+1) -- maxConj es el mΓ‘ximo nΓΊmero que puede pertenecer al conjunto. Depende -- de la implementaciΓ³n de Haskell. Por ejemplo, -- maxConj == 29 maxConj :: Int maxConj = truncate (logBase 2 (fromIntegral maxInt)) - 1 where maxInt = maxBound::Int -- vacio es el conjunto vacΓ­o. vacio :: Conj vacio = 0 -- (esVacio c) se verifica si c es el conjunto vacΓ­o. esVacio :: Conj -> Bool esVacio n = n == 0 -- (conjCompleto n) es el conjunto de los nΓΊmeros desde 1 hasta n. conjCompleto :: Int -> Conj conjCompleto n | (n >= 0) && (n <= maxConj) = 2^(n+1)-2 | otherwise = error ("conjCompleto:" ++ show n) -- (inserta x c) es el conjunto obtenido aΓ±adiendo el elemento x al -- conjunto c. inserta :: Int -> Conj -> Conj inserta i s | (i >=0 ) && (i <= maxConj) = d'*e+m | otherwise = error ("inserta: elemento ilegal =" ++ show i) where (d,m) = divMod s e e = 2^i d' = if odd d then d else d+1 -- (elimina x c) es el conjunto obtenido eliminando el elemento x -- del conjunto c. elimina :: Int -> Conj -> Conj elimina i s = d'*e+m where (d,m) = divMod s e e = 2^i d' = if odd d then d-1 else d -- --------------------------------------------------------------------- -- Ejemplos de grafos -- -- --------------------------------------------------------------------- -- Se usarΓ‘n los siguientes ejemplos de grafos, generados a partir de la -- lista ded adyaciencia, donde se ha puesto un peso de 100 entre los -- nodos que no estΓ‘n unidos por un arco. -- e1 es el grafo (de la pΓ‘gina 192): -- -- 4 5 -- +----- 2 -----+ -- | |1 | -- | 1 | 8 | -- 1----- 3 -----5 -- | \2 / -- | 6 2\ /5 -- +----- 4 --6 -- ej1 :: Grafo Int Int ej1 = creaGrafo ND (1,6) [(i,j,(v1!!(i-1))!!(j-1)) |i<-[1..6],j<-[1..6]] v1 :: [[Int]] v1 = [[ 0, 4, 1, 6,100,100], [ 4, 0, 1,100, 5,100], [ 1, 1, 0,100, 8, 2], [ 6,100,100, 0,100, 2], [100, 5, 8,100, 0, 5], [100,100, 2, 2, 5, 0]] ej2 :: Grafo Int Int ej2 = creaGrafo ND (1,6) [(i,j,(v2!!(i-1))!!(j-1)) |i<-[1..6],j<-[1..6]] v2 :: [[Int]] v2 = [[ 0, 3, 10, 11, 7, 25], [ 3, 0, 6, 12, 8, 26], [ 10, 6, 0, 9, 4, 20], [ 11, 12, 9, 0, 5, 15], [ 7, 8, 4, 5, 0, 18], [ 25, 26, 20, 15, 18, 0]] -- --------------------------------------------------------------------- -- SoluciΓ³n mediante programaciΓ³n dinΓ‘mica -- -- --------------------------------------------------------------------- -- Los Γ­ndices de la matriz de cΓ‘lculo son de la forma (i,S) y sus -- valores (v,xs) donde xs es el camino mΓ­nimo desde i hasta n visitando -- cada vΓ©rtice de S exactamente una vez y v es el coste de xs. type IndicePV = (Int,Conj) type ValorPV = (Int,[Int]) -- (viajante g) es el par (v,xs) donde xs es el camino de menor coste -- que pasa exactamente una vez por todos los nodos del grafo g -- empezando en su ΓΊltimo nodo y v es su coste. Por ejemplo, -- Ξ»> viajante ej1 -- (20,[6,4,1,3,2,5,6]) -- Ξ»> viajante ej2 -- (56,[6,3,2,1,5,4,6]) viajante :: Grafo Int Int -> (Int,[Int]) viajante g = valor t (n,conjCompleto (n-1)) where n = length (nodos g) t = dinamica (calculaPV g n) (cotasPV n) -- (calculaPV g n t (i,k)) es el valor del camino mΓ­nimo en el grafo g -- desde i hasta n visitando cada nodo del conjunto k exactamente una -- vez calculado usando la tabla t. calculaPV :: Grafo Int Int -> Int -> Tabla IndicePV ValorPV -> IndicePV -> ValorPV calculaPV g n t (i,k) | esVacio k = (peso i n g,[i,n]) | otherwise = minimum [sumaPrim (valor t (j, elimina j k)) (peso i j g) | j <- conj2Lista k] where sumaPrim (v,xs) v' = (v+v',i:xs) -- (cotasPV n) son las cotas de la matriz de cΓ‘lculo del problema del -- viajante en un grafo con n nodos. cotasPV :: Int -> ((Int,Conj),(Int,Conj)) cotasPV n = ((1,vacio),(n,conjCompleto n))
jaalonso/I1M-Cod-Temas
src/Tema_24/ProblemaDelViajante.hs
gpl-2.0
6,370
0
12
1,574
1,389
821
568
67
2
module Sound.Tidal.Params where import Sound.Tidal.Stream import Sound.Tidal.Pattern import Sound.OSC.FD import Sound.OSC.Datum import Data.Map as Map make' :: (a -> Datum) -> Param -> Pattern a -> OscPattern make' toOsc par p = fmap (\x -> Map.singleton par (defaultV x)) p where defaultV a = Just $ toOsc a sound :: Pattern String -> OscPattern sound = make' string sound_p sound_p = S "sound" Nothing offset :: Pattern Double -> OscPattern offset = make' float offset_p offset_p = F "offset" (Just 0) begin :: Pattern Double -> OscPattern begin = make' float begin_p begin_p = F "begin" (Just 0) end :: Pattern Double -> OscPattern end = make' float end_p end_p = F "end" (Just 1) speed :: Pattern Double -> OscPattern speed = make' float speed_p speed_p = F "speed" (Just 1) pan :: Pattern Double -> OscPattern pan = make' float pan_p pan_p = F "pan" (Just 0.5) velocity :: Pattern Double -> OscPattern velocity = make' float velocity_p velocity_p = F "velocity" (Just 0) vowel :: Pattern String -> OscPattern vowel = make' string vowel_p vowel_p = S "vowel" (Just "") cutoff :: Pattern Double -> OscPattern cutoff = make' float cutoff_p cutoff_p = F "cutoff" (Just 0) resonance :: Pattern Double -> OscPattern resonance = make' float resonance_p resonance_p = F "resonance" (Just 0) accelerate :: Pattern Double -> OscPattern accelerate = make' float accelerate_p accelerate_p = F "accelerate" (Just 0) shape :: Pattern Double -> OscPattern shape = make' float shape_p shape_p = F "shape" (Just 0) kriole :: Pattern Int -> OscPattern kriole = make' int32 kriole_p kriole_p = I "kriole" (Just 0) gain :: Pattern Double -> OscPattern gain = make' float gain_p gain_p = F "gain" (Just 1) cut :: Pattern Int -> OscPattern cut = make' int32 cut_p cut_p = I "cut" (Just (0)) delay :: Pattern Double -> OscPattern delay = make' float delay_p delay_p = F "delay" (Just (0)) delaytime :: Pattern Double -> OscPattern delaytime = make' float delaytime_p delaytime_p = F "delaytime" (Just (-1)) delayfeedback :: Pattern Double -> OscPattern delayfeedback = make' float delayfeedback_p delayfeedback_p = F "delayfeedback" (Just (-1)) crush :: Pattern Double -> OscPattern crush = make' float crush_p crush_p = F "crush" (Just 0) coarse :: Pattern Int -> OscPattern coarse = make' int32 coarse_p coarse_p = I "coarse" (Just 0) hcutoff :: Pattern Double -> OscPattern hcutoff = make' float hcutoff_p hcutoff_p = F "hcutoff" (Just 0) hresonance :: Pattern Double -> OscPattern hresonance = make' float hresonance_p hresonance_p = F "hresonance" (Just 0) bandf :: Pattern Double -> OscPattern bandf = make' float bandf_p bandf_p = F "bandf" (Just 0) bandq :: Pattern Double -> OscPattern bandq = make' float bandq_p bandq_p = F "bandq" (Just 0) unit :: Pattern String -> OscPattern unit = make' string unit_p unit_p = S "unit" (Just "rate") loop :: Pattern Int -> OscPattern loop = make' int32 loop_p loop_p = I "loop" (Just 1)
kindohm/Tidal
Sound/Tidal/Params.hs
gpl-3.0
2,948
0
10
520
1,118
568
550
87
1
module Diamond2 where import Diamond4 y = 2
roberth/uu-helium
test/make/Diamond2.hs
gpl-3.0
46
0
4
10
12
8
4
3
1
{- ============================================================================ | Copyright 2011 Matthew D. Steele <[email protected]> | | | | This file is part of Fallback. | | | | Fallback is free software: you can redistribute it and/or modify it under | | the terms of the GNU General Public License as published by the Free | | Software Foundation, either version 3 of the License, or (at your option) | | any later version. | | | | Fallback is distributed in the hope that it will be useful, but WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for | | more details. | | | | You should have received a copy of the GNU General Public License along | | with Fallback. If not, see <http://www.gnu.org/licenses/>. | ============================================================================ -} module Fallback.Data.Bijection (Bijection, make, getA, getB, invert) where import Data.Array ((!), Array, Ix, assocs, listArray, range) import Data.List (foldl') import qualified Data.Map as Map ------------------------------------------------------------------------------- data Bijection a b = Bijection !(Array a b) !(Array b a) make :: (Bounded a, Bounded b, Ix a, Ix b) => (a -> b) -> Bijection a b make fn = Bijection arr1 arr2 where list1 = map fn $ range (minBound, maxBound) arr1 = listArray (minBound, maxBound) $ foldr seq list1 list1 collide _ _ = error "Bijection.make: collision" add m (a, b) = Map.insertWith collide b a m map2 = foldl' add Map.empty $ assocs arr1 arr2 = listArray (minBound, maxBound) $ Map.elems map2 -- | /O(1)/. Look up the @a@ value for the corresponding @b@ value. getA :: (Ix b) => Bijection a b -> b -> a getA (Bijection _ arr) key = arr ! key -- | /O(1)/. Look up the @b@ value for the corresponding @a@ value. getB :: (Ix a) => Bijection a b -> a -> b getB (Bijection arr _) key = arr ! key -- | /O(1)/. Produce the inverse bijection. invert :: Bijection a b -> Bijection b a invert (Bijection arr1 arr2) = Bijection arr2 arr1 -------------------------------------------------------------------------------
mdsteele/fallback
src/Fallback/Data/Bijection.hs
gpl-3.0
2,715
0
9
908
435
234
201
24
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Crypto.Hash (hash, MD5) import Data.Maybe import Data.Monoid import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Control.Monad.IO.Class import Control.Monad (when) import Reflex.Dom hiding ((.~)) import Reflex.Dom.Xhr (performRequestAsync, xhrRequest, decodeXhrResponse) import Data.Default (def) import Lib import Types import Control.Lens hiding (Reversed, from, to) import Data.Time.Clock import Data.Time.Calendar import Data.Time.Format main :: IO () main = mainWidget bodyWidget bodyWidget :: MonadWidget t m => m () bodyWidget = do el "header" $ elClass "h1" "page-title" homePageLink elClass "div" "container" $ do (fromInput, toInput, showReverse, showToday) <- elClass "div" "input-container" $ do (fI, tI) <- elClass "div" "dateinput-container" $ (,) <$> newDateInput "From: YYYY-MM-DD" <*> newDateInput "To: YYYY-MM-DD" (srC, stC) <- elClass "div" "checkbox-container" $ (,) <$> newCheckBox "Reverse" <*> newCheckBox "Only today" return (fI, tI, srC, stC) let zippedDyn = updated $ zipDynWith toQuery (_textInput_value fromInput) (_textInput_value toInput) asyncRequest <- performRequestAsync $ fforMaybe zippedDyn changeInput post <- getPostBuild initialRequest <- performRequestAsync (const (apiRequest "") <$> post) today <- liftIO getCurrentTime rec state <- foldDyn updateState initialState updates let updates = leftmost -- Http Request from date inputs [ xhrToCommand <$> asyncRequest -- Start request when page loads , xhrToCommand <$> initialRequest -- "Reverse Messages" checkbox , changeOrder <$> _checkbox_change showReverse -- "Only show today" checkbox , changeFilter today <$> _checkbox_change showToday -- We start fetching the data , const (SetStatus Loading) <$> fforMaybe zippedDyn changeInput ] _ <- dyn (stateToWidget <$> state) return () homePageLink :: DomBuilder t m => m () homePageLink = do text "#" elAttr "a" ("href" =: itaLink ) (text "haskell.it") text " log" itaLink :: T.Text itaLink = "http://haskell-ita.it/" changeOrder :: Bool -> Command changeOrder True = SetOrder Reversed changeOrder False = SetOrder Normal changeFilter :: UTCTime -> Bool -> Command changeFilter now True = SetFilter (OnlyToday now) changeFilter _ False = SetFilter None changeInput :: QueryDates -> Maybe (XhrRequest ()) changeInput Neither = Nothing changeInput notNull = Just $ apiRequest finalParams where finalParams = toParams notNull apiRequest :: T.Text -> XhrRequest () apiRequest params = xhrRequest "GET" (apiUrl <> params) def apiUrl :: T.Text apiUrl = "/api/log/" toParams :: QueryDates -> T.Text toParams (From from) = "?from=" <> from toParams (To to) = "?to=" <> to toParams (Both from to) = "?from=" <> from <> "&" <> "to=" <> to toParams Neither = "" stateToWidget :: (MonadWidget t m) => State -> m () stateToWidget localState = elClass "div" "data-container" $ case _httpStatus localState of Ok -> do elClass "p" "statusMessage" (text . showLoadedStatus $ localState) elClass "p" "fromDate" (text (maybe invalidDate (showDate . runFD) $ _fromDate localState)) elClass "p" "toDate" (text (maybe invalidDate (showDate . runTD) $ _toDate localState)) elClass "table" "logtable" $ buildTable localState x -> elClass "p" "statusMessage" (text . showStatus $ x) buildTable :: (MonadWidget t m ) => State -> m () buildTable localState = do elClass "thead" "loghead" $ el "tr" $ do el "th" $ text "Timestamp (UTC)" el "th" $ text "Nickname" el "th" $ text "Message" elClass "tbody" "logbody" $ mapM_ (toRow (_dateFilter localState)) logRows where logRows = case _order localState of Normal -> fromMaybe [] (_messages localState) Reversed -> reverse $ fromMaybe [] (_messages localState) showLoadedStatus :: State -> T.Text showLoadedStatus localState = showStatus (_httpStatus localState) <> " " <> (T.pack . show . length) (fromMaybe [] (_messages localState)) <> " messages" toRow :: (MonadWidget t m) => Filter -> PrivMsg -> m () toRow (OnlyToday today) msg = when (isToday today msg) (buildRow msg) toRow _ msg = buildRow msg buildRow :: (MonadWidget t m) => PrivMsg -> m () buildRow msg = elClass "tr" "logrow" $ do el "td" (text . showDate $ timestamp msg) let md5Hash :: MD5 = hash . encodeUtf8 . nickname $ msg let nickColor = "#" <> T.take 6 (T.pack . show $ md5Hash) elAttr "td" ("style" =: ("color: " <> nickColor)) (text $ nickname msg) el "td" (text $ message msg) showDate :: UTCTime -> T.Text showDate = T.pack . formatTime defaultTimeLocale "%F %T" invalidDate :: T.Text invalidDate = "Invalid Date" showStatus :: Status -> T.Text showStatus Loading = "Loading" showStatus Lib.Invalid = "Invalid date" showStatus ServerError = "Error while fetching data" showStatus Ok = "Loaded" -- Try and parse the response xhrToCommand :: XhrResponse -> Command xhrToCommand response = fromMaybe (SetStatus ServerError) $ UpdateMessages <$> decodeXhrResponse response -- Update the state according to the command updateState :: Command -> State -> State updateState cmd oldState = case cmd of SetStatus newStatus -> oldState & httpStatus .~ newStatus UpdateMessages response -> updateStateResponse response oldState SetOrder newOrder -> oldState & order .~ newOrder SetFilter newFilter -> oldState & dateFilter .~ newFilter updateStateResponse :: LogResponse -> State -> State updateStateResponse (LogResponse stat fromD toD mess) oldState = case stat of Ok -> oldState & Types.messages .~ Just mess & Types.fromDate .~ Just (FD fromD) & Types.toDate .~ Just (TD toD) & Types.httpStatus .~ Ok x -> oldState & Types.messages .~ Nothing & Types.fromDate .~ Nothing & Types.toDate .~ Nothing & Types.httpStatus .~ x -- Is the PrivMsg the same day as the utctime? isToday :: UTCTime -> PrivMsg -> Bool isToday today msg = diffDays (utctDay today) (utctDay . timestamp $ msg) < 1 toQuery :: T.Text -> T.Text -> QueryDates toQuery from to = let validF = validDate from validT = validDate to in case (validF, validT) of -- The dates can either be Valid, Invalid or Empty -- When one date is empty or invalid and the other is valid -- we shouldn't keep fetching data for the Valid when the invalid/empty -- one changes (ValidDate, EmptyField) -> From from (EmptyField, ValidDate) -> To to (ValidDate, ValidDate ) -> Both from to _ -> Neither validDate :: T.Text -> InputCase validDate date | T.null date = EmptyField | isJust (parseTimeM False defaultTimeLocale "%F" (T.unpack date) :: Maybe UTCTime) = ValidDate | otherwise = InvalidDate newCheckBox :: (DomBuilder t m, PostBuild t m) => T.Text -> m (Checkbox t) newCheckBox label = el "div" $ do text label checkbox False def newDateInput :: (MonadWidget t m) => T.Text -> m (TextInput t) newDateInput defText = textInput $ def & textInputConfig_inputType .~ "date" & textInputConfig_attributes .~ constDyn attri where attri = "placeholder" =: defText
Arguggi/irc-log
frontend/src/Main.hs
gpl-3.0
7,795
0
20
1,953
2,329
1,163
1,166
158
4
{-# LANGUAGE NoMonomorphismRestriction, PackageImports, TypeFamilies, ScopedTypeVariables #-} module HEP.Physics.TTBar.Analysis.Separate where import HEP.Util.Functions import HROOT import HEP.Parser.LHCOAnalysis.PhysObj hiding (FourMomentum,fourmomfrometaphipt,trd3) import HEP.Physics.TTBar.Error import HEP.Physics.TTBar.Reconstruction.Leptonic import HEP.Physics.TTBar.Reconstruction.Hadronic chisqrcut :: TH1F -> Double -> SemiLepTopInfo -> ((Double,Double),Double) -> IO () chisqrcut hist cutval sinfo (x,y) = if y < cutval then do let einfo = cnstrctSemiLepExc4Mom sinfo x mtopmass = sqrt $ sqr4 (lepton_4mom einfo `plus` neutrino_4mom einfo `plus` bquark_4mom einfo) fill1 hist mtopmass print mtopmass else return () topjetinvmass_w_chisqrcut_print :: Double -> Double -> PhyEventClassified -> IO () topjetinvmass_w_chisqrcut_print chisqrcutl chisqrcuth p = do let sinfo = eventToInfo p (_,y) <- chisqr_min jetError lepError sinfo putStrLn $ "chisqrcutl = " ++ show chisqrcutl putStrLn $ "y = " ++ show y if y < chisqrcutl then do let -- einfo = cnstrctSemiLepExc4Mom sinfo x -- topmom = lepton_4mom einfo -- `plus` neutrino_4mom einfo -- `plus` bquark_4mom einfo otherjet' = otherjets sinfo -- ltopinvmass = sqrt $ sqr4 topmom thjresult = threejetinvmass_chisqr jetError chisqrcuth otherjet' {- htopinvmass -} if (not.null) thjresult then do let thj' = head thjresult print (eventid p, y, fst thj') else return () else return ()
wavewave/ttbar
lib/HEP/Physics/TTBar/Analysis/Separate.hs
gpl-3.0
2,027
0
16
775
401
213
188
34
3
module LP.Read where import Data.Maybe (fromMaybe) import Data.Map import LP.Utils import Stundenplan data LPParseError v = InvalidDouble v Double | InexistentVar v deriving Show stupidParse :: LPVar a v => [a] -> Map v Double -> Either (LPParseError v) [a] stupidParse as lpResult = parseList $ assocs lpResult where parseList [] = Right [] parseList ((_, 0) : vds) = parseList vds parseList ((v, 1) : vds) = do rest <- parseList vds -- maybe (Left (InexistentVar v)) (return . (: rest)) $ val as v return $ maybe rest (: rest) $ val as v parseList ((v, d) : _) = Left $ InvalidDouble v d -- TODO Lokal parseStundenplan :: Seminar -> String -> Map String Double -> Either (LPParseError String) LokalStundenplan parseStundenplan seminar version lpResult = do globalBelegung <- stupidParse (moeglicheGlobalBelegungen seminar) lpResult betreuerBelegung <- stupidParse (moeglicheBetreuerBelegungen seminar) lpResult raumBelegung <- stupidParse (moeglicheRaumBelegungen seminar) lpResult lokalBelegungen <- stupidParse (moeglicheLokalBelegungen seminar) lpResult let globalplan = GlobalStundenplan seminar globalBelegung betreuerBelegung raumBelegung version return $ LokalStundenplan globalplan lokalBelegungen
turion/hasched
LP/Read.hs
gpl-3.0
1,269
0
12
229
388
195
193
25
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} -- | Heterogeneous lists in Haskell. module HList where -- | Heterogeneous lists with GADTs (and DataKinds, and TypeOperators). -- -- data HList tys where -- `tys` denotes the types of all the elements in the list! HNil :: HList '[] (:>) :: h -> HList t -> HList (h ': t) infixr 5 :> -- | Using HList we can we can write heterogeneous lists like this one. xs0 :: HList ([String, Int]) xs0 = "foo" :> 1 :> HNil xs1 = "bar" :> xs0 :> HNil xs2 = True :> () :> [Just 7] :> "Hi" :> HNil hhead :: HList (ty: tys) -> ty hhead (x :> _) = x hsize :: HList tys -> Int hsize HNil = 0 hsize (_ :> xs) = 1 + hsize xs -- | To make this work you need "PromotedDatatypes" -- Also, you need to enable TypeOperators, DataKinds, PolyKinds -- -- To get the trick working you use data-kinds. -- | Also you can use partial-type signatures (type holes). To enable this use -- the language extension 'PartialTypeSignature'. -- | Now, how would you make a function 'get' for 'HList'? You can't even type -- it? How can you know which type it will return? We need to define another -- type. data Elem list elt where EZ :: Elem (x ': xs) x ES :: Elem xs x -> Elem (y ': xs) x -- | 'Elem xs x' allows to *select* a type in a list of types. -- | The first constructor selects the first element in a list of types. The -- second one selects the next element. -- | To try this in the ghci REPL, -- -- ghci> :set -XDataKinds -- ghci> :t EZ :: Elem '[Bool, Int] Bool -- -- Try also -- -- ghci> :t EZ :: Elem '[Bool, Int] Int -- -- and see what happens. -- -- Also look at the types of the following expressions: -- -- > ES EZ :: Elem (y : x : xs) x -- > ES (ES EZ) :: Elem (y : y1 : x : xs) x -- > ES (ES (ES EZ)) :: Elem (y : y1 : y2 : x : xs) x -- -- | Now how could we use 'Elem' to write our get function? get :: Elem tys ty -> HList tys -> ty get EZ (x :> _) = x get (ES tys) (_ :> xs) = get tys xs example = get (ES EZ) ("hello" :> 2 :> HNil)
capitanbatata/apath-slfp
competent/gadts/src/HList.hs
gpl-3.0
2,055
0
10
494
388
225
163
24
1
{-# LANGUAGE PatternSynonyms #-} {-| Module : ANSI Description : ANSI escape codes Copyright : (c) FrΓ©dΓ©ric BISSON, 2014 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX ANSI escape codes. -} module Minitel.Constants.ANSI where import Minitel.Constants.ASCII as ASCII -- * Column number 04 pattern ICH = ASCII.At -- Insert CHaracter pattern CUU = ASCII.UpperA -- CUrsor Up pattern CUD = ASCII.UpperB -- CUrsor Down pattern CUF = ASCII.UpperC -- CUrsor Forward pattern CUB = ASCII.UpperD -- CUrsor Back pattern CNL = ASCII.UpperE -- Cursor Next Line pattern CPL = ASCII.UpperF -- Cursor Preceding Line pattern CHA = ASCII.UpperG -- Cursor Horizontal Absolute pattern CUP = ASCII.UpperH -- CUrsor Position pattern CHT = ASCII.UpperI -- Cursor Horizontal Tabulation pattern ED = ASCII.UpperJ -- Erase Display pattern EL = ASCII.UpperK -- Erase in Line pattern IL = ASCII.UpperL -- Insert Line pattern DL = ASCII.UpperM -- Delete Line pattern EF = ASCII.UpperN -- Erase in Field pattern EA = ASCII.UpperO -- Erase in Area -- * Column number 05 pattern DCH = ASCII.UpperP -- Delete CHaracter pattern SEE = ASCII.UpperQ -- Select Editing Extent pattern CPR = ASCII.UpperR -- Cursor Position Report pattern SU = ASCII.UpperS -- Scroll Up pattern SD = ASCII.UpperT -- Scroll Down pattern NP = ASCII.UpperU -- Next Page pattern PP = ASCII.UpperV -- Preceding Page pattern CTC = ASCII.UpperW -- Cursor Tabulation Control pattern ECH = ASCII.UpperX -- Erase CHaracter pattern CVT = ASCII.UpperY -- Cursor Vertical Tabulation pattern CBT = ASCII.UpperZ -- Cursor Backward Tabulation pattern SRS = ASCII.LeftSqBra -- Start Reversed String pattern PTX = ASCII.BackSlash -- Parallel TeXts pattern SDS = ASCII.RightSqBra -- Start Directed String pattern SIMD = ASCII.Circumflex -- Select Implicit Movmement Direction -- -- ASCII.UnderScore not used -- * Column number 06 pattern HPA = ASCII.BackTick -- Horizontal Position Absolute pattern HPR = ASCII.LowerA -- Horizontal Position Relative pattern REP = ASCII.LowerB -- REPeat pattern DA = ASCII.LowerC -- Device Attributes pattern VPA = ASCII.LowerD -- Vertical Position Absolute pattern VPR = ASCII.LowerE -- Vertical Position Relative pattern HVP = ASCII.LowerF -- Horizontal and Vertical Position pattern TBC = ASCII.LowerG -- TaBulation Clear pattern SM = ASCII.LowerH -- Set Mode pattern MC = ASCII.LowerI -- Media Copy pattern HPB = ASCII.LowerJ -- Horizontal Position Backward pattern VPB = ASCII.LowerK -- Vertical Position Backward pattern RM = ASCII.LowerL -- Reset Mode pattern SGR = ASCII.LowerM -- Select Graphic Rendition pattern DSR = ASCII.LowerN -- Device Status Report pattern DAQ = ASCII.LowerO -- Define Area Qualification -- * Column number 07 --pattern SCP = ASCII.LowerS -- Save Cursor Position --pattern RCP = ASCII.LowerU -- Restore Cursor Position -- * EL and ED parameter values pattern CursorToEnd = 0 pattern BeginningToCursor = 1 pattern AllCharacters = 2 -- * SM (Set Mode) parameter values pattern GATM = 1 -- Guarded Area Transfer Mode pattern KAM = 2 -- Keyboard Action Mode pattern CRM = 3 -- Control Representation Mode pattern IRM = 4 -- Insertion Replacement Mode pattern SRTM = 5 -- Status Report Transfer Mode pattern ERM = 6 -- ERasure Mode pattern VEM = 7 -- Vertical Editing Mode pattern BDSM = 8 -- Bi-Directional Support Mode pattern DCSM = 9 -- Device Component Select Mode pattern HEM = 10 -- Horizontal Editing Mode pattern PUM = 11 -- Positioning Unit Mode pattern SRM = 12 -- Send/Receive mode pattern FEAM = 13 -- Format Effector Action Mode pattern FETM = 14 -- Format Effector Transfer Mode pattern MATM = 15 -- Multiple Area Transfer Mode pattern TTM = 16 -- Transfer Termination Mode pattern SATM = 17 -- Selected Area Transfer Mode pattern TSM = 18 -- Tabulation Stop Mode pattern GRCM = 21 -- Grpahic Rendition CoMbination pattern ZDM = 22 -- Zero Default Mode
Zigazou/HaMinitel
src/Minitel/Constants/ANSI.hs
gpl-3.0
4,325
0
6
1,057
747
416
331
73
0
module Peer.Get.Packet (messageConduit) where import HTorrentPrelude import Peer.Get.Exception import Peer.Message import Peer.Message.Get import qualified Data.ByteString.Lazy as LBS import Data.Conduit.Serialization.Binary import qualified Data.Conduit.List as CL import Control.Monad.Exception.Synchronous messageConduit :: Conduit ByteString (ExceptT PeerGetE IO) PeerMessage messageConduit = packetConduit =$= CL.mapM (ExceptionalT . return . parsePacket) packetConduit :: Conduit ByteString (ExceptT PeerGetE IO) LBS.ByteString packetConduit = hoist (mapExceptT IncompletePacket . except) (conduitGet getPacket) parsePacket :: LBS.ByteString -> Exceptional PeerGetE PeerMessage parsePacket bs = mapException InvalidMessage (runGetExcept getMessage bs)
ian-mi/hTorrent
Peer/Get/Packet.hs
gpl-3.0
763
0
9
81
194
110
84
15
1
import Import import System.IO import System.Environment import System.Console.GetOpt import System.Directory import System.Exit import Control.Concurrent.MVar import qualified Data.Map as Map import Language.Octopus import Language.Octopus.Data import Language.Octopus.Parser import Language.Octopus.Libraries import Language.Octopus.Primitive (resolveSymbol) import Data.Version import Paths_octopus main :: IO () main = do (opts, filepath) <- getOptions filepath' <- canonicalizePath filepath cache <- newMVar Map.empty lib <- getDataFileName "lib/" parse_e <- parseOctopusFile filepath <$> readFile filepath let startConfig = MConfig { libdir = lib, importsCache = cache, thisFile = Just filepath' } case parse_e of Left err -> print err Right (_, val) -> do fileEnv <- eval startConfig initialEnv val case resolveSymbol (intern "main") fileEnv of Nothing -> return () Just main -> print =<< eval startConfig fileEnv main exitSuccess data Options = Options { } deriving (Show) startOptions = Options { } getOptions :: IO (Options, FilePath) getOptions = do (actions, args, errors) <- getOpt Permute options <$> getArgs if errors == [] then do opts <- foldl (>>=) (return startOptions) actions case args of [] -> putErrLn "No file supplied." >> exitFailure [file] -> return (opts, file) _ -> putErrLn "Too many files supplied." >> exitFailure else mapM putErrLn errors >> exitFailure options :: [OptDescr (Options -> IO Options)] options = [ Option "V" ["version"] (NoArg (\_ -> do putErrLn $ "Octi " ++ showVersion version exitSuccess)) "Print version" , Option "h" ["help"] (NoArg (\_ -> do prg <- getProgName putErrLn "Octopus interpreter." putErrLn "This program is lisenced under the GPLv3." putErrLn (usageInfo (prg ++ " [options] file") options) putErrLn "Interpret the given file of Octopus code." exitSuccess)) "Show help" , Option "" ["print-libdir"] (NoArg (\_ -> do putErrLn =<< getDataFileName "" exitSuccess)) "Print directory where the system's Octopus library files are searched." ] putErrLn = hPutStrLn stderr
Zankoku-Okuno/octopus
main.hs
gpl-3.0
2,527
1
17
786
667
341
326
70
4
import System.IO import System.FilePath import Data.List import Data.List.Split days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"] nums = ["a", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"] song :: [String] -> [String] song [] = [] song cnts = (verse (length cnts) cnts) ++ (phrase (length cnts)) ++ (song ( tail cnts)) verse :: Int -> [String] -> [String] verse day items = reverse $ allItems (day-1) items phrase :: Int -> [String] phrase day = ["\nOn the " ++ days!!(day-1) ++ " day of Christmas\nmy true love sent to me:"] allItems :: Int -> [String] -> [String] allItems _ [] = [] allItems day (item:items) = (combo day item):(allItems (day-1) items) combo :: Int -> String -> String combo 0 item = "and " ++ nums!!0 ++ " " ++ item combo day item = nums!!day ++ " " ++ item h_print :: Int -> String -> IO () h_print 0 a = putStrLn $ take (length a) (drop 1 a) h_print 1 a = putStrLn $ take (length a ) (drop 4 a) h_print _ b = putStrLn b main :: IO [()] main = do contents <- readFile "..\\twelve_input_1.txt" let lyrics = zip [0,1..] $ reverse . song . reverse $ lines contents do mapM (uncurry $ h_print) lyrics
jandersen7/Daily
src/296e/hs/twelve.hs
gpl-3.0
1,342
0
15
323
590
315
275
33
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.DataTransfer.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.DataTransfer.Types.Product where import Network.Google.DataTransfer.Types.Sum import Network.Google.Prelude -- | Applications resources represent applications installed on the domain -- that support transferring ownership of user data. -- -- /See:/ 'application' smart constructor. data Application = Application' { _aTransferParams :: !(Maybe [ApplicationTransferParam]) , _aEtag :: !(Maybe Text) , _aKind :: !Text , _aName :: !(Maybe Text) , _aId :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Application' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aTransferParams' -- -- * 'aEtag' -- -- * 'aKind' -- -- * 'aName' -- -- * 'aId' application :: Application application = Application' { _aTransferParams = Nothing , _aEtag = Nothing , _aKind = "admin#datatransfer#ApplicationResource" , _aName = Nothing , _aId = Nothing } -- | The list of all possible transfer parameters for this application. These -- parameters can be used to select the data of the user in this -- application to be transferred. aTransferParams :: Lens' Application [ApplicationTransferParam] aTransferParams = lens _aTransferParams (\ s a -> s{_aTransferParams = a}) . _Default . _Coerce -- | Etag of the resource. aEtag :: Lens' Application (Maybe Text) aEtag = lens _aEtag (\ s a -> s{_aEtag = a}) -- | Identifies the resource as a DataTransfer Application Resource. aKind :: Lens' Application Text aKind = lens _aKind (\ s a -> s{_aKind = a}) -- | The application\'s name. aName :: Lens' Application (Maybe Text) aName = lens _aName (\ s a -> s{_aName = a}) -- | The application\'s ID. aId :: Lens' Application (Maybe Int64) aId = lens _aId (\ s a -> s{_aId = a}) . mapping _Coerce instance FromJSON Application where parseJSON = withObject "Application" (\ o -> Application' <$> (o .:? "transferParams" .!= mempty) <*> (o .:? "etag") <*> (o .:? "kind" .!= "admin#datatransfer#ApplicationResource") <*> (o .:? "name") <*> (o .:? "id")) instance ToJSON Application where toJSON Application'{..} = object (catMaybes [("transferParams" .=) <$> _aTransferParams, ("etag" .=) <$> _aEtag, Just ("kind" .= _aKind), ("name" .=) <$> _aName, ("id" .=) <$> _aId]) -- | Template for application transfer parameters. -- -- /See:/ 'applicationTransferParam' smart constructor. data ApplicationTransferParam = ApplicationTransferParam' { _atpValue :: !(Maybe [Text]) , _atpKey :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationTransferParam' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'atpValue' -- -- * 'atpKey' applicationTransferParam :: ApplicationTransferParam applicationTransferParam = ApplicationTransferParam' {_atpValue = Nothing, _atpKey = Nothing} -- | The value of the corresponding transfer parameter. eg: \'PRIVATE\' or -- \'SHARED\' atpValue :: Lens' ApplicationTransferParam [Text] atpValue = lens _atpValue (\ s a -> s{_atpValue = a}) . _Default . _Coerce -- | The type of the transfer parameter. eg: \'PRIVACY_LEVEL\' atpKey :: Lens' ApplicationTransferParam (Maybe Text) atpKey = lens _atpKey (\ s a -> s{_atpKey = a}) instance FromJSON ApplicationTransferParam where parseJSON = withObject "ApplicationTransferParam" (\ o -> ApplicationTransferParam' <$> (o .:? "value" .!= mempty) <*> (o .:? "key")) instance ToJSON ApplicationTransferParam where toJSON ApplicationTransferParam'{..} = object (catMaybes [("value" .=) <$> _atpValue, ("key" .=) <$> _atpKey]) -- | Template for a collection of Applications. -- -- /See:/ 'applicationsListResponse' smart constructor. data ApplicationsListResponse = ApplicationsListResponse' { _alrEtag :: !(Maybe Text) , _alrNextPageToken :: !(Maybe Text) , _alrKind :: !Text , _alrApplications :: !(Maybe [Application]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alrEtag' -- -- * 'alrNextPageToken' -- -- * 'alrKind' -- -- * 'alrApplications' applicationsListResponse :: ApplicationsListResponse applicationsListResponse = ApplicationsListResponse' { _alrEtag = Nothing , _alrNextPageToken = Nothing , _alrKind = "admin#datatransfer#applicationsList" , _alrApplications = Nothing } -- | ETag of the resource. alrEtag :: Lens' ApplicationsListResponse (Maybe Text) alrEtag = lens _alrEtag (\ s a -> s{_alrEtag = a}) -- | Continuation token which will be used to specify next page in list API. alrNextPageToken :: Lens' ApplicationsListResponse (Maybe Text) alrNextPageToken = lens _alrNextPageToken (\ s a -> s{_alrNextPageToken = a}) -- | Identifies the resource as a collection of Applications. alrKind :: Lens' ApplicationsListResponse Text alrKind = lens _alrKind (\ s a -> s{_alrKind = a}) -- | List of applications that support data transfer and are also installed -- for the customer. alrApplications :: Lens' ApplicationsListResponse [Application] alrApplications = lens _alrApplications (\ s a -> s{_alrApplications = a}) . _Default . _Coerce instance FromJSON ApplicationsListResponse where parseJSON = withObject "ApplicationsListResponse" (\ o -> ApplicationsListResponse' <$> (o .:? "etag") <*> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "admin#datatransfer#applicationsList") <*> (o .:? "applications" .!= mempty)) instance ToJSON ApplicationsListResponse where toJSON ApplicationsListResponse'{..} = object (catMaybes [("etag" .=) <$> _alrEtag, ("nextPageToken" .=) <$> _alrNextPageToken, Just ("kind" .= _alrKind), ("applications" .=) <$> _alrApplications]) -- | A Transfer resource represents the transfer of the ownership of user -- data between users. -- -- /See:/ 'dataTransfer' smart constructor. data DataTransfer = DataTransfer' { _dtEtag :: !(Maybe Text) , _dtOldOwnerUserId :: !(Maybe Text) , _dtKind :: !Text , _dtNewOwnerUserId :: !(Maybe Text) , _dtRequestTime :: !(Maybe DateTime') , _dtApplicationDataTransfers :: !(Maybe [ApplicationDataTransfer]) , _dtId :: !(Maybe Text) , _dtOverallTransferStatusCode :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DataTransfer' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dtEtag' -- -- * 'dtOldOwnerUserId' -- -- * 'dtKind' -- -- * 'dtNewOwnerUserId' -- -- * 'dtRequestTime' -- -- * 'dtApplicationDataTransfers' -- -- * 'dtId' -- -- * 'dtOverallTransferStatusCode' dataTransfer :: DataTransfer dataTransfer = DataTransfer' { _dtEtag = Nothing , _dtOldOwnerUserId = Nothing , _dtKind = "admin#datatransfer#DataTransfer" , _dtNewOwnerUserId = Nothing , _dtRequestTime = Nothing , _dtApplicationDataTransfers = Nothing , _dtId = Nothing , _dtOverallTransferStatusCode = Nothing } -- | ETag of the resource. dtEtag :: Lens' DataTransfer (Maybe Text) dtEtag = lens _dtEtag (\ s a -> s{_dtEtag = a}) -- | ID of the user whose data is being transferred. dtOldOwnerUserId :: Lens' DataTransfer (Maybe Text) dtOldOwnerUserId = lens _dtOldOwnerUserId (\ s a -> s{_dtOldOwnerUserId = a}) -- | Identifies the resource as a DataTransfer request. dtKind :: Lens' DataTransfer Text dtKind = lens _dtKind (\ s a -> s{_dtKind = a}) -- | ID of the user to whom the data is being transferred. dtNewOwnerUserId :: Lens' DataTransfer (Maybe Text) dtNewOwnerUserId = lens _dtNewOwnerUserId (\ s a -> s{_dtNewOwnerUserId = a}) -- | The time at which the data transfer was requested (Read-only). dtRequestTime :: Lens' DataTransfer (Maybe UTCTime) dtRequestTime = lens _dtRequestTime (\ s a -> s{_dtRequestTime = a}) . mapping _DateTime -- | List of per application data transfer resources. It contains data -- transfer details of the applications associated with this transfer -- resource. Note that this list is also used to specify the applications -- for which data transfer has to be done at the time of the transfer -- resource creation. dtApplicationDataTransfers :: Lens' DataTransfer [ApplicationDataTransfer] dtApplicationDataTransfers = lens _dtApplicationDataTransfers (\ s a -> s{_dtApplicationDataTransfers = a}) . _Default . _Coerce -- | The transfer\'s ID (Read-only). dtId :: Lens' DataTransfer (Maybe Text) dtId = lens _dtId (\ s a -> s{_dtId = a}) -- | Overall transfer status (Read-only). dtOverallTransferStatusCode :: Lens' DataTransfer (Maybe Text) dtOverallTransferStatusCode = lens _dtOverallTransferStatusCode (\ s a -> s{_dtOverallTransferStatusCode = a}) instance FromJSON DataTransfer where parseJSON = withObject "DataTransfer" (\ o -> DataTransfer' <$> (o .:? "etag") <*> (o .:? "oldOwnerUserId") <*> (o .:? "kind" .!= "admin#datatransfer#DataTransfer") <*> (o .:? "newOwnerUserId") <*> (o .:? "requestTime") <*> (o .:? "applicationDataTransfers" .!= mempty) <*> (o .:? "id") <*> (o .:? "overallTransferStatusCode")) instance ToJSON DataTransfer where toJSON DataTransfer'{..} = object (catMaybes [("etag" .=) <$> _dtEtag, ("oldOwnerUserId" .=) <$> _dtOldOwnerUserId, Just ("kind" .= _dtKind), ("newOwnerUserId" .=) <$> _dtNewOwnerUserId, ("requestTime" .=) <$> _dtRequestTime, ("applicationDataTransfers" .=) <$> _dtApplicationDataTransfers, ("id" .=) <$> _dtId, ("overallTransferStatusCode" .=) <$> _dtOverallTransferStatusCode]) -- | Template for a collection of DataTransfer resources. -- -- /See:/ 'dataTransfersListResponse' smart constructor. data DataTransfersListResponse = DataTransfersListResponse' { _dtlrEtag :: !(Maybe Text) , _dtlrNextPageToken :: !(Maybe Text) , _dtlrKind :: !Text , _dtlrDataTransfers :: !(Maybe [DataTransfer]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DataTransfersListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dtlrEtag' -- -- * 'dtlrNextPageToken' -- -- * 'dtlrKind' -- -- * 'dtlrDataTransfers' dataTransfersListResponse :: DataTransfersListResponse dataTransfersListResponse = DataTransfersListResponse' { _dtlrEtag = Nothing , _dtlrNextPageToken = Nothing , _dtlrKind = "admin#datatransfer#dataTransfersList" , _dtlrDataTransfers = Nothing } -- | ETag of the resource. dtlrEtag :: Lens' DataTransfersListResponse (Maybe Text) dtlrEtag = lens _dtlrEtag (\ s a -> s{_dtlrEtag = a}) -- | Continuation token which will be used to specify next page in list API. dtlrNextPageToken :: Lens' DataTransfersListResponse (Maybe Text) dtlrNextPageToken = lens _dtlrNextPageToken (\ s a -> s{_dtlrNextPageToken = a}) -- | Identifies the resource as a collection of data transfer requests. dtlrKind :: Lens' DataTransfersListResponse Text dtlrKind = lens _dtlrKind (\ s a -> s{_dtlrKind = a}) -- | List of data transfer requests. dtlrDataTransfers :: Lens' DataTransfersListResponse [DataTransfer] dtlrDataTransfers = lens _dtlrDataTransfers (\ s a -> s{_dtlrDataTransfers = a}) . _Default . _Coerce instance FromJSON DataTransfersListResponse where parseJSON = withObject "DataTransfersListResponse" (\ o -> DataTransfersListResponse' <$> (o .:? "etag") <*> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "admin#datatransfer#dataTransfersList") <*> (o .:? "dataTransfers" .!= mempty)) instance ToJSON DataTransfersListResponse where toJSON DataTransfersListResponse'{..} = object (catMaybes [("etag" .=) <$> _dtlrEtag, ("nextPageToken" .=) <$> _dtlrNextPageToken, Just ("kind" .= _dtlrKind), ("dataTransfers" .=) <$> _dtlrDataTransfers]) -- | Template to map fields of ApplicationDataTransfer resource. -- -- /See:/ 'applicationDataTransfer' smart constructor. data ApplicationDataTransfer = ApplicationDataTransfer' { _adtApplicationTransferParams :: !(Maybe [ApplicationTransferParam]) , _adtApplicationId :: !(Maybe (Textual Int64)) , _adtApplicationTransferStatus :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationDataTransfer' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adtApplicationTransferParams' -- -- * 'adtApplicationId' -- -- * 'adtApplicationTransferStatus' applicationDataTransfer :: ApplicationDataTransfer applicationDataTransfer = ApplicationDataTransfer' { _adtApplicationTransferParams = Nothing , _adtApplicationId = Nothing , _adtApplicationTransferStatus = Nothing } -- | The transfer parameters for the application. These parameters are used -- to select the data which will get transferred in context of this -- application. adtApplicationTransferParams :: Lens' ApplicationDataTransfer [ApplicationTransferParam] adtApplicationTransferParams = lens _adtApplicationTransferParams (\ s a -> s{_adtApplicationTransferParams = a}) . _Default . _Coerce -- | The application\'s ID. adtApplicationId :: Lens' ApplicationDataTransfer (Maybe Int64) adtApplicationId = lens _adtApplicationId (\ s a -> s{_adtApplicationId = a}) . mapping _Coerce -- | Current status of transfer for this application. (Read-only) adtApplicationTransferStatus :: Lens' ApplicationDataTransfer (Maybe Text) adtApplicationTransferStatus = lens _adtApplicationTransferStatus (\ s a -> s{_adtApplicationTransferStatus = a}) instance FromJSON ApplicationDataTransfer where parseJSON = withObject "ApplicationDataTransfer" (\ o -> ApplicationDataTransfer' <$> (o .:? "applicationTransferParams" .!= mempty) <*> (o .:? "applicationId") <*> (o .:? "applicationTransferStatus")) instance ToJSON ApplicationDataTransfer where toJSON ApplicationDataTransfer'{..} = object (catMaybes [("applicationTransferParams" .=) <$> _adtApplicationTransferParams, ("applicationId" .=) <$> _adtApplicationId, ("applicationTransferStatus" .=) <$> _adtApplicationTransferStatus])
brendanhay/gogol
gogol-admin-datatransfer/gen/Network/Google/DataTransfer/Types/Product.hs
mpl-2.0
16,508
0
18
4,049
3,061
1,765
1,296
355
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionHealthCheckServices.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes the specified regional HealthCheckService. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionHealthCheckServices.delete@. module Network.Google.Resource.Compute.RegionHealthCheckServices.Delete ( -- * REST Resource RegionHealthCheckServicesDeleteResource -- * Creating a Request , regionHealthCheckServicesDelete , RegionHealthCheckServicesDelete -- * Request Lenses , rhcsdRequestId , rhcsdHealthCheckService , rhcsdProject , rhcsdRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionHealthCheckServices.delete@ method which the -- 'RegionHealthCheckServicesDelete' request conforms to. type RegionHealthCheckServicesDeleteResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "healthCheckServices" :> Capture "healthCheckService" Text :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes the specified regional HealthCheckService. -- -- /See:/ 'regionHealthCheckServicesDelete' smart constructor. data RegionHealthCheckServicesDelete = RegionHealthCheckServicesDelete' { _rhcsdRequestId :: !(Maybe Text) , _rhcsdHealthCheckService :: !Text , _rhcsdProject :: !Text , _rhcsdRegion :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionHealthCheckServicesDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rhcsdRequestId' -- -- * 'rhcsdHealthCheckService' -- -- * 'rhcsdProject' -- -- * 'rhcsdRegion' regionHealthCheckServicesDelete :: Text -- ^ 'rhcsdHealthCheckService' -> Text -- ^ 'rhcsdProject' -> Text -- ^ 'rhcsdRegion' -> RegionHealthCheckServicesDelete regionHealthCheckServicesDelete pRhcsdHealthCheckService_ pRhcsdProject_ pRhcsdRegion_ = RegionHealthCheckServicesDelete' { _rhcsdRequestId = Nothing , _rhcsdHealthCheckService = pRhcsdHealthCheckService_ , _rhcsdProject = pRhcsdProject_ , _rhcsdRegion = pRhcsdRegion_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). rhcsdRequestId :: Lens' RegionHealthCheckServicesDelete (Maybe Text) rhcsdRequestId = lens _rhcsdRequestId (\ s a -> s{_rhcsdRequestId = a}) -- | Name of the HealthCheckService to delete. The name must be 1-63 -- characters long, and comply with RFC1035. rhcsdHealthCheckService :: Lens' RegionHealthCheckServicesDelete Text rhcsdHealthCheckService = lens _rhcsdHealthCheckService (\ s a -> s{_rhcsdHealthCheckService = a}) -- | Project ID for this request. rhcsdProject :: Lens' RegionHealthCheckServicesDelete Text rhcsdProject = lens _rhcsdProject (\ s a -> s{_rhcsdProject = a}) -- | Name of the region scoping this request. rhcsdRegion :: Lens' RegionHealthCheckServicesDelete Text rhcsdRegion = lens _rhcsdRegion (\ s a -> s{_rhcsdRegion = a}) instance GoogleRequest RegionHealthCheckServicesDelete where type Rs RegionHealthCheckServicesDelete = Operation type Scopes RegionHealthCheckServicesDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient RegionHealthCheckServicesDelete'{..} = go _rhcsdProject _rhcsdRegion _rhcsdHealthCheckService _rhcsdRequestId (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy RegionHealthCheckServicesDeleteResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionHealthCheckServices/Delete.hs
mpl-2.0
5,362
0
17
1,147
553
331
222
91
1
{-# OPTIONS -fglasgow-exts -fffi #-} module PluginEvalAux where import System.Plugins.Make import System.Plugins.Load import System.Plugins.Utils import Foreign.C import Control.Exception ( evaluate ) import System.IO import System.Directory ( renameFile, removeFile ) symbol = "resource" evalWithStringResult :: FilePath -> String -> IO String evalWithStringResult srcFile s = do status <- make srcFile ["-O0"] case status of MakeFailure err -> putStrLn "error occured" >> return (show err) MakeSuccess _ obj -> load' obj where load' obj = do loadResult <- load obj [] [] symbol case loadResult of LoadFailure errs -> putStrLn "load error" >> return (show errs) LoadSuccess m (rsrc :: String -> IO String) -> do v' <- rsrc s unload m mapM_ removeFile [ obj, replaceSuffix obj ".hi" ] return v' foreign export ccall evalhaskell_CString :: CString -> CString -> IO CString evalhaskell_CString :: CString -> CString -> IO CString evalhaskell_CString filePathCS sCS = do s <- peekCString sCS filePath <- peekCString filePathCS retval <- evalWithStringResult filePath s newCString retval -- vi:sw=2 sts=2
stepcut/plugins
testsuite/objc/expression_parser/PluginEvalAux.hs
lgpl-2.1
1,190
1
17
251
364
176
188
-1
-1
module Main where import Prelude as P import System.Console.GetOpt import System.Environment import System.FilePath.Posix import Control.Monad.IO.Class import Control.Applicative import qualified Data.ByteString as BS import Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import Data.Conduit import Utils data Conversion = BinaryToHex | HexToBinary deriving (Eq) data Config = Config { outFile :: String , conversion :: Conversion} defaultConfig = Config "output" HexToBinary options :: [OptDescr (Config -> Config)] options = [ Option ['b'] ["binary"] (NoArg (\ option -> option {conversion = BinaryToHex})) "convert binary to hex", Option ['o'] ["output"] (ReqArg (\ arg option -> option {outFile = arg}) "FILE") "output file name" ] hexBinConduit = CL.map (hex2bs . map word2char . BS.unpack) binHexConduit = CL.map (BS.pack . map char2word . bs2hex) chunksOf n = CL.sequence (CB.take n) printLength = do maybeBytes <- await case maybeBytes of Just bs -> do liftIO $ putStrLn $ "received bytes of length " ++ (show $ BS.length bs) yield bs Nothing -> return () run (Config outFile conv) inFile = runResourceT $ sourceFile inFile =$= printLength =$= converter $$ sinkFile outFile where converter = case conv of HexToBinary -> hexBinConduit BinaryToHex -> binHexConduit main = do args <- getArgs case getOpt Permute options args of --Arguments correctly parsed (opts, inFile:[], []) -> do --Make changes to default configuration let config = runEach opts defaultConfig --run program run config inFile --Arguments not valid (_, nonOpts, []) -> error $ "Unrecognized arguments: " ++ unwords nonOpts --Other errors (_, _, msgs) -> error $ concat msgs ++ usageInfo "" options
nsmryan/BIC
hexBin.hs
unlicense
1,923
0
16
482
569
309
260
51
3
squaresList n = [i ^ 2 | i <- [1..n]] pairsList x y = [(a, b) | a <- [1..x], b <- [10..y]] -- nested two loop concat xss = [x | xs <- xss, x <- xs] -- loop with guard evens n = [x | x <- [1..n], even x] factors n = [x | x <- [1..n], n `mod` x == 0] prime n = factors n == [1, n] primes n = [x | x <- [1..n], prime x] pairs a b = [(x, y) | x <- a, y <- b] pairsOfAdj xs = zip xs (tail xs) qsort :: Ord a => [a] -> [a] qsort [] = [] qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger where smaller = [a | a <- xs, a <= x] larger = [b | b <- xs, b > x] isSorted :: Ord a => [a] -> Bool isSorted xs = and [x <= y | (x, y) <- pairsOfAdj xs] positions :: Eq a => a -> [a] -> [Int] positions x xs = [i | (i, n) <- zip [1..n] xs, n == x] where n = length xs --lowers xs = length [x | x <- xs, isLower x] pyths n = [(x, y, z) | x <- [1..n], y <- [1..n], z <- [1..n], x ^ 2 + y ^ 2 == z ^ 2] -- no is perfect if sum of its factor = number itself perfects n = [x | x <- [1..n], isPerfect x] where isPerfect a = sum (init(factors a)) == a divides :: Int -> Int -> Bool divides n a = n `mod` a == 0 divisors :: Int -> [Int] divisors n = [x | x <- [1..n], divides n x] riffle a b = Main.concat [[x, y] | (x, y) <- zip a b]
dongarerahul/edx-haskell
chapter4.hs
apache-2.0
1,242
0
12
344
795
422
373
27
1
ans :: [Int] -> [String] ans (x:y:xs) = replicate x $ replicate y '#' printRec :: [[String]] -> IO() printRec [] = return () printRec (s:sx) = do mapM_ putStrLn s putStrLn "" printRec sx main = do c <- getContents let t = map (map read) $ map words $ lines c :: [[Int]] i = takeWhile (/= [0,0]) t o = map ans i printRec o
a143753/AOJ
ITP1_5_A.hs
apache-2.0
352
0
14
98
206
102
104
15
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {- BoardTest.hs Copyright (c) 2014 by Sebastien Soudan. Apache License Version 2.0, January 2004 -} module BoardTest where import Board import Data.Maybe (isNothing) import Test.QuickCheck (Arbitrary (..)) import Test.QuickCheck.Gen (choose, elements) prop_evalBoard :: Bool prop_evalBoard = evalBoard initialBoard == 0 prop_elementAt :: Bool prop_elementAt = elementAt (Pos (0,0)) initialBoard == Just (Piece Rook Black) prop_elementAt2 :: Bool prop_elementAt2 = isNothing $ elementAt (Pos (4,4)) initialBoard prop_elementAt3 :: Bool prop_elementAt3 = elementAt (Pos (7,7)) initialBoard == Just (Piece Rook White) instance Arbitrary PieceType where arbitrary = elements [Pawn, Rook, Queen, King, Bishop, Knight] instance Arbitrary PieceColor where arbitrary = elements [Black, White] instance Arbitrary Pos where arbitrary = do x <- choose (0,7) y <- choose (0,7) return $ Pos (x, y) prop_valuePiece :: PieceType -> Bool prop_valuePiece ptype = valuePiece (Piece ptype Black) == valuePiece (Piece ptype White) prop_deleteSquare :: Pos -> Bool prop_deleteSquare pos = isNothing $ elementAt pos updatedBoard where updatedBoard = deleteSquare pos initialBoard prop_movePieceOnBoard :: Pos -> Pos -> Bool prop_movePieceOnBoard origin destination = let originalBoard = initialBoard movedBoard = movePieceOnBoard originalBoard origin destination in elementAt destination movedBoard == elementAt origin originalBoard && (isNothing (elementAt origin movedBoard) || origin == destination)
ssoudan/hsChess
test/BoardTest.hs
apache-2.0
1,746
0
13
426
463
246
217
32
1
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- {-# OPTIONS_GHC -fno-warn-unused-matches -fno-warn-incomplete-patterns #-} {-# LANGUAGE CPP, OverloadedStrings #-} module Server where import Control.Exception import Data.HashMap.Strict as Map import Network.Socket import System.IO import Thrift import Thrift.Server import ThriftTest import ThriftTest_Iface import ThriftTest_Types data TestHandler = TestHandler instance ThriftTest_Iface TestHandler where testVoid a = return () testString a (Just s) = do print s; return s testByte a (Just x) = do print x; return x testI32 a (Just x) = do print x; return x testI64 a (Just x) = do print x; return x testDouble a (Just x) = do print x; return x testFloat a (Just x) = do print x; return x testStruct a (Just x) = do print x; return x testNest a (Just x) = do print x; return x testMap a (Just x) = do print x; return x testSet a (Just x) = do print x; return x testList a (Just x) = do print x; return x testEnum a (Just x) = do print x; return x testTypedef a (Just x) = do print x; return x testMapMap a (Just x) = return (Map.fromList [(1,Map.fromList [(2,2)])]) testInsanity a (Just x) = return (Map.fromList [(1,Map.fromList [(ONE,x)])]) testMulti a a1 a2 a3 a4 a5 a6 = return (Xtruct Nothing Nothing Nothing Nothing) testException a c = throw (Xception (Just 1) (Just "bya")) testMultiException a c1 c2 = throw (Xception (Just 1) (Just "bya")) testOneway a (Just i) = print i main :: IO () main = catch (runThreadedServer (accepter p) TestHandler process 9090) (\(TransportExn s t) -> print s) where accepter p s = do (s', _) <- accept s h <- socketToHandle s' ReadWriteMode return (p h, p h)
facebook/fbthrift
thrift/test/hs/Server.hs
apache-2.0
2,531
0
13
534
806
401
405
41
1
-- | -- Module : Statistics.Matrix.Mutable -- Copyright : (c) 2014 Bryan O'Sullivan -- License : BSD3 -- -- Basic mutable matrix operations. module Statistics.Matrix.Mutable ( MMatrix(..) , MVector , replicate , thaw , bounds , unsafeFreeze , unsafeRead , unsafeWrite , unsafeModify , immutably , unsafeBounds ) where import Control.Applicative ((<$>)) import Control.DeepSeq (NFData(..)) import Control.Monad.ST (ST) import Statistics.Matrix.Types (Matrix(..), MMatrix(..), MVector) import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as M import Prelude hiding (replicate) replicate :: Int -> Int -> Double -> ST s (MMatrix s) replicate r c k = MMatrix r c 0 <$> M.replicate (r*c) k thaw :: Matrix -> ST s (MMatrix s) thaw (Matrix r c e v) = MMatrix r c e <$> U.thaw v unsafeFreeze :: MMatrix s -> ST s Matrix unsafeFreeze (MMatrix r c e mv) = Matrix r c e <$> U.unsafeFreeze mv unsafeRead :: MMatrix s -> Int -> Int -> ST s Double unsafeRead mat r c = unsafeBounds mat r c M.unsafeRead {-# INLINE unsafeRead #-} unsafeWrite :: MMatrix s -> Int -> Int -> Double -> ST s () unsafeWrite mat row col k = unsafeBounds mat row col $ \v i -> M.unsafeWrite v i k {-# INLINE unsafeWrite #-} unsafeModify :: MMatrix s -> Int -> Int -> (Double -> Double) -> ST s () unsafeModify mat row col f = unsafeBounds mat row col $ \v i -> do k <- M.unsafeRead v i M.unsafeWrite v i (f k) {-# INLINE unsafeModify #-} -- | Given row and column numbers, calculate the offset into the flat -- row-major vector. bounds :: MMatrix s -> Int -> Int -> (MVector s -> Int -> r) -> r bounds (MMatrix rs cs _ mv) r c k | r < 0 || r >= rs = error "row out of bounds" | c < 0 || c >= cs = error "column out of bounds" | otherwise = k mv $! r * cs + c {-# INLINE bounds #-} -- | Given row and column numbers, calculate the offset into the flat -- row-major vector, without checking. unsafeBounds :: MMatrix s -> Int -> Int -> (MVector s -> Int -> r) -> r unsafeBounds (MMatrix _ cs _ mv) r c k = k mv $! r * cs + c {-# INLINE unsafeBounds #-} immutably :: NFData a => MMatrix s -> (Matrix -> a) -> ST s a immutably mmat f = do k <- f <$> unsafeFreeze mmat rnf k `seq` return k {-# INLINE immutably #-}
fpco/statistics
Statistics/Matrix/Mutable.hs
bsd-2-clause
2,298
0
11
523
834
437
397
52
1
module Language.Ptlish.Simplify (simplify) where import Language.Ptlish.AST import Control.Monad.State import qualified Data.Map as Map import Data.Maybe type SimplifyM = State SimplifyState data SimplifyState = SimplifyState { stNextExprId :: Int, stExtra :: [(Name,Expr)], stExprMap :: Map.Map Expr Name, stScope :: Map.Map Name Expr } initState :: SimplifyState initState = SimplifyState 1 [] Map.empty Map.empty simplify :: Ptlish -> Ptlish simplify ptl = let (v, s) = runState (simplify' ptl) initState in [ (Def n e) | (n,e) <- reverse $ stExtra s ] ++ v simplify' :: [Stmt] -> SimplifyM [Stmt] simplify' = (fmap catMaybes) . mapM simplifyStmt notLambda :: Expr -> Bool notLambda (LambdaExpr _ _) = False notLambda _ = True simplifyStmt :: Stmt -> SimplifyM (Maybe Stmt) simplifyStmt (Def n e) = do e' <- simplifyExpr e s <- get put $ s { stScope = Map.insert n e (stScope s) } return $ if notLambda e' then Just $ (Def n e') else Nothing simplifyStmt (Trigger n as) = do as' <- mapM simplifyAction as return $ Just $ Trigger n as' simplifyAction :: Action -> SimplifyM Action simplifyAction (Action n exprs) = do exprs' <- mapM simplifyExpr exprs return $ Action n exprs' simplifyExpr :: Expr -> SimplifyM Expr simplifyExpr (UnExpr op e) = do e' <- simplifyExpr e matchExpr (UnExpr op e') simplifyExpr (BinExpr op e1 e2) = do e1' <- simplifyExpr e1 e2' <- simplifyExpr e2 matchExpr (BinExpr op e1' e2') simplifyExpr ce@(ConstExpr _) = do return ce simplifyExpr (IfExpr i t e) = do i' <- simplifyExpr i t' <- simplifyExpr t e' <- simplifyExpr e matchExpr (IfExpr i' t' e') simplifyExpr ve@(VarExpr v e) = do e' <- simplifyExpr e return $ VarExpr v e' simplifyExpr re@(RefExpr _) = do e <- normalize re simplifyExpr e simplifyExpr ue@(UnboundExpr _) = return ue simplifyExpr ae@(ApplyExpr _ _) = do ae' <- normalize ae simplifyExpr ae' simplifyExpr le@(LambdaExpr n e) = do e' <- normalize e matchExpr (LambdaExpr n e') matchExpr :: Expr -> SimplifyM Expr matchExpr e = do s <- get case Map.lookup e (stExprMap s) of Just n -> return $ RefExpr n Nothing -> if notLambda e then do let n = "_" ++ (show $ stNextExprId s) put $ s { stExprMap = Map.insert e n (stExprMap s), stScope = Map.insert n e (stScope s), stNextExprId = stNextExprId s + 1, stExtra = (n,e):stExtra s } return $ RefExpr n else return e normalize :: Expr -> SimplifyM Expr normalize (UnExpr op e) = do e' <- normalize e return $ UnExpr op e' normalize (BinExpr op e1 e2) = do e1' <- normalize e1 e2' <- normalize e2 return $ BinExpr op e1' e2' normalize (ConstExpr i) = return $ ConstExpr i normalize (IfExpr i t e) = do i' <- normalize i t' <- normalize t e' <- normalize e return $ IfExpr i' t' e' normalize (VarExpr n e) = do e' <- normalize e return $ VarExpr n e' normalize (RefExpr n) = do s <- get case Map.lookup n (stScope s) of Just e -> normalize e Nothing -> fail $ "Reference to undeclared identifier: " ++ n normalize u@(UnboundExpr n) = return u normalize (ApplyExpr e1 e2) = do e1' <- normalize e1 e2' <- normalize e2 apply e1' e2' normalize (LambdaExpr n e) = do e' <- normalize e return $ LambdaExpr n e' apply :: Expr -> Expr -> SimplifyM Expr apply (LambdaExpr n e1) e2 = bind n e2 e1 apply e _ = fail $ "Cannot apply:" ++ (show e) bind :: Name -> Expr -> Expr -> SimplifyM Expr bind n be (UnExpr op e) = do e' <- bind n be e return $ UnExpr op e' bind n be (BinExpr op e1 e2) = do e1' <- bind n be e1 e2' <- bind n be e2 return $ BinExpr op e1' e2' bind _ _ ce@(ConstExpr _) = return $ ce bind n be (IfExpr i t e) = do i' <- bind n be i t' <- bind n be t e' <- bind n be e return $ IfExpr i' t' e' bind n be (VarExpr vn e) = do e' <- bind n be e return $ VarExpr vn e' bind n be re@(RefExpr en) = return $ re bind n be ue@(UnboundExpr n') = return $ if n == n' then be else ue bind n be ae@(ApplyExpr _ _) = fail $ "Apply not allowed when binding: " ++ (show ae) bind n be le@(LambdaExpr n' e) = do e' <- bind n be e return $ if n == n' then le else LambdaExpr n' e'
tlaitinen/ptlish
Language/Ptlish/Simplify.hs
bsd-2-clause
4,544
0
19
1,359
1,945
937
1,008
135
3
{-# LANGUAGE OverloadedStrings #-} import System.Directory import System.Time import System.IO import qualified Data.List as L import Text.ParserCombinators.Parsec import Text.Blaze.Html5 as H import Text.Blaze.Html5.Attributes as A import Text.Blaze.Html.Renderer.Pretty import qualified Text.Blaze.Internal as I import Text.Pandoc import Text.Pandoc.Readers.Markdown import Control.Monad data Entry = Entry { entryUrl :: String, entryDate :: CalendarTime, entryTitle :: String, entryTags :: String, entryBody :: String} deriving (Eq, Show) instance Ord Entry where compare e1 e2 = compare (entryDate e1) (entryDate e2) metadata :: String -> Parser String metadata s = do string ("<!--- " ++ s ++ ": ") manyTill anyChar (try (string " -->")) entryParser :: Parser [String] entryParser = do u <- metadata "url" spaces d <- metadata "date" spaces ti <- metadata "title" spaces ta <- metadata "tags" spaces b <- manyTill anyChar eof return [u, d, ti, ta, b] dateParser :: Parser CalendarTime dateParser = do d <- manyTill digit (char '/') m <- manyTill digit (char '/') y <- many digit let defaultDate = CalendarTime 2012 January 1 0 0 0 0 Sunday 0 "GMT" 0 False let dt = defaultDate {ctYear = 2000 + read y , ctMonth = toEnum (read m - 1) , ctDay = read d} return $ toUTCTime $ toClockTime dt date :: String -> CalendarTime date s = case parse dateParser "Error parsing date string" s of Left e -> error $ show e Right d -> d ymd :: CalendarTime -> String ymd cal = let yyyy = show $ ctYear cal m = show (1 + (fromEnum $ ctMonth cal)) d = show $ ctDay cal mm = if L.length m == 1 then '0' : m else m dd = if L.length d == 1 then '0' : d else d in yyyy ++ "-" ++ mm ++ "-" ++ dd rfc882 :: Entry -> String rfc882 e = let cal = entryDate e dow = (take 3 $ show $ ctWDay cal) ++ ", " day = (show $ ctDay cal) ++ " " mon = (take 3 $ show $ ctMonth cal) ++ " " year = (show $ ctYear cal) ++ " " in dow ++ day ++ mon ++ year ++ "20:00:00 GMT" expireDate :: Entry -> String expireDate e = let cal = entryDate e cty = ctYear cal d = cal {ctYear = cty + 1} in rfc882 $ e {entryDate = d} publishedOn :: Entry -> String publishedOn e = let cal = entryDate e month = (show $ ctMonth cal) ++ " " day = (show $ ctDay cal) ++ ", " year = show $ ctYear cal in month ++ day ++ year absoluteUrl :: Entry -> String absoluteUrl e = "http://www.adrienhaxaire.org/" ++ entryUrl e ++ ".html" entry :: String -> Entry entry s = case parse entryParser "Error in entry string" s of Left e -> error $ show e Right [u, d, ti, ta, b] -> Entry u (date d) ti ta (markdownToHtml b) markdownToHtml :: String -> String markdownToHtml s = let md = readMarkdown defaultParserState {stateStrict = True} s in writeHtmlString defaultWriterOptions md htmlHead :: String -> Markup htmlHead t = do H.head $ do meta ! httpEquiv "content-type" ! content "text/html; charset=UTF-8" meta ! name "google-site-verification" ! content "6vhHz6JpHz2tcB6ElSHx7ev3bzmZo-skd2iRRHiwCjw" meta ! name "keywords" ! content "adrien haxaire, adrienhaxaire, existence et applications" link ! type_ "text/css" ! rel "stylesheet" ! media "all" ! href "base.css" H.title $ toHtml ("Existence et Applications" ++ t) entryHead :: Entry -> Markup entryHead e = do H.head $ do meta ! httpEquiv "content-type" ! content "text/html; charset=UTF-8" meta ! httpEquiv "Last-Modified" ! content (toValue $ show $ rfc882 e) meta ! httpEquiv "expires" ! content (toValue $ show $ expireDate e) meta ! name "google-site-verification" ! content "6vhHz6JpHz2tcB6ElSHx7ev3bzmZo-skd2iRRHiwCjw" meta ! name "keywords" ! content "adrien haxaire, adrienhaxaire, existence et applications" meta ! name "keywords" ! content (toValue $ show $ entryTitle e) meta ! name "keywords" ! content (toValue $ show $ entryTags e) link ! type_ "text/css" ! rel "stylesheet" ! media "all" ! href "base.css" H.title $ toHtml ("Existence et Applications | " ++ entryTitle e) htmlBody :: Html -> Markup htmlBody contents = H.body $ do entete contents htmlFooter googleAnalytics entete :: Markup entete = do H.div ! A.id "entete" $ do h1 $ a ! href "/" $ "Existence et Applications" H.div ! A.id "nav" $ do a ! href "/" $ "home" a ! href "archive.html" $ "archive" a ! href "rss.xml" $ "rss" a ! href "about.html" $ "about" htmlTemplate :: String -> Html -> Html htmlTemplate pageTitle contents = docTypeHtml ! lang "en" $ do htmlHead pageTitle htmlBody contents entryTemplate :: Entry -> Html entryTemplate e = docTypeHtml ! lang "en" $ do entryHead e htmlBody $ entryContents e entryContents :: Entry -> Html entryContents e = do H.div ! A.id "contents" ! A.class_ "container" $ I.preEscapedString (entryBody e ++ "\n<p> " ++ publishedOn e ++ "</p>\n") comments e markdownEntries :: IO [String] markdownEntries = do es <- getDirectoryContents "entries/" return $ L.map (\x -> "entries/" ++ x) (filterMarkdown es) where filterMarkdown = L.delete "." . L.delete ".." . L.filter (L.isSuffixOf ".md") writeEntry :: Entry -> IO () writeEntry e = writeFile filename (renderHtml $ entryTemplate e) where filename = "public/" ++ entryUrl e ++ ".html" entries :: IO [Entry] entries = liftM (L.map entry) (markdownEntries >>= mapM readFile) updateEntries :: [Entry] -> IO () updateEntries = mapM_ writeEntry updateIndex :: [Entry] -> IO () updateIndex es = let filename = "public/index.html" contents = entryContents $ maximum es in writeFile filename (renderHtml $ htmlTemplate "" contents) updateArchive :: [Entry] -> IO () updateArchive es = let filename = "public/archive.html" contents = archiveContents es in writeFile filename (renderHtml $ htmlTemplate " | Archive" contents) archiveContents :: [Entry] -> Html archiveContents es = let ses = reverse $ L.sort es in do H.div ! A.id "contents" ! A.class_ "container" $ do p "Previous posts:" forM_ ses archiveLine archiveLine :: Entry -> Markup archiveLine e = do p $ do a ! href (toValue $ absoluteUrl e) $ toHtml (entryTitle e) toHtml (", " ++ (publishedOn e)) rss :: [Entry] -> String rss es = let ses = reverse $ L.sort es lastBuild = rfc882 $ maximum ses rssItems = foldl1 (++) $ L.map rssItem ses in "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n" ++ "<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n" ++ " <channel>" ++ " <title>Existence et Applications</title>\n" ++ " <link>http://www.adrienhaxaire.org</link>\n" ++ " <description>Adrien Haxaire's Existence et Applications blog</description>\n" ++ " <lastBuildDate>" ++ lastBuild ++ "</lastBuildDate>\n" ++ " <atom:link href=\"http://www.adrienhaxaire.org/rss.xml\" rel=\"self\" type=\"application/rss+xml\" />" ++ rssItems ++ " </channel>\n" ++ "</rss>" rssItem :: Entry -> String rssItem e = " <item>\n" ++ " <title>" ++ entryTitle e++ "</title>\n" ++ " <link>" ++ absoluteUrl e ++ "</link>\n" ++ " <guid>" ++ absoluteUrl e ++ "</guid>\n" ++ " <pubDate>" ++ rfc882 e ++ "</pubDate>\n" ++ " <description><![CDATA[" ++ entryBody e ++ "]]></description>\n" ++ " </item>\n" updateRSS :: [Entry] -> IO () updateRSS es = writeFile "public/rss.xml" $ rss es sitemap :: [Entry] -> String sitemap es = let lastmod = ymd $ entryDate $ maximum es sitemapUrls = foldl1 (++) $ L.map sitemapUrl es in "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ++ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" ++ "<url>\n <loc>http://www.adrienhaxaire.org</loc>\n" ++ " <lastmod>" ++ lastmod ++ "</lastmod>\n</url>\n" ++ "<url>\n <loc>http://www.adrienhaxaire.org/about.html</loc>\n" ++ " <lastmod>" ++ lastmod ++ "</lastmod>\n</url>\n" ++ "<url>\n <loc>http://www.adrienhaxaire.org/archive.html</loc>\n" ++ " <lastmod>" ++ lastmod ++ "</lastmod>\n</url>\n" ++ sitemapUrls ++ "</urlset>" sitemapUrl :: Entry -> String sitemapUrl e = "<url>\n" ++ " <loc>" ++ absoluteUrl e ++ "</loc>\n" ++ " <lastmod>" ++ (ymd $ entryDate e) ++ "</lastmod>\n" ++ " <changefreq>never</changefreq>" ++ "</url>\n" updateSitemap :: [Entry] -> IO () updateSitemap es = writeFile "public/sitemap.xml" $ sitemap es googleAnalytics :: Html googleAnalytics = script ! type_ "text/javascript" $ "var _gaq = _gaq || [];\n _gaq.push(['_setAccount', 'UA-13136595-1']);\n _gaq.push(['_trackPageview']);\n (function() {\n var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n })();" htmlFooter :: Html htmlFooter = H.div ! A.id "licence" $ I.preEscapedString "<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nd/3.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"http://i.creativecommons.org/l/by-nd/3.0/88x31.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" href=\"http://purl.org/dc/dcmitype/Text\" property=\"dct:title\" rel=\"dct:type\">Existence et Applications</span> by Adrien Haxaire</a> is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nd/3.0/\">Creative Commons Attribution-NoDerivs 3.0 Unported License</a>.<br />Find more on <a href=\"http://twitter.com/adrienhaxaire\">Twitter</a> and <a href=\"https://plus.google.com/109821515852278704885?rel=author\">Google</a>." comments :: Entry -> Html comments e = do H.div ! A.id "comments" ! A.class_ "container" $ do h2 "Comments" H.div ! A.id "disqus_thread" $ "" script ! type_ "text/javascript" $ disqus e noscript $ I.preEscapedString "Please enable JavaScript to view the <a href=\"http://disqus.com/?ref_noscript\">comments powered by Disqus.</a>" a ! href "http://disqus.com" ! A.class_ "dsq-brlink" $ I.preEscapedString "comments powered by <span class=\"logo-disqus\">Disqus</span>" disqus :: Entry -> Html disqus e = toHtml $ "var disqus_shortname = 'adrienhaxaire';\n" ++ " var disqus_identifier = '" ++ entryUrl e ++ "'\n" ++ " var disqus_url = '" ++ absoluteUrl e ++ "';\n" ++ " var disqus_title = '" ++ entryTitle e ++ "';\n" ++ " (function() {var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;" ++ " dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; " ++ " (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);})();" main :: IO () main = do es <- entries updateEntries es updateIndex es updateArchive es updateRSS es updateSitemap es
adrienhaxaire/adrienhaxaire.org
update.hs
bsd-3-clause
12,406
0
21
3,596
3,114
1,515
1,599
238
3
--------------------------------------------------------------------------- -- | -- module : Control.Monad.Trans.Cont -- Copyright : (c) Evgeniy Permyakov 2010 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable (haskell - 2010) -- Actually, this module is redundant, because Coroutines provides superset of this functional. -- However, it is simplier to use, so it is provided. module Control.Monad.Trans.Invoke where import Control.Monad.Trans.Class import Control.Monad.IO.Class newtype InvokeT p m a = InvokeT ( (p -> m () ) -> m a ) invokeT :: ( (p -> m () ) -> m a ) -> InvokeT p m a invokeT = InvokeT runInvokeT :: InvokeT p m a -> ( p -> m () ) -> m a runInvokeT (InvokeT a) f = a f instance Functor m => Functor (InvokeT p m) where fmap f m = invokeT $ \i -> fmap f (runInvokeT m i) instance Monad m => Monad (InvokeT p m) where return a = invokeT $ \_ -> return a m >>= k = invokeT $ \f -> runInvokeT m f >>= \x -> runInvokeT (k x) f invoke :: p -> InvokeT p m () invoke p = invokeT $ \f -> f p
permeakra/yamtl
Control/Monad/Trans/Invoke.hs
bsd-3-clause
1,150
0
12
245
344
183
161
15
1
-- | Bookstore Example -- example from Realworld Haskell Chapter 03 module Week02.BookStore where data BookInfo = Book Integer String [String] deriving (Show) data MagazineInfo = Magazine Integer String [String] deriving (Show) -- Type synonyms type CustomerID = Int type CardHolder = String type CardNumber = String type Address = [String] type ReviewBody = String data BookReview = BookReview BookInfo CustomerID String data BetterReview = BetterReview BookInfo CustomerID ReviewBody myInfo :: BookInfo myInfo = Book 9780135072455 "Algerbra of Programming" ["Richard Bird", "Oege de Moor"] type BookRecord = (BookInfo, BookReview) data BillingInfo = CreditCard CardNumber CardHolder Address | CashOnDelivery | Invoice CustomerID deriving (Show) bookID :: BookInfo -> Integer bookID (Book bid _ _) = bid bookTitle :: BookInfo -> String bookTitle (Book _ title _) = title bookAuthors :: BookInfo -> [String] bookAuthors (Book _ _ authors) = authors data Customer = Customer { customerID :: CustomerID , customerName :: String , customerAddress :: Address } deriving (Show) customer2 :: Customer customer2 = Customer { customerID = 271828 , customerAddress = ["1048576 Disk Drive", "Milpitas, CA 95134", "USA"] , customerName = "Jane Q. Citizen" }
emaphis/Haskell-Practice
cis194/src/Week02/BookStore.hs
bsd-3-clause
1,484
0
8
422
334
196
138
38
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Pattern-matching bindings (HsBinds and MonoBinds) Handles @HsBinds@; those at the top level require different handling, in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at lower levels it is preserved with @let@/@letrec@s). -} {-# LANGUAGE CPP #-} module Language.Haskell.Liquid.Desugar710.DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, dsSpec, dsHsWrapper, dsTcEvBinds, dsEvBinds ) where -- #include "HsVersions.h" import {-# SOURCE #-} Language.Haskell.Liquid.Desugar710.DsExpr( dsLExpr ) import {-# SOURCE #-} Language.Haskell.Liquid.Desugar710.Match( matchWrapper ) import DsMonad import Language.Haskell.Liquid.Desugar710.DsGRHSs import Language.Haskell.Liquid.Desugar710.DsUtils import HsSyn -- lots of things import CoreSyn -- lots of things import Literal ( Literal(MachStr) ) import CoreSubst import OccurAnal ( occurAnalyseExpr ) import MkCore import CoreUtils import CoreArity ( etaExpand ) import CoreUnfold import CoreFVs import UniqSupply import Digraph import Module import PrelNames import TysPrim ( mkProxyPrimTy ) import TyCon ( tyConDataCons_maybe , tyConName, isPromotedTyCon, isPromotedDataCon ) import TcEvidence import TcType import Type import Coercion hiding (substCo) import TysWiredIn ( eqBoxDataCon, coercibleDataCon, tupleCon ) import Id import MkId(proxyHashId) import Class import DataCon ( dataConWorkId ) import Name import MkId ( seqId ) import IdInfo ( IdDetails(..) ) import Var import VarSet import Rules import VarEnv import Outputable import SrcLoc import Maybes import OrdList import Bag import BasicTypes hiding ( TopLevel ) import DynFlags import FastString import ErrUtils( MsgDoc ) import ListSetOps( getNth ) import Util import Control.Monad( when ) import MonadUtils import Control.Monad(liftM) import Fingerprint(Fingerprint(..), fingerprintString) {- ************************************************************************ * * \subsection[dsMonoBinds]{Desugaring a @MonoBinds@} * * ************************************************************************ -} dsTopLHsBinds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) dsTopLHsBinds binds = ds_lhs_binds binds dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)] dsLHsBinds binds = do { binds' <- ds_lhs_binds binds ; return (fromOL binds') } ------------------------ ds_lhs_binds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) ds_lhs_binds binds = do { ds_bs <- mapBagM dsLHsBind binds ; return (foldBag appOL id nilOL ds_bs) } dsLHsBind :: LHsBind Id -> DsM (OrdList (Id,CoreExpr)) dsLHsBind (L loc bind) = putSrcSpanDs loc $ dsHsBind bind dsHsBind :: HsBind Id -> DsM (OrdList (Id,CoreExpr)) dsHsBind (VarBind { var_id = var, var_rhs = expr, var_inline = inline_regardless }) = do { dflags <- getDynFlags ; core_expr <- dsLExpr expr -- Dictionary bindings are always VarBinds, -- so we only need do this here ; let var' | inline_regardless = var `setIdUnfolding` mkCompulsoryUnfolding core_expr | otherwise = var ; return (unitOL (makeCorePair dflags var' False 0 core_expr)) } dsHsBind (FunBind { fun_id = L _ fun, fun_matches = matches , fun_co_fn = co_fn, fun_tick = tick , fun_infix = inf }) = do { dflags <- getDynFlags ; (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches ; let body' = mkOptTickBox tick body ; rhs <- dsHsWrapper co_fn (mkLams args body') ; {- pprTrace "dsHsBind" (ppr fun <+> ppr (idInlinePragma fun)) $ -} return (unitOL (makeCorePair dflags fun False 0 rhs)) } dsHsBind (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty , pat_ticks = (rhs_tick, var_ticks) }) = do { body_expr <- dsGuarded grhss ty ; let body' = mkOptTickBox rhs_tick body_expr ; sel_binds <- mkSelectorBinds var_ticks pat body' -- We silently ignore inline pragmas; no makeCorePair -- Not so cool, but really doesn't matter ; return (toOL sel_binds) } -- A common case: one exported variable -- Non-recursive bindings come through this way -- So do self-recursive bindings, and recursive bindings -- that have been chopped up with type signatures dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = [export] , abs_ev_binds = ev_binds, abs_binds = binds }) | ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = prags } <- export = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec (fromOL bind_prs) ; ds_binds <- dsTcEvBinds ev_binds ; rhs <- dsHsWrapper wrap $ -- Usually the identity mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ Var local ; (spec_binds, rules) <- dsSpecs rhs prags ; let global' = addIdSpecialisations global rules main_bind = makeCorePair dflags global' (isDefaultMethod prags) (dictArity dicts) rhs ; return (main_bind `consOL` spec_binds) } dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = exports, abs_ev_binds = ev_binds , abs_binds = binds }) -- See Note [Desugaring AbsBinds] = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec [ makeCorePair dflags (add_inline lcl_id) False 0 rhs | (lcl_id, rhs) <- fromOL bind_prs ] -- Monomorphic recursion possible, hence Rec locals = map abe_mono exports tup_expr = mkBigCoreVarTup locals tup_ty = exprType tup_expr ; ds_binds <- dsTcEvBinds ev_binds ; let poly_tup_rhs = mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ tup_expr ; poly_tup_id <- newSysLocalDs (exprType poly_tup_rhs) ; let mk_bind (ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = spec_prags }) = do { tup_id <- newSysLocalDs tup_ty ; rhs <- dsHsWrapper wrap $ mkLams tyvars $ mkLams dicts $ mkTupleSelector locals local tup_id $ mkVarApps (Var poly_tup_id) (tyvars ++ dicts) ; let rhs_for_spec = Let (NonRec poly_tup_id poly_tup_rhs) rhs ; (spec_binds, rules) <- dsSpecs rhs_for_spec spec_prags ; let global' = (global `setInlinePragma` defaultInlinePragma) `addIdSpecialisations` rules -- Kill the INLINE pragma because it applies to -- the user written (local) function. The global -- Id is just the selector. Hmm. ; return ((global', rhs) `consOL` spec_binds) } ; export_binds_s <- mapM mk_bind exports ; return ((poly_tup_id, poly_tup_rhs) `consOL` concatOL export_binds_s) } where inline_env :: IdEnv Id -- Maps a monomorphic local Id to one with -- the inline pragma from the source -- The type checker put the inline pragma -- on the *global* Id, so we need to transfer it inline_env = mkVarEnv [ (lcl_id, setInlinePragma lcl_id prag) | ABE { abe_mono = lcl_id, abe_poly = gbl_id } <- exports , let prag = idInlinePragma gbl_id ] add_inline :: Id -> Id -- tran add_inline lcl_id = lookupVarEnv inline_env lcl_id `orElse` lcl_id dsHsBind (PatSynBind{}) = panic "dsHsBind: PatSynBind" ------------------------ makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr) makeCorePair dflags gbl_id is_default_method dict_arity rhs | is_default_method -- Default methods are *always* inlined = (gbl_id `setIdUnfolding` mkCompulsoryUnfolding rhs, rhs) | DFunId _ is_newtype <- idDetails gbl_id = (mk_dfun_w_stuff is_newtype, rhs) | otherwise = case inlinePragmaSpec inline_prag of EmptyInlineSpec -> (gbl_id, rhs) NoInline -> (gbl_id, rhs) Inlinable -> (gbl_id `setIdUnfolding` inlinable_unf, rhs) Inline -> inline_pair where inline_prag = idInlinePragma gbl_id inlinable_unf = mkInlinableUnfolding dflags rhs inline_pair | Just arity <- inlinePragmaSat inline_prag -- Add an Unfolding for an INLINE (but not for NOINLINE) -- And eta-expand the RHS; see Note [Eta-expanding INLINE things] , let real_arity = dict_arity + arity -- NB: The arity in the InlineRule takes account of the dictionaries = ( gbl_id `setIdUnfolding` mkInlineUnfolding (Just real_arity) rhs , etaExpand real_arity rhs) | otherwise = pprTrace "makeCorePair: arity missing" (ppr gbl_id) $ (gbl_id `setIdUnfolding` mkInlineUnfolding Nothing rhs, rhs) -- See Note [ClassOp/DFun selection] in TcInstDcls -- See Note [Single-method classes] in TcInstDcls mk_dfun_w_stuff is_newtype | is_newtype = gbl_id `setIdUnfolding` mkInlineUnfolding (Just 0) rhs `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 } | otherwise = gbl_id `setIdUnfolding` mkDFunUnfolding dfun_bndrs dfun_constr dfun_args `setInlinePragma` dfunInlinePragma (dfun_bndrs, dfun_body) = collectBinders (simpleOptExpr rhs) (dfun_con, dfun_args, _) = collectArgsTicks (const True) dfun_body dfun_constr | Var id <- dfun_con , DataConWorkId con <- idDetails id = con | otherwise = pprPanic "makeCorePair: dfun" (ppr rhs) dictArity :: [Var] -> Arity -- Don't count coercion variables in arity dictArity dicts = count isId dicts {- [Desugaring AbsBinds] ~~~~~~~~~~~~~~~~~~~~~ In the general AbsBinds case we desugar the binding to this: tup a (d:Num a) = let fm = ...gm... gm = ...fm... in (fm,gm) f a d = case tup a d of { (fm,gm) -> fm } g a d = case tup a d of { (fm,gm) -> fm } Note [Rules and inlining] ~~~~~~~~~~~~~~~~~~~~~~~~~ Common special case: no type or dictionary abstraction This is a bit less trivial than you might suppose The naive way woudl be to desguar to something like f_lcl = ...f_lcl... -- The "binds" from AbsBinds M.f = f_lcl -- Generated from "exports" But we don't want that, because if M.f isn't exported, it'll be inlined unconditionally at every call site (its rhs is trivial). That would be ok unless it has RULES, which would thereby be completely lost. Bad, bad, bad. Instead we want to generate M.f = ...f_lcl... f_lcl = M.f Now all is cool. The RULES are attached to M.f (by SimplCore), and f_lcl is rapidly inlined away. This does not happen in the same way to polymorphic binds, because they desugar to M.f = /\a. let f_lcl = ...f_lcl... in f_lcl Although I'm a bit worried about whether full laziness might float the f_lcl binding out and then inline M.f at its call site Note [Specialising in no-dict case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even if there are no tyvars or dicts, we may have specialisation pragmas. Class methods can generate AbsBinds [] [] [( ... spec-prag] { AbsBinds [tvs] [dicts] ...blah } So the overloading is in the nested AbsBinds. A good example is in GHC.Float: class (Real a, Fractional a) => RealFrac a where round :: (Integral b) => a -> b instance RealFrac Float where {-# SPECIALIZE round :: Float -> Int #-} The top-level AbsBinds for $cround has no tyvars or dicts (because the instance does not). But the method is locally overloaded! Note [Abstracting over tyvars only] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When abstracting over type variable only (not dictionaries), we don't really need to built a tuple and select from it, as we do in the general case. Instead we can take AbsBinds [a,b] [ ([a,b], fg, fl, _), ([b], gg, gl, _) ] { fl = e1 gl = e2 h = e3 } and desugar it to fg = /\ab. let B in e1 gg = /\b. let a = () in let B in S(e2) h = /\ab. let B in e3 where B is the *non-recursive* binding fl = fg a b gl = gg b h = h a b -- See (b); note shadowing! Notice (a) g has a different number of type variables to f, so we must use the mkArbitraryType thing to fill in the gaps. We use a type-let to do that. (b) The local variable h isn't in the exports, and rather than clone a fresh copy we simply replace h by (h a b), where the two h's have different types! Shadowing happens here, which looks confusing but works fine. (c) The result is *still* quadratic-sized if there are a lot of small bindings. So if there are more than some small number (10), we filter the binding set B by the free variables of the particular RHS. Tiresome. Why got to this trouble? It's a common case, and it removes the quadratic-sized tuple desugaring. Less clutter, hopefully faster compilation, especially in a case where there are a *lot* of bindings. Note [Eta-expanding INLINE things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider foo :: Eq a => a -> a {-# INLINE foo #-} foo x = ... If (foo d) ever gets floated out as a common sub-expression (which can happen as a result of method sharing), there's a danger that we never get to do the inlining, which is a Terribly Bad thing given that the user said "inline"! To avoid this we pre-emptively eta-expand the definition, so that foo has the arity with which it is declared in the source code. In this example it has arity 2 (one for the Eq and one for x). Doing this should mean that (foo d) is a PAP and we don't share it. Note [Nested arities] ~~~~~~~~~~~~~~~~~~~~~ For reasons that are not entirely clear, method bindings come out looking like this: AbsBinds [] [] [$cfromT <= [] fromT] $cfromT [InlPrag=INLINE] :: T Bool -> Bool { AbsBinds [] [] [fromT <= [] fromT_1] fromT :: T Bool -> Bool { fromT_1 ((TBool b)) = not b } } } Note the nested AbsBind. The arity for the InlineRule on $cfromT should be gotten from the binding for fromT_1. It might be better to have just one level of AbsBinds, but that requires more thought! Note [Implementing SPECIALISE pragmas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Example: f :: (Eq a, Ix b) => a -> b -> Bool {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-} f = <poly_rhs> From this the typechecker generates AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ]) Note that wrap_fn can transform *any* function with the right type prefix forall ab. (Eq a, Ix b) => XXX regardless of XXX. It's sort of polymorphic in XXX. This is useful: we use the same wrapper to transform each of the class ops, as well as the dict. From these we generate: Rule: forall p, q, (dp:Ix p), (dq:Ix q). f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq Spec bind: f_spec = wrap_fn <poly_rhs> Note that * The LHS of the rule may mention dictionary *expressions* (eg $dfIxPair dp dq), and that is essential because the dp, dq are needed on the RHS. * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it can fully specialise it. -} ------------------------ dsSpecs :: CoreExpr -- Its rhs -> TcSpecPrags -> DsM ( OrdList (Id,CoreExpr) -- Binding for specialised Ids , [CoreRule] ) -- Rules for the Global Ids -- See Note [Implementing SPECIALISE pragmas] dsSpecs _ IsDefaultMethod = return (nilOL, []) dsSpecs poly_rhs (SpecPrags sps) = do { pairs <- mapMaybeM (dsSpec (Just poly_rhs)) sps ; let (spec_binds_s, rules) = unzip pairs ; return (concatOL spec_binds_s, rules) } dsSpec :: Maybe CoreExpr -- Just rhs => RULE is for a local binding -- Nothing => RULE is for an imported Id -- rhs is in the Id's unfolding -> Located TcSpecPrag -> DsM (Maybe (OrdList (Id,CoreExpr), CoreRule)) dsSpec mb_poly_rhs (L loc (SpecPrag poly_id spec_co spec_inl)) | isJust (isClassOpId_maybe poly_id) = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for class method selector") <+> quotes (ppr poly_id)) ; return Nothing } -- There is no point in trying to specialise a class op -- Moreover, classops don't (currently) have an inl_sat arity set -- (it would be Just 0) and that in turn makes makeCorePair bleat | no_act_spec && isNeverActive rule_act = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for NOINLINE function:") <+> quotes (ppr poly_id)) ; return Nothing } -- Function is NOINLINE, and the specialiation inherits that -- See Note [Activation pragmas for SPECIALISE] | otherwise = putSrcSpanDs loc $ do { uniq <- newUnique ; let poly_name = idName poly_id spec_occ = mkSpecOcc (getOccName poly_name) spec_name = mkInternalName uniq spec_occ (getSrcSpan poly_name) ; (bndrs, ds_lhs) <- liftM collectBinders (dsHsWrapper spec_co (Var poly_id)) ; let spec_ty = mkPiTypes bndrs (exprType ds_lhs) ; -- pprTrace "dsRule" (vcat [ ptext (sLit "Id:") <+> ppr poly_id -- , ptext (sLit "spec_co:") <+> ppr spec_co -- , ptext (sLit "ds_rhs:") <+> ppr ds_lhs ]) $ case decomposeRuleLhs bndrs ds_lhs of { Left msg -> do { warnDs msg; return Nothing } ; Right (rule_bndrs, _fn, args) -> do { dflags <- getDynFlags ; let fn_unf = realIdUnfolding poly_id unf_fvs = stableUnfoldingVars fn_unf `orElse` emptyVarSet in_scope = mkInScopeSet (unf_fvs `unionVarSet` exprsFreeVars args) spec_unf = specUnfolding dflags (mkEmptySubst in_scope) bndrs args fn_unf spec_id = mkLocalId spec_name spec_ty `setInlinePragma` inl_prag `setIdUnfolding` spec_unf rule = mkRule False {- Not auto -} is_local_id (mkFastString ("SPEC " ++ showPpr dflags poly_name)) rule_act poly_name rule_bndrs args (mkVarApps (Var spec_id) bndrs) ; spec_rhs <- dsHsWrapper spec_co poly_rhs ; when (isInlinePragma id_inl && wopt Opt_WarnPointlessPragmas dflags) (warnDs (specOnInline poly_name)) ; return (Just (unitOL (spec_id, spec_rhs), rule)) -- NB: do *not* use makeCorePair on (spec_id,spec_rhs), because -- makeCorePair overwrites the unfolding, which we have -- just created using specUnfolding } } } where is_local_id = isJust mb_poly_rhs poly_rhs | Just rhs <- mb_poly_rhs = rhs -- Local Id; this is its rhs | Just unfolding <- maybeUnfoldingTemplate (realIdUnfolding poly_id) = unfolding -- Imported Id; this is its unfolding -- Use realIdUnfolding so we get the unfolding -- even when it is a loop breaker. -- We want to specialise recursive functions! | otherwise = pprPanic "dsImpSpecs" (ppr poly_id) -- The type checker has checked that it *has* an unfolding id_inl = idInlinePragma poly_id -- See Note [Activation pragmas for SPECIALISE] inl_prag | not (isDefaultInlinePragma spec_inl) = spec_inl | not is_local_id -- See Note [Specialising imported functions] -- in OccurAnal , isStrongLoopBreaker (idOccInfo poly_id) = neverInlinePragma | otherwise = id_inl -- Get the INLINE pragma from SPECIALISE declaration, or, -- failing that, from the original Id spec_prag_act = inlinePragmaActivation spec_inl -- See Note [Activation pragmas for SPECIALISE] -- no_act_spec is True if the user didn't write an explicit -- phase specification in the SPECIALISE pragma no_act_spec = case inlinePragmaSpec spec_inl of NoInline -> isNeverActive spec_prag_act _ -> isAlwaysActive spec_prag_act rule_act | no_act_spec = inlinePragmaActivation id_inl -- Inherit | otherwise = spec_prag_act -- Specified by user specOnInline :: Name -> MsgDoc specOnInline f = ptext (sLit "SPECIALISE pragma on INLINE function probably won't fire:") <+> quotes (ppr f) {- Note [Activation pragmas for SPECIALISE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From a user SPECIALISE pragma for f, we generate a) A top-level binding spec_fn = rhs b) A RULE f dOrd = spec_fn We need two pragma-like things: * spec_fn's inline pragma: inherited from f's inline pragma (ignoring activation on SPEC), unless overriden by SPEC INLINE * Activation of RULE: from SPECIALISE pragma (if activation given) otherwise from f's inline pragma This is not obvious (see Trac #5237)! Examples Rule activation Inline prag on spec'd fn --------------------------------------------------------------------- SPEC [n] f :: ty [n] Always, or NOINLINE [n] copy f's prag NOINLINE f SPEC [n] f :: ty [n] NOINLINE copy f's prag NOINLINE [k] f SPEC [n] f :: ty [n] NOINLINE [k] copy f's prag INLINE [k] f SPEC [n] f :: ty [n] INLINE [k] copy f's prag SPEC INLINE [n] f :: ty [n] INLINE [n] (ignore INLINE prag on f, same activation for rule and spec'd fn) NOINLINE [k] f SPEC f :: ty [n] INLINE [k] ************************************************************************ * * \subsection{Adding inline pragmas} * * ************************************************************************ -} decomposeRuleLhs :: [Var] -> CoreExpr -> Either SDoc ([Var], Id, [CoreExpr]) -- (decomposeRuleLhs bndrs lhs) takes apart the LHS of a RULE, -- The 'bndrs' are the quantified binders of the rules, but decomposeRuleLhs -- may add some extra dictionary binders (see Note [Free dictionaries]) -- -- Returns Nothing if the LHS isn't of the expected shape -- Note [Decomposing the left-hand side of a RULE] decomposeRuleLhs orig_bndrs orig_lhs | not (null unbound) -- Check for things unbound on LHS -- See Note [Unused spec binders] = Left (vcat (map dead_msg unbound)) | Var fn_var <- fun , not (fn_var `elemVarSet` orig_bndr_set) = -- pprTrace "decmposeRuleLhs" (vcat [ ptext (sLit "orig_bndrs:") <+> ppr orig_bndrs -- , ptext (sLit "orig_lhs:") <+> ppr orig_lhs -- , ptext (sLit "lhs1:") <+> ppr lhs1 -- , ptext (sLit "bndrs1:") <+> ppr bndrs1 -- , ptext (sLit "fn_var:") <+> ppr fn_var -- , ptext (sLit "args:") <+> ppr args]) $ Right (bndrs1, fn_var, args) | Case scrut bndr ty [(DEFAULT, _, body)] <- fun , isDeadBinder bndr -- Note [Matching seqId] , let args' = [Type (idType bndr), Type ty, scrut, body] = Right (bndrs1, seqId, args' ++ args) | otherwise = Left bad_shape_msg where lhs1 = drop_dicts orig_lhs lhs2 = simpleOptExpr lhs1 -- See Note [Simplify rule LHS] (fun,args) = collectArgs lhs2 lhs_fvs = exprFreeVars lhs2 unbound = filterOut (`elemVarSet` lhs_fvs) orig_bndrs bndrs1 = orig_bndrs ++ extra_dict_bndrs orig_bndr_set = mkVarSet orig_bndrs -- Add extra dict binders: Note [Free dictionaries] extra_dict_bndrs = [ mkLocalId (localiseName (idName d)) (idType d) | d <- varSetElems (lhs_fvs `delVarSetList` orig_bndrs) , isDictId d ] bad_shape_msg = hang (ptext (sLit "RULE left-hand side too complicated to desugar")) 2 (vcat [ text "Optimised lhs:" <+> ppr lhs2 , text "Orig lhs:" <+> ppr orig_lhs]) dead_msg bndr = hang (sep [ ptext (sLit "Forall'd") <+> pp_bndr bndr , ptext (sLit "is not bound in RULE lhs")]) 2 (vcat [ text "Orig bndrs:" <+> ppr orig_bndrs , text "Orig lhs:" <+> ppr orig_lhs , text "optimised lhs:" <+> ppr lhs2 ]) pp_bndr bndr | isTyVar bndr = ptext (sLit "type variable") <+> quotes (ppr bndr) | Just pred <- evVarPred_maybe bndr = ptext (sLit "constraint") <+> quotes (ppr pred) | otherwise = ptext (sLit "variable") <+> quotes (ppr bndr) drop_dicts :: CoreExpr -> CoreExpr drop_dicts e = wrap_lets needed bnds body where needed = orig_bndr_set `minusVarSet` exprFreeVars body (bnds, body) = split_lets (occurAnalyseExpr e) -- The occurAnalyseExpr drops dead bindings which is -- crucial to ensure that every binding is used later; -- which in turn makes wrap_lets work right split_lets :: CoreExpr -> ([(DictId,CoreExpr)], CoreExpr) split_lets e | Let (NonRec d r) body <- e , isDictId d , (bs, body') <- split_lets body = ((d,r):bs, body') | otherwise = ([], e) wrap_lets :: VarSet -> [(DictId,CoreExpr)] -> CoreExpr -> CoreExpr wrap_lets _ [] body = body wrap_lets needed ((d, r) : bs) body | rhs_fvs `intersectsVarSet` needed = Let (NonRec d r) (wrap_lets needed' bs body) | otherwise = wrap_lets needed bs body where rhs_fvs = exprFreeVars r needed' = (needed `minusVarSet` rhs_fvs) `extendVarSet` d {- Note [Decomposing the left-hand side of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are several things going on here. * drop_dicts: see Note [Drop dictionary bindings on rule LHS] * simpleOptExpr: see Note [Simplify rule LHS] * extra_dict_bndrs: see Note [Free dictionaries] Note [Drop dictionary bindings on rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ drop_dicts drops dictionary bindings on the LHS where possible. E.g. let d:Eq [Int] = $fEqList $fEqInt in f d --> f d Reasoning here is that there is only one d:Eq [Int], and so we can quantify over it. That makes 'd' free in the LHS, but that is later picked up by extra_dict_bndrs (Note [Dead spec binders]). NB 1: We can only drop the binding if the RHS doesn't bind one of the orig_bndrs, which we assume occur on RHS. Example f :: (Eq a) => b -> a -> a {-# SPECIALISE f :: Eq a => b -> [a] -> [a] #-} Here we want to end up with RULE forall d:Eq a. f ($dfEqList d) = f_spec d Of course, the ($dfEqlist d) in the pattern makes it less likely to match, but ther is no other way to get d:Eq a NB 2: We do drop_dicts *before* simplOptEpxr, so that we expect all the evidence bindings to be wrapped around the outside of the LHS. (After simplOptExpr they'll usually have been inlined.) dsHsWrapper does dependency analysis, so that civilised ones will be simple NonRec bindings. We don't handle recursive dictionaries! NB3: In the common case of a non-overloaded, but perhaps-polymorphic specialisation, we don't need to bind *any* dictionaries for use in the RHS. For example (Trac #8331) {-# SPECIALIZE INLINE useAbstractMonad :: ReaderST s Int #-} useAbstractMonad :: MonadAbstractIOST m => m Int Here, deriving (MonadAbstractIOST (ReaderST s)) is a lot of code but the RHS uses no dictionaries, so we want to end up with RULE forall s (d :: MonadBstractIOST (ReaderT s)). useAbstractMonad (ReaderT s) d = $suseAbstractMonad s Trac #8848 is a good example of where there are some intersting dictionary bindings to discard. The drop_dicts algorithm is based on these observations: * Given (let d = rhs in e) where d is a DictId, matching 'e' will bind e's free variables. * So we want to keep the binding if one of the needed variables (for which we need a binding) is in fv(rhs) but not already in fv(e). * The "needed variables" are simply the orig_bndrs. Consider f :: (Eq a, Show b) => a -> b -> String ... SPECIALISE f :: (Show b) => Int -> b -> String ... Then orig_bndrs includes the *quantified* dictionaries of the type namely (dsb::Show b), but not the one for Eq Int So we work inside out, applying the above criterion at each step. Note [Simplify rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~ simplOptExpr occurrence-analyses and simplifies the LHS: (a) Inline any remaining dictionary bindings (which hopefully occur just once) (b) Substitute trivial lets so that they don't get in the way Note that we substitute the function too; we might have this as a LHS: let f71 = M.f Int in f71 (c) Do eta reduction. To see why, consider the fold/build rule, which without simplification looked like: fold k z (build (/\a. g a)) ==> ... This doesn't match unless you do eta reduction on the build argument. Similarly for a LHS like augment g (build h) we do not want to get augment (\a. g a) (build h) otherwise we don't match when given an argument like augment (\a. h a a) (build h) Note [Matching seqId] ~~~~~~~~~~~~~~~~~~~ The desugarer turns (seq e r) into (case e of _ -> r), via a special-case hack and this code turns it back into an application of seq! See Note [Rules for seq] in MkId for the details. Note [Unused spec binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: a -> a ... SPECIALISE f :: Eq a => a -> a ... It's true that this *is* a more specialised type, but the rule we get is something like this: f_spec d = f RULE: f = f_spec d Note that the rule is bogus, because it mentions a 'd' that is not bound on the LHS! But it's a silly specialisation anyway, because the constraint is unused. We could bind 'd' to (error "unused") but it seems better to reject the program because it's almost certainly a mistake. That's what the isDeadBinder call detects. Note [Free dictionaries] ~~~~~~~~~~~~~~~~~~~~~~~~ When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict, which is presumably in scope at the function definition site, we can quantify over it too. *Any* dict with that type will do. So for example when you have f :: Eq a => a -> a f = <rhs> ... SPECIALISE f :: Int -> Int ... Then we get the SpecPrag SpecPrag (f Int dInt) And from that we want the rule RULE forall dInt. f Int dInt = f_spec f_spec = let f = <rhs> in f Int dInt But be careful! That dInt might be GHC.Base.$fOrdInt, which is an External Name, and you can't bind them in a lambda or forall without getting things confused. Likewise it might have an InlineRule or something, which would be utterly bogus. So we really make a fresh Id, with the same unique and type as the old one, but with an Internal name and no IdInfo. ************************************************************************ * * Desugaring evidence * * ************************************************************************ -} dsHsWrapper :: HsWrapper -> CoreExpr -> DsM CoreExpr dsHsWrapper WpHole e = return e dsHsWrapper (WpTyApp ty) e = return $ App e (Type ty) dsHsWrapper (WpLet ev_binds) e = do bs <- dsTcEvBinds ev_binds return (mkCoreLets bs e) dsHsWrapper (WpCompose c1 c2) e = do { e1 <- dsHsWrapper c2 e ; dsHsWrapper c1 e1 } dsHsWrapper (WpFun c1 c2 t1 _) e = do { x <- newSysLocalDs t1 ; e1 <- dsHsWrapper c1 (Var x) ; e2 <- dsHsWrapper c2 (e `mkCoreAppDs` e1) ; return (Lam x e2) } dsHsWrapper (WpCast co) e = -- ASSERT(tcCoercionRole co == Representational) dsTcCoercion co (mkCast e) dsHsWrapper (WpEvLam ev) e = return $ Lam ev e dsHsWrapper (WpTyLam tv) e = return $ Lam tv e dsHsWrapper (WpEvApp tm) e = liftM (App e) (dsEvTerm tm) -------------------------------------- dsTcEvBinds :: TcEvBinds -> DsM [CoreBind] dsTcEvBinds (TcEvBinds {}) = panic "dsEvBinds" -- Zonker has got rid of this dsTcEvBinds (EvBinds bs) = dsEvBinds bs dsEvBinds :: Bag EvBind -> DsM [CoreBind] dsEvBinds bs = mapM ds_scc (sccEvBinds bs) where ds_scc (AcyclicSCC (EvBind v r)) = liftM (NonRec v) (dsEvTerm r) ds_scc (CyclicSCC bs) = liftM Rec (mapM ds_pair bs) ds_pair (EvBind v r) = liftM ((,) v) (dsEvTerm r) sccEvBinds :: Bag EvBind -> [SCC EvBind] sccEvBinds bs = stronglyConnCompFromEdgedVertices edges where edges :: [(EvBind, EvVar, [EvVar])] edges = foldrBag ((:) . mk_node) [] bs mk_node :: EvBind -> (EvBind, EvVar, [EvVar]) mk_node b@(EvBind var term) = (b, var, varSetElems (evVarsOfTerm term)) --------------------------------------- dsEvTerm :: EvTerm -> DsM CoreExpr dsEvTerm (EvId v) = return (Var v) dsEvTerm (EvCast tm co) = do { tm' <- dsEvTerm tm ; dsTcCoercion co $ mkCast tm' } -- 'v' is always a lifted evidence variable so it is -- unnecessary to call varToCoreExpr v here. dsEvTerm (EvDFunApp df tys tms) = do { tms' <- mapM dsEvTerm tms ; return (Var df `mkTyApps` tys `mkApps` tms') } dsEvTerm (EvCoercion (TcCoVarCo v)) = return (Var v) -- See Note [Simple coercions] dsEvTerm (EvCoercion co) = dsTcCoercion co mkEqBox dsEvTerm (EvTupleSel v n) = do { tm' <- dsEvTerm v ; let scrut_ty = exprType tm' (tc, tys) = splitTyConApp scrut_ty Just [dc] = tyConDataCons_maybe tc xs = mkTemplateLocals tys the_x = getNth xs n ; -- ASSERT( isTupleTyCon tc ) return $ Case tm' (mkWildValBinder scrut_ty) (idType the_x) [(DataAlt dc, xs, Var the_x)] } dsEvTerm (EvTupleMk tms) = do { tms' <- mapM dsEvTerm tms ; let tys = map exprType tms' ; return $ Var (dataConWorkId dc) `mkTyApps` tys `mkApps` tms' } where dc = tupleCon ConstraintTuple (length tms) dsEvTerm (EvSuperClass d n) = do { d' <- dsEvTerm d ; let (cls, tys) = getClassPredTys (exprType d') sc_sel_id = classSCSelId cls n -- Zero-indexed ; return $ Var sc_sel_id `mkTyApps` tys `App` d' } where dsEvTerm (EvDelayedError ty msg) = return $ Var errorId `mkTyApps` [ty] `mkApps` [litMsg] where errorId = rUNTIME_ERROR_ID litMsg = Lit (MachStr (fastStringToByteString msg)) dsEvTerm (EvLit l) = case l of EvNum n -> mkIntegerExpr n EvStr s -> mkStringExprFS s dsEvTerm (EvTypeable ev) = dsEvTypeable ev dsEvTypeable :: EvTypeable -> DsM CoreExpr dsEvTypeable ev = do tyCl <- dsLookupTyCon typeableClassName typeRepTc <- dsLookupTyCon typeRepTyConName let tyRepType = mkTyConApp typeRepTc [] (ty, rep) <- case ev of EvTypeableTyCon tc ks -> do ctr <- dsLookupGlobalId mkPolyTyConAppName mkTyCon <- dsLookupGlobalId mkTyConName dflags <- getDynFlags let mkRep cRep kReps tReps = mkApps (Var ctr) [ cRep, mkListExpr tyRepType kReps , mkListExpr tyRepType tReps ] let kindRep k = case splitTyConApp_maybe k of Nothing -> panic "dsEvTypeable: not a kind constructor" Just (kc,ks) -> do kcRep <- tyConRep dflags mkTyCon kc reps <- mapM kindRep ks return (mkRep kcRep [] reps) tcRep <- tyConRep dflags mkTyCon tc kReps <- mapM kindRep ks return ( mkTyConApp tc ks , mkRep tcRep kReps [] ) EvTypeableTyApp t1 t2 -> do e1 <- getRep tyCl t1 e2 <- getRep tyCl t2 ctr <- dsLookupGlobalId mkAppTyName return ( mkAppTy (snd t1) (snd t2) , mkApps (Var ctr) [ e1, e2 ] ) EvTypeableTyLit ty -> do str <- case (isNumLitTy ty, isStrLitTy ty) of (Just n, _) -> return (show n) (_, Just n) -> return (show n) _ -> panic "dsEvTypeable: malformed TyLit evidence" ctr <- dsLookupGlobalId typeLitTypeRepName tag <- mkStringExpr str return (ty, mkApps (Var ctr) [ tag ]) -- TyRep -> Typeable t -- see also: Note [Memoising typeOf] repName <- newSysLocalDs tyRepType let proxyT = mkProxyPrimTy (typeKind ty) ty method = bindNonRec repName rep $ mkLams [mkWildValBinder proxyT] (Var repName) -- package up the method as `Typeable` dictionary return $ mkCast method $ mkSymCo $ getTypeableCo tyCl ty where -- co: method -> Typeable k t getTypeableCo tc t = case instNewTyCon_maybe tc [typeKind t, t] of Just (_,co) -> co _ -> panic "Class `Typeable` is not a `newtype`." -- Typeable t -> TyRep getRep tc (ev,t) = do typeableExpr <- dsEvTerm ev let co = getTypeableCo tc t method = mkCast typeableExpr co proxy = mkTyApps (Var proxyHashId) [typeKind t, t] return (mkApps method [proxy]) -- This part could be cached tyConRep dflags mkTyCon tc = do pkgStr <- mkStringExprFS pkg_fs modStr <- mkStringExprFS modl_fs nameStr <- mkStringExprFS name_fs return (mkApps (Var mkTyCon) [ int64 high, int64 low , pkgStr, modStr, nameStr ]) where tycon_name = tyConName tc modl = nameModule tycon_name pkg = modulePackageKey modl modl_fs = moduleNameFS (moduleName modl) pkg_fs = packageKeyFS pkg name_fs = occNameFS (nameOccName tycon_name) hash_name_fs | isPromotedTyCon tc = appendFS (mkFastString "$k") name_fs | isPromotedDataCon tc = appendFS (mkFastString "$c") name_fs | otherwise = name_fs hashThis = unwords $ map unpackFS [pkg_fs, modl_fs, hash_name_fs] Fingerprint high low = fingerprintString hashThis int64 | wORD_SIZE dflags == 4 = mkWord64LitWord64 | otherwise = mkWordLit dflags . fromIntegral {- Note [Memoising typeOf] ~~~~~~~~~~~~~~~~~~~~~~~~~~ See #3245, #9203 IMPORTANT: we don't want to recalculate the TypeRep once per call with the proxy argument. This is what went wrong in #3245 and #9203. So we help GHC by manually keeping the 'rep' *outside* the lambda. -} --------------------------------------- dsTcCoercion :: TcCoercion -> (Coercion -> CoreExpr) -> DsM CoreExpr -- This is the crucial function that moves -- from TcCoercions to Coercions; see Note [TcCoercions] in Coercion -- e.g. dsTcCoercion (trans g1 g2) k -- = case g1 of EqBox g1# -> -- case g2 of EqBox g2# -> -- k (trans g1# g2#) -- thing_inside will get a coercion at the role requested dsTcCoercion co thing_inside = do { us <- newUniqueSupply ; let eqvs_covs :: [(EqVar,CoVar)] eqvs_covs = zipWith mk_co_var (varSetElems (coVarsOfTcCo co)) (uniqsFromSupply us) subst = mkCvSubst emptyInScopeSet [(eqv, mkCoVarCo cov) | (eqv, cov) <- eqvs_covs] result_expr = thing_inside (ds_tc_coercion subst co) result_ty = exprType result_expr ; return (foldr (wrap_in_case result_ty) result_expr eqvs_covs) } where mk_co_var :: Id -> Unique -> (Id, Id) mk_co_var eqv uniq = (eqv, mkUserLocal occ uniq ty loc) where eq_nm = idName eqv occ = nameOccName eq_nm loc = nameSrcSpan eq_nm ty = mkCoercionType (getEqPredRole (evVarPred eqv)) ty1 ty2 (ty1, ty2) = getEqPredTys (evVarPred eqv) wrap_in_case result_ty (eqv, cov) body = case getEqPredRole (evVarPred eqv) of Nominal -> Case (Var eqv) eqv result_ty [(DataAlt eqBoxDataCon, [cov], body)] Representational -> Case (Var eqv) eqv result_ty [(DataAlt coercibleDataCon, [cov], body)] Phantom -> panic "wrap_in_case/phantom" ds_tc_coercion :: CvSubst -> TcCoercion -> Coercion -- If the incoming TcCoercion if of type (a ~ b) (resp. Coercible a b) -- the result is of type (a ~# b) (reps. a ~# b) -- The VarEnv maps EqVars of type (a ~ b) to Coercions of type (a ~# b) (resp. and so on) -- No need for InScope set etc because the ds_tc_coercion subst tc_co = go tc_co where go (TcRefl r ty) = Refl r (Coercion.substTy subst ty) go (TcTyConAppCo r tc cos) = mkTyConAppCo r tc (map go cos) go (TcAppCo co1 co2) = mkAppCo (go co1) (go co2) go (TcForAllCo tv co) = mkForAllCo tv' (ds_tc_coercion subst' co) where (subst', tv') = Coercion.substTyVarBndr subst tv go (TcAxiomInstCo ax ind cos) = AxiomInstCo ax ind (map go cos) go (TcPhantomCo ty1 ty2) = UnivCo (fsLit "ds_tc_coercion") Phantom ty1 ty2 go (TcSymCo co) = mkSymCo (go co) go (TcTransCo co1 co2) = mkTransCo (go co1) (go co2) go (TcNthCo n co) = mkNthCo n (go co) go (TcLRCo lr co) = mkLRCo lr (go co) go (TcSubCo co) = mkSubCo (go co) go (TcLetCo bs co) = ds_tc_coercion (ds_co_binds bs) co go (TcCastCo co1 co2) = mkCoCast (go co1) (go co2) go (TcCoVarCo v) = ds_ev_id subst v go (TcAxiomRuleCo co ts cs) = AxiomRuleCo co (map (Coercion.substTy subst) ts) (map go cs) go (TcCoercion co) = co ds_co_binds :: TcEvBinds -> CvSubst ds_co_binds (EvBinds bs) = foldl ds_scc subst (sccEvBinds bs) ds_co_binds eb@(TcEvBinds {}) = pprPanic "ds_co_binds" (ppr eb) ds_scc :: CvSubst -> SCC EvBind -> CvSubst ds_scc subst (AcyclicSCC (EvBind v ev_term)) = extendCvSubstAndInScope subst v (ds_co_term subst ev_term) ds_scc _ (CyclicSCC other) = pprPanic "ds_scc:cyclic" (ppr other $$ ppr tc_co) ds_co_term :: CvSubst -> EvTerm -> Coercion ds_co_term subst (EvCoercion tc_co) = ds_tc_coercion subst tc_co ds_co_term subst (EvId v) = ds_ev_id subst v ds_co_term subst (EvCast tm co) = mkCoCast (ds_co_term subst tm) (ds_tc_coercion subst co) ds_co_term _ other = pprPanic "ds_co_term" (ppr other $$ ppr tc_co) ds_ev_id :: CvSubst -> EqVar -> Coercion ds_ev_id subst v | Just co <- Coercion.lookupCoVar subst v = co | otherwise = pprPanic "ds_tc_coercion" (ppr v $$ ppr tc_co) {- Note [Simple coercions] ~~~~~~~~~~~~~~~~~~~~~~~ We have a special case for coercions that are simple variables. Suppose cv :: a ~ b is in scope Lacking the special case, if we see f a b cv we'd desguar to f a b (case cv of EqBox (cv# :: a ~# b) -> EqBox cv#) which is a bit stupid. The special case does the obvious thing. This turns out to be important when desugaring the LHS of a RULE (see Trac #7837). Suppose we have normalise :: (a ~ Scalar a) => a -> a normalise_Double :: Double -> Double {-# RULES "normalise" normalise = normalise_Double #-} Then the RULE we want looks like forall a, (cv:a~Scalar a). normalise a cv = normalise_Double But without the special case we generate the redundant box/unbox, which simpleOpt (currently) doesn't remove. So the rule never matches. Maybe simpleOpt should be smarter. But it seems like a good plan to simply never generate the redundant box/unbox in the first place. -}
spinda/liquidhaskell
src/Language/Haskell/Liquid/Desugar710/DsBinds.hs
bsd-3-clause
46,621
0
24
14,591
7,877
4,053
3,824
508
21
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Network.EasyBitcoin.BitcoinUnits ( btc , mBTC , satoshis , asBtc , asMbtc , asSatoshis , showAsBtc , showAsMbtc , showAsSatoshis , BTC() )where import Network.EasyBitcoin.NetworkParams import Network.EasyBitcoin.Internal.InstanciationHelpers import Control.Arrow(first) import Control.Applicative((<$>)) import Data.Aeson -- | Bitcoins are represented internally as an integer value, but showed and read as a decimal values. -- When importing them, extra significative digits will be silently dropped. newtype BTC a = Satoshis Int deriving (Eq,Ord,Num) btc :: Double -> BTC net btc x = Satoshis $ round (x*100000000) mBTC :: Double -> BTC net mBTC x = Satoshis $ round (x*100000) satoshis :: Int -> BTC net satoshis = Satoshis asBtc :: BTC net -> Double asBtc (Satoshis x) = fromIntegral x/100000000 asMbtc :: BTC net -> Double asMbtc (Satoshis x) = fromIntegral x /100000 asSatoshis :: BTC net -> Int asSatoshis (Satoshis x) = x showAsBtc :: BTC net -> String showAsBtc (Satoshis x) = let str = reverse (show x) ++ replicate 9 '0' (smallers,biggers) = splitAt 8 str in if all (=='0') biggers then "0." ++ reverse smallers else dropWhile (=='0') $ reverse biggers ++ "." ++ reverse smallers showAsMbtc :: BTC net -> String showAsMbtc (Satoshis x) = let str = reverse (show x) ++ replicate 6 '0' (smallers,biggers) = splitAt 5 str in if all (=='0') biggers then "0." ++ reverse smallers else dropWhile (=='0') $ reverse biggers ++ "." ++ reverse smallers showAsSatoshis :: BTC net -> String showAsSatoshis = show.asSatoshis instance Show (BTC a) where show = showAsBtc instance Read (BTC a) where readsPrec n str = first btc <$> (readsPrec n str:: [(Double,String)]) instance ToJSON (BTC a) where toJSON = toJSON.asBtc
vwwv/easy-bitcoin
Network/EasyBitcoin/BitcoinUnits.hs
bsd-3-clause
2,212
0
12
721
638
337
301
53
2
module Tunagui.Widget.Component.Part ( ClickableArea (..) , mkClickableArea , TextContent (..) , mkTextContent ) where import Control.Monad (void) import Control.Monad.IO.Class (liftIO) import Control.Concurrent (forkIO) import Control.Concurrent.MVar import FRP.Sodium import qualified Data.Text as T import Linear.V2 import Data.Maybe (fromMaybe) import Graphics.UI.SDL.TTF.FFI (TTFFont) import qualified Tunagui.General.Data as D import Tunagui.General.Types (Point(..), Size(..), Shape(..), within) import qualified Tunagui.Internal.Render as R import Tunagui.Internal.Render (runRender) data ClickableArea = ClickableArea { clickEvent :: Event (Point Int) , crossBoundary :: Event Bool } mkClickableArea :: Behavior (Point Int) -> Behavior (Shape Int) -> Event (Point Int) -> Event (Point Int) -> Event (Point Int) -> -- Mouse motion Reactive ClickableArea mkClickableArea bPos bShape eClick eRelease eMotion = do behWaitingRls <- hold False ((const True <$> eClkOn) `merge` (const False <$> eRelease)) let eClk = (fst . fst) <$> filterE snd (snapshot (,) eRlsOn behWaitingRls) ClickableArea <$> pure eClk <*> mkMotion where within' = uncurry within bArea = (,) <$> bPos <*> bShape -- Click eClkOn = filterE within' $ snapshot (,) eClick bArea eRlsOn = filterE within' $ snapshot (,) eRelease bArea -- Motion mkMotion = do (behPre, pushPre) <- newBehavior False _ <- listen eMotionOn $ void . forkIO . sync . pushPre return $ fst <$> filterE (uncurry (/=)) (snapshot (,) eMotionOn behPre) where eMotionOn = within' <$> snapshot (,) eMotion bArea data TextContent = TextContent { tcText :: Behavior T.Text , tcWidth :: Behavior Int , tcHeight :: Behavior Int -- , modifyText :: (T.Text -> T.Text) -> Reactive () } mkTextContent :: D.Window -> TTFFont -> Maybe T.Text -> Reactive TextContent mkTextContent win font mtext = do (behCW, pushCW) <- newBehavior 0 (behCH, pushCH) <- newBehavior 0 (behText, pushText) <- newBehavior $ T.pack "" _ <- listen (updates behText) $ \text -> void . forkIO $ do (S (V2 w h)) <- withMVar (D.wRenderer win) $ \r -> runRender r $ R.textSize font text liftIO . sync $ do pushCW w pushCH h pushText $ fromMaybe (T.pack "") mtext return TextContent { tcText = behText , tcWidth = behCW , tcHeight = behCH -- , modifyText = \f -> pushText . f =<< sample behText }
masatoko/tunagui
src/Tunagui/Widget/Component/Part.hs
bsd-3-clause
2,600
0
18
655
901
483
418
67
1
import Language.Mira.RegExpParser as Parser import Control.Monad import System.Environment main = liftM head getArgs >>= print . Parser.regex . Parser.lexer
AidanDelaney/Mira
src/examples/ParserExample.hs
bsd-3-clause
158
0
8
20
45
25
20
4
1
{-# LANGUAGE ViewPatterns #-} module Lib ( someFunc , Point , LineSegment , distance , perpendicularDistance , splitAtMaxDistance , douglasPeucker ) where import Data.Sequence as D type Point = (Double,Double) type LineSegment = (Point,Point) distance :: Point -> Point -> Double distance (x1,y1) (x2,y2) = sqrt(((x1 - x2) ^ 2) + ((y1 - y2) ^ 2)) -- http://paulbourke.net/geometry/pointlineplane/DistancePoint.java perpendicularDistance :: Point -> LineSegment -> Double perpendicularDistance p@(pX, pY) (a@(aX, aY), b@(bX, bY)) | a == b = distance p a | u < 0 = distance p a | u > 1 = distance p b | otherwise = distance p (aX + u * deltaX, aY + u * deltaY) where (deltaX, deltaY) = (bX - aX, bY - aY) u = ((pX - aX) * deltaX + (pY - aY) * deltaY) / (deltaX * deltaX + deltaY * deltaY) -- https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm douglasPeucker :: Double -> Seq Point -> Seq Point douglasPeucker epsilon points | points == D.empty = D.empty | dmax > epsilon = douglasPeucker epsilon left >< allButFirst(douglasPeucker epsilon right) | otherwise = first points <| Lib.last points <| D.empty where (left, right) = (D.take index points, D.drop (index - 1) points) (dmax, index) = splitAtMaxDistance points splitAtMaxDistance :: Seq Point -> (Double, Int) splitAtMaxDistance points = D.foldlWithIndex (\(max, index) ni a -> if cp a ls > max then (cp a ls, ni + 1) else (max, index)) (0.0, D.length points) points where ls = (first points, Lib.last points) cp = perpendicularDistance last :: Seq a -> a last (viewr -> xs :> x) = x first :: Seq a -> a first (viewl -> x :< xs) = x allButFirst :: Seq a -> Seq a allButFirst (viewl -> x :< xs) = xs -- douglasPeucker 1.0 (fromList [(0.0,0.0),(1.0,0.1), (2.0,-0.1),(3.0,5.0), (4.0,6.0),(5.0,7.0), (6.0,8.1),(7.0,9.0), (8.0,9.0),(9.0,9.0)]) -- fromList [(0.0,0.0),(2.0,-0.1),(3.0,5.0),(7.0,9.0),(9.0,9.0)] someFunc :: IO () someFunc = putStrLn "someFunc"
newmana/simplify
src/Lib.hs
bsd-3-clause
2,067
0
13
444
761
409
352
42
2
import qualified Data.List is_int x = x == fromInteger (round x) calc_min_path :: Integer -> Integer -> Integer -> Double calc_min_path w l h = (sqrt . fromInteger . minimum) [ l^2 + (w+h)^2, w^2 + (l+h)^2, h^2 + (l+w)^2] calc_n_int_min_paths_up_to :: Integer -> Integer calc_n_int_min_paths_up_to m = (toInteger . length) $ filter is_int [calc_min_path w l h | w <- [1..m] , l <- [w..m] , h <- [l..m]] add_new_m :: Integer -> Integer -> Integer add_new_m m m_minus_one_value = m_minus_one_value + ((toInteger . length) $ filter is_int min_paths) where min_paths = [calc_min_path w l h | w <- [1..m], l <- [w..m], h <- [m]] subtract_new_m :: Integer -> Integer -> Integer subtract_new_m m m_plus_one_value = m_plus_one_value - ((toInteger . length) $ filter is_int min_paths) where min_paths = [calc_min_path w l h | w <- [1..(m+1)], l <- [w..(m+1)], h <- [m+1]] add_new_m_pow_2 :: Integer -> Integer add_new_m_pow_2 m = (toInteger . length) $ filter is_int min_paths where min_paths = [calc_min_path w l h | h <- [((m `div` 2) + 1)..m], w <- [1..h], l <- [w..h]] add_new_m_given_lower_m :: Integer -> Integer -> Integer add_new_m_given_lower_m m lower_m = (toInteger . length) $ filter is_int min_paths where min_paths = [calc_min_path w l h | h <- [(lower_m + 1)..m], w <- [1..h], l <- [w..h]] bsearch :: Integer -> Integer -> Integer -> Integer -> Integer -> [Integer] bsearch lb m ub bound lb_num_paths = case n_paths `compare` bound of LT -> case n_paths_succ `compare` bound of LT -> m : (bsearch (m+1) case_lt_m ub bound n_paths_succ) EQ -> [m + 2] GT -> [m + 1] EQ -> [m + 1] GT -> m : (bsearch lb case_gt_m m bound lb_num_paths) where n_paths = lb_num_paths + (add_new_m_given_lower_m m lb) n_paths_succ = (add_new_m (m+1) n_paths) case_lt_m = (m + ub) `div` 2 case_gt_m = (lb + m) `div` 2 initial_ms = map (2^) [0..] n_paths = scanl1 (+) $ map add_new_m_pow_2 initial_ms n_paths_with_ms = zipWith (\m -> \x -> (m, x)) initial_ms n_paths bound = 1000000 --first_m_over = (\(Just x) -> fst x) (Data.List.find -- (\(m, x) -> x > bound) -- n_paths_with_ms) first_m_over = 2048 -- calculated via above formula ub = first_m_over lb = first_m_over `div` 2 curr_m = (ub + lb) `div` 2 sought = bsearch lb curr_m ub bound (calc_n_int_min_paths_up_to lb) main = do (putStrLn . show) sought
bgwines/project-euler
src/solved/problem86.hs
bsd-3-clause
2,525
0
15
630
1,038
561
477
55
5
{-# LANGUAGE UnicodeSyntax #-} module Shake.It.Rust ( module Rust ) where import Shake.It.Rust.Cargo as Rust
Heather/Shake.it.off
src/Shake/It/Rust.hs
bsd-3-clause
125
0
4
31
23
17
6
4
0
{-# LANGUAGE OverloadedLists #-} {-# LANGUAGE TemplateHaskell #-} module Test.Examples.IArraySpec ( spec ) where import Test.Hspec (Spec, describe, it) import Test.QuickCheck (NonNegative (..), Property, Small (..), property, (==>)) import Universum import Test.Arbitrary () import Test.Execution (describeExecWays, (>-*->)) import Test.Util (VerySmall (..)) import Toy.Base import Toy.Execution (ExecWay (..), Executable, TranslateToSM, defCompileX86, transShow, translateLang, (<~~>)) import Toy.Exp import Toy.Lang (Stmt (..)) import qualified Toy.Lang as L spec :: Spec spec = do let ways :: forall l. (Executable l, Show l, TranslateToSM l) => [ExecWay l] ways = [ Ex transShow , Ex translateLang , Ex $ translateLang <~~> defCompileX86 ] describeExecWays ways $ \way -> do describe "examples" $ do describe "arrays" $ do it "allocation" $ property $ arrayAllocTest way it "allocation of two arrays subsequently" $ property $ arrayAlloc2Test way it "arrlen" $ property $ arrayLengthTest way it "simple" $ property $ arraySimpleTest way it "safe store" $ property $ safeStoreTest way it "deep" $ property $ arrayDeepTest way it "long nested" $ property $ arrayLongNestedTest way it "set gc" $ property $ arraySetGcTest way describeExecWays ways $ \way -> do describe "examples" $ do describe "arrays" $ do describe "funs" $ do it "array argument" $ arrayArgTest way it "array return" $ arrayReturnTest way arrayAllocTest :: ExecWay Stmt -> Property arrayAllocTest = sample & [] >-*-> [] where sample = "a" `L.storeArrayS` [] arrayAlloc2Test :: ExecWay Stmt -> Property arrayAlloc2Test = sample & [] >-*-> [] where sample = mconcat . replicate 2 $ "a" `L.storeArrayS` [] arrayLengthTest :: ExecWay Stmt -> (NonNegative (Small Value)) -> Property arrayLengthTest way (NonNegative (Small k)) = sample & [] >-*-> [k] $ way where sample = L.writeS $ FunE "arrlen" [ArrayUninitE $ fromIntegral k] arraySimpleTest :: ExecWay Stmt -> (NonNegative (Small Value)) -> Property arraySimpleTest way (NonNegative (Small k)) = k `elem` range ==> ([k] >-*-> [k]) sample way where sample = mconcat [ "a" `L.storeArrayS` (ValueE <$> range) , "i" := readE , L.writeS ("a" !!: "i") ] range = [0 .. 5] safeStoreTest :: ExecWay Stmt -> Property safeStoreTest = sample & [] >-*-> [11] where sample = mconcat [ "a" `L.storeArrayS` [11] , "a" := "a" , L.writeS ("a" !!: 0) ] arrayDeepTest :: ExecWay Stmt -> NonNegative (VerySmall Value) -> NonNegative (VerySmall Value) -> Property arrayDeepTest way (NonNegative (VerySmall k1)) (NonNegative (VerySmall k2)) = k1 == k2 ==> ([] >-*-> [7]) sample way where sample = mconcat [ "a" := 7 , mconcat . replicate (fromIntegral k1) $ -- {{{... 1 ...}}} ("a" :=) `L.arrayS` ["a"] , L.forS ("i" := 0, "i" <: ValueE k2, "i" := "i" + 1) $ "a" := "a" !!: 0 , L.writeS "a" ] arrayLongNestedTest :: ExecWay Stmt -> ([Value], [Value]) -> Property arrayLongNestedTest way (vs0, vs1) = sample & [] >-*-> [100500] $ way where sample = mconcat [ "a0" `L.storeArrayS` (ValueE <$> vs0) , "a1" `L.storeArrayS` (ValueE <$> vs1) , "a" `L.storeArrayS` ["a0", "a1"] , L.writeS 100500 ] arraySetGcTest :: ExecWay Stmt -> Property arraySetGcTest = sample & [] >-*-> [] where sample = mconcat [ "a0" `L.storeArrayS` (ValueE <$> [1]) , "a0_" `L.storeArrayS` (ValueE <$> [2]) , "a" `L.storeArrayS` ["a0"] , ArrayAssign "a" 0 "a0_" ] arrayArgTest :: ExecWay L.Program -> Property arrayArgTest = sample & [] >-*-> [5] where fun = ("lol", (FunSign "lol" ["x"], L.writeS $ ArrayAccessE "x" 0)) sample = L.Program [fun] $ mconcat [ "a" `L.storeArrayS` [5] , L.funCallS "lol" ["a"] ] arrayReturnTest :: ExecWay L.Program -> Property arrayReturnTest = sample & [] >-*-> [7] where fun = ("lol", (FunSign "lol" [], L.Return `L.arrayS` [7])) sample = L.Program [fun] $ mconcat [ L.writeS $ FunE "lol" [] `ArrayAccessE` 0 ]
Martoon-00/toy-compiler
test/Test/Examples/IArraySpec.hs
bsd-3-clause
4,920
0
21
1,716
1,577
845
732
-1
-1
-- | -- Module : Crypto.Hash.MD2 -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- -- module containing the binding functions to work with the -- MD2 cryptographic hash. -- {-# LANGUAGE ForeignFunctionInterface #-} module Crypto.Hash.MD2 ( MD2 (..) ) where import Crypto.Hash.Types import Foreign.Ptr (Ptr) import Data.Word (Word8, Word32) -- | MD2 cryptographic hash algorithm data MD2 = MD2 deriving (Show) instance HashAlgorithm MD2 where hashBlockSize _ = 16 hashDigestSize _ = 16 hashInternalContextSize _ = 96 hashInternalInit = c_md2_init hashInternalUpdate = c_md2_update hashInternalFinalize = c_md2_finalize foreign import ccall unsafe "cryptonite_md2_init" c_md2_init :: Ptr (Context a)-> IO () foreign import ccall "cryptonite_md2_update" c_md2_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO () foreign import ccall unsafe "cryptonite_md2_finalize" c_md2_finalize :: Ptr (Context a) -> Ptr (Digest a) -> IO ()
nomeata/cryptonite
Crypto/Hash/MD2.hs
bsd-3-clause
1,139
0
10
271
236
132
104
20
0
module LibrarySpec where import qualified Data.Matrix as Mx import qualified Data.Vector as Vec import Library import Test.Hspec suite :: SpecWith () suite = describe "Library" $ do it "compares 0.1 + 0.2 = 0.3" $ nearZero (0.3 - (0.1 + 0.2)) `shouldBe` True it "finds correct L∞ norm of (0, -5, 3)" $ lInftyNorm (Vec.fromList [0, -5, 3]) `shouldBe` 5 it "finds correct L∞ norm of (-1, 3)" $ lInftyNorm (Vec.fromList [-1, 3]) `shouldBe` 3 it "find correct L∞ unit vector of (0, 5)" $ toLInftyNormUnit (Vec.fromList [0, 5]) `shouldBe` Vec.fromList [0, 1] it "find correct L∞ unit vector of (3, -5)" $ toLInftyNormUnit (Vec.fromList [3, -5]) `shouldBe` Vec.fromList [0.6, -1] it "multiplies {{3, 4}, {2, 8}} by (1, 2)" $ Mx.fromLists [[3, 4], [2, 8]] `mulMxByVec` Vec.fromList [1, 2] `shouldBe` Vec.fromList [11, 18]
hrsrashid/nummet
tests/LibrarySpec.hs
bsd-3-clause
913
0
14
224
315
172
143
20
1
{-# LANGUAGE FlexibleInstances #-} {-| Module : $Header$ CopyRight : (c) 8c6794b6, 2011, 2012 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable Benchmark for comparing FFT with repa-fftw to repa-algorithms. -} module Main where import Control.DeepSeq (NFData(..)) import Data.Complex import System.Random import Criterion.Main import Data.Array.Repa ((:.)(..), Array, U, DIM1, Z(..)) import Data.Array.Repa.Repr.ForeignPtr (F) import qualified Data.Array.Repa as R import qualified Data.Array.Repa.Eval as Eval import qualified Data.Array.Repa.Algorithms.FFT as FFT import qualified Data.Array.Repa.FFTW as FFTW type RFFTArr = Array U DIM1 (Double, Double) main :: IO () main = do rs <- randomRs (0,1) `fmap` newStdGen is <- randomRs (0,1) `fmap` newStdGen let bench_fft n = let mkarr ks = Eval.fromList (Z:.n) $ take n ks ts = R.fromListUnboxed (Z:.n) $ take n $ zip rs is cs = mkarr $ zipWith (:+) rs is ra = FFT.fft1dP FFT.Forward :: RFFTArr -> IO RFFTArr in ts `seq` cs `seq` bgroup ("n="++show n) [ bench "repa-algorithms" (nfIO (ra ts)) , bench "repa-fftw" (nf FFTW.fft cs) ] defaultMain $ map (\k -> bench_fft (2^k)) [9..13::Int] instance NFData (Array U DIM1 (Double, Double)) where rnf arr = arr `R.deepSeqArray` () instance NFData (Array F DIM1 (Complex Double)) where rnf arr = arr `R.deepSeqArray` ()
8c6794b6/repa-fftw
exec/bench.hs
bsd-3-clause
1,499
0
19
344
506
287
219
31
1
module CradleSpec where import Control.Applicative import Data.List (isSuffixOf) import Language.Haskell.GhcMod.Cradle import Language.Haskell.GhcMod.Types import System.Directory (canonicalizePath,getCurrentDirectory) import System.FilePath ((</>), pathSeparator) import Test.Hspec import Dir spec :: Spec spec = do describe "findCradle" $ do it "returns the current directory" $ do withDirectory_ "/" $ do curDir <- stripLastDot <$> canonicalizePath "/" res <- findCradle res `shouldBe` Cradle { cradleCurrentDir = curDir , cradleRootDir = curDir , cradleCabalFile = Nothing , cradlePkgDbStack = [GlobalDb] } it "finds a cabal file and a sandbox" $ do cwd <- getCurrentDirectory withDirectory "test/data/subdir1/subdir2" $ \dir -> do res <- relativeCradle dir <$> findCradle res `shouldBe` Cradle { cradleCurrentDir = "test" </> "data" </> "subdir1" </> "subdir2" , cradleRootDir = "test" </> "data" , cradleCabalFile = Just ("test" </> "data" </> "cabalapi.cabal") , cradlePkgDbStack = [GlobalDb, PackageDb (cwd </> "test/data/.cabal-sandbox/i386-osx-ghc-7.6.3-packages.conf.d")] } it "works even if a sandbox config file is broken" $ do withDirectory "test/data/broken-sandbox" $ \dir -> do res <- relativeCradle dir <$> findCradle res `shouldBe` Cradle { cradleCurrentDir = "test" </> "data" </> "broken-sandbox" , cradleRootDir = "test" </> "data" </> "broken-sandbox" , cradleCabalFile = Just ("test" </> "data" </> "broken-sandbox" </> "dummy.cabal") , cradlePkgDbStack = [GlobalDb, UserDb] } relativeCradle :: FilePath -> Cradle -> Cradle relativeCradle dir cradle = cradle { cradleCurrentDir = toRelativeDir dir $ cradleCurrentDir cradle , cradleRootDir = toRelativeDir dir $ cradleRootDir cradle , cradleCabalFile = toRelativeDir dir <$> cradleCabalFile cradle } -- Work around GHC 7.2.2 where `canonicalizePath "/"` returns "/.". stripLastDot :: FilePath -> FilePath stripLastDot path | (pathSeparator:'.':"") `isSuffixOf` path = init path | otherwise = path
carlohamalainen/ghc-mod
test/CradleSpec.hs
bsd-3-clause
2,487
0
24
776
535
286
249
47
1
-- | This module provides automatic differentiation for Quantities. {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Numeric.Units.Dimensional.AD (FAD, diff, Lift (lift), undim, todim) where import Numeric.Units.Dimensional (Dimensional (Dimensional), Quantity, type (/)) import Numeric.Units.Dimensional.Coercion import Numeric.AD (AD, Mode, auto, Scalar) import qualified Numeric.AD (diff) import Numeric.AD.Mode.Forward (Forward) -- | Unwrap a Dimensional's numeric representation. undim :: Quantity d a -> a undim = coerce todim :: a -> Quantity d a todim = coerce type FAD tag a = AD tag (Forward a) -- | @diff f x@ computes the derivative of the function @f(x)@ for the -- given value of @x@. diff :: Num a => (forall tag. Quantity d1 (FAD tag a) -> Quantity d2 (FAD tag a)) -> Quantity d1 a -> Quantity ((/) d2 d1) a diff f = todim . Numeric.AD.diff (undim . f . todim) . undim -- | Class to provide 'Numeric.AD.lift'ing of constant data structures -- (data structures with numeric constants used in a differentiated -- function). class Lift w where -- | Embed a constant data structure. lift :: (Mode t) => w (Scalar t) -> w t instance Lift (Quantity d) where lift = todim . auto . undim
bjornbm/dimensional-experimental
src/Numeric/Units/Dimensional/AD.hs
bsd-3-clause
1,353
0
12
236
350
202
148
-1
-1
----------------------------------------------------------------------------- -- Kind: Kinds -- -- Part of `Typing Haskell in Haskell', version of November 23, 2000 -- Copyright (c) Mark P Jones and the Oregon Graduate Institute -- of Science and Technology, 1999-2000 -- -- This program is distributed as Free Software under the terms -- in the file "License" that is included in the distribution -- of this software, copies of which may be obtained from: -- http://www.cse.ogi.edu/~mpj/thih/ -- ----------------------------------------------------------------------------- module Kind where import PPrint data Kind = Star | Kfun Kind Kind deriving Eq instance PPrint Kind where pprint = ppkind 0 parPprint = ppkind 10 ppkind :: Int -> Kind -> Doc ppkind d Star = text "Star" ppkind d (Kfun l r) = ppParen (d>=10) (text "Kfun" <+> ppkind 10 l <+> ppkind 0 r) -----------------------------------------------------------------------------
elben/typing-haskell-in-haskell
Kind.hs
bsd-3-clause
1,053
0
9
246
142
80
62
11
1
{-# LANGUAGE Rank2Types, TypeFamilies, FlexibleContexts, UndecidableInstances #-} import Data.Reflection -- from reflection import Data.Monoid -- from base import Data.Proxy -- from tagged -- | Values in our dynamically constructed monoid over 'a' newtype M a s = M { runM :: a } deriving (Eq,Ord) -- | A dictionary describing the contents of a monoid data Monoid_ a = Monoid_ { mappend_ :: a -> a -> a, mempty_ :: a } instance Reifies s (Monoid_ a) => Monoid (M a s) where mappend a b = M $ mappend_ (reflect a) (runM a) (runM b) mempty = a where a = M $ mempty_ (reflect a) -- > ghci> withMonoid (+) 0 $ mempty <> M 2 -- > 2 withMonoid :: (a -> a -> a) -> a -> (forall s. Reifies s (Monoid_ a) => M a s) -> a withMonoid f z v = reify (Monoid_ f z) (runM . asProxyOf v) asProxyOf :: f s -> Proxy s -> f s asProxyOf a _ = a
ehird/reflection
examples/Monoid.hs
bsd-3-clause
849
0
13
196
298
160
138
13
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Test interaction between parsing output and logstash module Logstash where import Control.Monad import Control.Monad.Logger import Control.Monad.Reader import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HMap import Data.Monoid import Data.Text ( Text ) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Logging import NejlaCommon import Shelly import Test.Hspec.Expectations import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.TH -- Set the default string type to Text so we don't get ambiguity errors default ( Text ) exampleInput :: Text exampleInput = "[Debug#test] test123\n[Debug#test] test345\n" logstashConfNames :: [Text] logstashConfNames = [ "1-input-stdin.conf", "2-filter-parse-logs.conf", "3-output-stdout.conf" ] mkLogsstashConfPaths :: Text -> Text -> (Text, Text) mkLogsstashConfPaths pwd name = (pwd <> "/tests/logstash/conf.d/" <> name, "/etc/logstash/conf.d/" <> name) confVolume :: Text -> Text -> [Text] confVolume pwd name = [ "-v" , let (lPath, dPath) = mkLogsstashConfPaths pwd name in lPath <> ":" <> dPath ] checkConfFiles :: Sh () checkConfFiles = do workdir <- toTextIgnore <$> pwd forM_ logstashConfNames $ \name -> do let (path, _) = mkLogsstashConfPaths workdir name unlessM (test_f $ fromText path) . terror $ "File" <> path <> " does not exist" docker :: Text -> [Text] -> Sh Text docker cmnd args = command "docker" [ cmnd ] args logstash :: [Text] -> Sh Text logstash parameters = do workdir <- toTextIgnore <$> pwd docker "run" $ concat [ [ "--rm", "-i" ] , concat $ confVolume workdir <$> logstashConfNames , [ "elk_logstash", "logstash", "-f", "/etc/logstash/conf.d" ] , parameters ] runLogstash :: MonadIO m => IORefLogger a -> m [Text] runLogstash f = shelly . silently $ do checkConfFiles logs <- liftIO $ captureLogs f setStdin . Text.unlines $ Text.decodeUtf8 <$> logs out <- logstash [ "-w", "1", "--quiet", "-l", "/dev/null" ] stripped <- case Text.stripPrefix "Sending logstash logs to /dev/null.\n" out of Nothing -> terror "Expected output prefix \ \ \"Sending logstash logs to /dev/null.\\n\"" Just s -> return s return $ splitLines stripped where splitLines lines = case Text.breakOn "}{" lines of (rest, "") -> [ rest ] (first, last) -> (first <> "}") : splitLines (Text.drop 1 last) case_logstash :: IO () case_logstash = do res <- runLogstash $ do logEvent logTest1 logWarnNS "database" "foo" let rows = Aeson.decode . BSL.fromStrict . Text.encodeUtf8 <$> res case rows of [ Just (Aeson.Object row1), Just (Aeson.Object row2) ] -> do withRow row1 $ do "event" `shouldDecodeTo` ("test" :: Text) "time" `shouldDecodeTo` log1TestTime "level" `shouldDecodeTo` (5 :: Int) "foo" `shouldDecodeTo` False "bar" `shouldDecodeTo` True "parsed_json" `shouldDecodeTo` True withRow row2 $ do "type" `shouldDecodeTo` ("logs" :: Text) "component" `shouldDecodeTo` ("database" :: Text) "level" `shouldDecodeTo` (4 :: Int) "message" `shouldDecodeTo` ("foo" :: Text) _ -> assertFailure $ "Expected 1 row, instead got " <> unlines (Text.unpack <$> res) where shouldDecodeTo x y = ReaderT $ \o -> case HMap.lookup x o of Nothing -> assertFailure $ "could not find element" <> show x Just v -> case Aeson.fromJSON v of Aeson.Error e -> assertFailure $ "Could not decode " <> show x <> " because " <> e Aeson.Success v -> v `shouldBe` y withRow row m = runReaderT m row tests :: TestTree tests = $testGroupGenerator
nejla/nejla-common
tests/Logstash.hs
bsd-3-clause
4,103
0
18
1,100
1,127
599
528
96
4
{-# LANGUAGE StandaloneDeriving,DeriveFunctor #-} module Main where import GameDSL hiding (Rule,Action) import qualified GameDSL as GameDSL (Rule,Action) import Graphics.Gloss import Control.Monad (guard) data Tag = Selected | Stone deriving instance Eq Tag deriving instance Ord Tag deriving instance Show Tag data Attribute = XPosition | YPosition deriving instance Eq Attribute deriving instance Ord Attribute deriving instance Show Attribute type Rule = GameDSL.Rule Tag Attribute type Action = GameDSL.Action Tag Attribute move :: Rule move = do selected <- entityTagged Selected x <- getAttribute XPosition selected y <- getAttribute YPosition selected (dx,dy) <- for [(1,0),(-1,0),(0,1),(0,-1)] let (nx,ny) = (x + dx, y + dy) (tx,ty) = (nx + dx, ny + dy) other <- stoneAt nx ny ensureNot (stoneAt tx ty) return (trigger (clickInRect (fieldRect tx ty) (do delete other setAttribute XPosition selected tx setAttribute YPosition selected ty))) stoneAt :: Integer -> Integer -> Query Tag Attribute Entity stoneAt x y = do stone <- entityTagged Stone x' <- getAttribute XPosition stone y' <- getAttribute YPosition stone guard (x == x') guard (y == y') return stone select :: Rule select = do stone <- entityTagged Stone x <- getAttribute XPosition stone y <- getAttribute YPosition stone selected <- entityTagged Selected return (trigger (clickInRect (fieldRect x y) (do unsetTag Selected selected setTag Selected stone))) setupBoard :: Action () setupBoard = do mapM_ (uncurry newStone) ( [(x,y) | x <- [-1,0,1], y <- [-1,0,1], not (x == 0 && y == 0)] ++ [(x,y) | x <- [-1,0,1], y <- [2,3]] ++ [(x,y) | x <- [-1,0,1], y <- [-2,-3]] ++ [(x,y) | x <- [2,3], y <- [-1,0,1]] ++ [(x,y) | x <- [-2,-3], y <- [-1,0,1]]) setTag Selected 0 newStone :: Integer -> Integer -> Action () newStone x y = do stone <- new setTag Stone stone setAttribute XPosition stone x setAttribute YPosition stone y renderStone :: Rule renderStone = do stone <- entityTagged Stone x <- getAttribute XPosition stone y <- getAttribute YPosition stone return (draw (translate (fieldCoordinate x) (fieldCoordinate y) (circleSolid 20))) renderSelected :: Rule renderSelected = do selected <- entityTagged Selected x <- getAttribute XPosition selected y <- getAttribute YPosition selected return (draw (translate (fieldCoordinate x) (fieldCoordinate y) (color red (circleSolid 18)))) fieldRect :: Integer -> Integer -> Rect fieldRect x y = Rect (fieldCoordinate x) (fieldCoordinate y) 40 40 fieldCoordinate :: Integer -> Float fieldCoordinate x = fromIntegral x * 40 main :: IO () main = runGame setupBoard [select,move,renderStone,renderSelected]
phischu/game-dsl
peg-solitaire/Main.hs
bsd-3-clause
2,856
0
19
644
1,216
622
594
80
1
{-# LANGUAGE FlexibleInstances #-} -- Algorithm for tiling the diagram with diamond calissons. module Hexagrid.Tiling where import Control.Arrow (first, (&&&)) import Core.Function import Core.Math (l1dist) import Data.Color import Data.Entropy import qualified Data.IntMap as M import qualified Data.IntSet as IntSet import Data.List (foldl') import Data.List (nub) import Data.Maybe (isJust, fromJust) import Data.Monoid (Sum(Sum), getSum) import Data.MapUtil (Map, foldl1WithKey, getValues) import qualified Debug.Trace as T import Diagrams.Prelude (blue, green, red) import Data.BinarySearch (Binary, insert, remove, search, get, emptyBinary, binarySize) import Hexagrid.Grid import Hexagrid.Hexacycle import Hexagrid.Path import Hexagrid.TriangleCell -- fixme improve these names mpget k pToC = mget (posToInt k) (positionToColorMap pToC) mpmget k posIntMap = mget (posToInt k) posIntMap mpinsert k v pToC = M.insert (posToInt k) v (positionToColorMap pToC) mpminsert k v posIntMap = M.insert (posToInt k) v posIntMap type PositionToColorMap = Map ColorCode data Tiling = Tiling { tilingRadius :: Int, -- easier to store than recompute when needed. -- colors induced by tiling (the pairs of triangles in a calisson is not explicitly stored) positionToColorMap :: PositionToColorMap, -- "upper left corners" of unit-hexagons populated by 3 different tiles, which can be rotated/mirrored -- to generate a different valid tiling tilingUsableHexagons :: PositionSet } deriving (Show, Read) class PositionSetClass a where instance PositionSetClass IntSet.IntSet where instance PositionSetClass (Binary Position) where type PositionSet = IntSet.IntSet -- Binary Position --fixme typeclass for this switcher and implementations getImpl intSet bsearch = intSet -- bseach asBinary = getImpl undefined id asIntSet = getImpl id undefined -- fixme O(n) traversal to get element -- Use a "Binary (Measure (MinMax Position))" to maintain a tree of these. -- getNth :: PositionSet -> Int -> Int getNth tilingUsableHexagons n = getImpl ((IntSet.toList tilingUsableHexagons) !! n) (posToInt $ fromJust $ get (asBinary tilingUsableHexagons) n) insertToPositionSet :: Int -> PositionSet-> PositionSet insertToPositionSet = getImpl IntSet.insert (insert . intToPos) removeFromPositionSet :: Int -> PositionSet-> PositionSet removeFromPositionSet = getImpl IntSet.delete (remove . intToPos) emptyPositionSet :: PositionSet emptyPositionSet = getImpl IntSet.empty (emptyBinary :: Binary Position) size = getImpl IntSet.size (getSum . binarySize) initialTiling spec = let radius = (gridRadius spec) in let pToCM = mkCanonicalTiling (mkCornerColors radius ) (orientations spec) in (Tiling radius pToCM (mkUsableHexagons (orientations spec) pToCM)) mkUsableHexagons :: Map TriangleOrientation -> PositionToColorMap -> PositionSet mkUsableHexagons theOrientations pToCM = -- T.trace "mkUsableHexagons" foldl' (flip insertToPositionSet) emptyPositionSet $ filter (\posInt -> -- T.trace ("mkUsableHexagons: checking usability of hexagon: " ++ show (intToPos posInt)) $ let orientation = mget posInt theOrientations in isJust (getHexacycleIfUsable orientation (intToPos posInt) pToCM)) (IntSet.toList $ M.keysSet pToCM) -- A Hexacycle's position is just the position of its top-left corner. type HexacyclePosition = Position posToIntFlattenAndDedup :: [[Position]] -> [Int] posToIntFlattenAndDedup = IntSet.toList . foldl' (\set poss -> foldl' (\set pos -> IntSet.insert (posToInt pos) set) set poss) IntSet.empty updateUsableHexagons :: Map TriangleOrientation -> PositionToColorMap -> PositionSet -> [HexacyclePosition] -> PositionSet updateUsableHexagons theOrientations newColorization oldUsableHexagons changedPositions = let getOverlappingHexacycles pos = overlappingHexacycles pos (mpmget pos theOrientations) newColorization in let overlappingHexacylePosInts = posToIntFlattenAndDedup (map getOverlappingHexacycles changedPositions) in foldl' go oldUsableHexagons overlappingHexacylePosInts where go oldUsableHexagons posInt = -- T.trace ("updateUsableHexagons: checking usability of hexagon: " ++ show (intToPos posInt)) $ let update = case getHexacycleIfUsable (mget posInt theOrientations) (intToPos posInt) newColorization of Nothing -> -- T.trace ("remove unusable hexagon: " ++ show (intToPos posInt)) $ removeFromPositionSet Just _ -> -- T.trace ("add usable hexagon: " ++ show (intToPos posInt)) $ insertToPositionSet in update posInt oldUsableHexagons -- validPositions for its keys overlappingHexacycles :: Position -> TriangleOrientation -> Map a -> [Position] overlappingHexacycles pos orientation validPositions = let paths = case orientation of -- paths to hexacycle-positions determined by inspecting a diagram PointingLeft -> [[], [blueToRed, blueToGreen], [blueToRed, greenToRed]] PointingRight -> [[greenToRed, blueToRed, blueToGreen], -- equivalent to bg,br,gr [greenToRed], [blueToGreen]] in filter (isValidPosition validPositions) (map (walk' pos) paths) -- map of positions to position's colors -- Map TriangleOrientations is used only for the keys mkCanonicalTiling :: PositionToColorMap -> Map TriangleOrientation -> PositionToColorMap mkCanonicalTiling cornerColors positionToDummy = M.fromList . map (id &&& (getNearestCornerColor cornerColors . intToPos)) $ M.keys positionToDummy -- generate map of positions to color of positions' home corner getNearestCornerColor :: PositionToColorMap -> Position -> ColorCode getNearestCornerColor cornerColors cell@(Position (row, col)) = let fcell = (row,col) in snd $ foldl1WithKey (\(nearest, ncolor) corner ccolor -> -- fixme ugh if l1dist fcell (toTuple $ intToPos corner) < l1dist fcell (toTuple $ intToPos nearest) then (corner, ccolor) else (nearest, ncolor)) cornerColors -- map of home postions to colors mkCornerColors :: Int -> PositionToColorMap mkCornerColors radius = let s = fromIntegral radius in M.fromList . map (first posToInt) $ [ (Position (-(4*s), 0) , Red) , (Position (2*s, -2*s), Green) -- todo, use `rows` instead of `size` ? , (Position (2*s, 2*s), Blue) ] getColor :: PositionToColorMap -> Position -> ColorCode getColor pToC position = mpmget position pToC applyATiling :: Spec source -> Maybe Tiling -> Tiling applyATiling spec mInitialTiling = shuffleColors spec $ case mInitialTiling of Nothing -> initialTiling spec Just tiling -> tiling -- Computes a position's color by applying a shuffle function to the "positionColors" scheme shuffleColors:: Spec source -> Tiling -> Tiling shuffleColors spec positionColors = let entropy = specPositionEntropy spec in map fst (iterate (withEntropyAndRetry (shuffleOnce spec)) (positionColors, entropy)) !! specShuffles spec -- warning! this is a "transient" method, (returns an invalid tiling!) -- caller must do work to maintain invariants! copyColorFrom :: PositionToColorMap -> (Position, Position) -> PositionToColorMap -> PositionToColorMap copyColorFrom sourcePToC (srcPos, destPos) destPToC = mpminsert destPos (mpmget srcPos sourcePToC) destPToC -- A 'shuffle' rotates a unit-hexagon a half-turn, if that would be a valid tiling (flips) -- Our convention is to use the upper-left corner as the starting-point, -- so only PointingLeft triangles are valid -- FIXME! Very few grid positions are valid -- but they are predictable. -- Build an index at start, and update it (as part of PositionToColor) shuffleOnce :: Spec source -> Int -> Tiling -> Maybe (Maybe Tiling) shuffleOnce spec entropyForCellIndex tiling = let numUsableHexagons = size (tilingUsableHexagons tiling) in case numUsableHexagons of 0 -> T.trace ("ERROR!: No usable hexagons to shuffle colors!") $ Nothing _ -> let theOrientations = orientations spec in -- todo: pos<->int conversion happens and roundtrip. better to normalize on 'int', for performance let hexagonIndex = entropyForCellIndex `mod` numUsableHexagons in let posInt = getNth (tilingUsableHexagons tiling) hexagonIndex in let pos = intToPos posInt in -- T.trace ("shuffleOnce: " ++ show cellIndex) $ let orientation = mget posInt theOrientations in let pToCM = (positionToColorMap tiling) in -- rendundant check oh usability, but good for validating computations case getHexacycleIfUsable orientation pos pToCM of Just hexacycle -> -- T.trace ("yep: " ++ show pos) $ let hexagonPositions = take 6 hexacycle in let hexagonOpposites = take 6 (zip hexacycle (drop 3 hexacycle)) in let prevUsableHexagons = (tilingUsableHexagons tiling) in let newPToCM = (foldl' (flip ($)) pToCM (map (copyColorFrom pToCM) hexagonOpposites)) in Just $ Just $ Tiling (gridRadius spec) newPToCM (updateUsableHexagons theOrientations newPToCM prevUsableHexagons hexagonPositions) Nothing -> T.trace ("SHOULD NEVER HAPPEN: unsable hexacycle in hexacycle-cache: " ++ show pos) $ Just Nothing getHexacycleIfUsable :: TriangleOrientation -> HexacyclePosition -> PositionToColorMap -> Maybe [Position] getHexacycleIfUsable orientation pos pToC = -- determine which triangles to include in unit-hexagon -- if on a hexagon with 3 diff color, reflect colors across center of hexagon. -- T.trace ("orient: " ++ show orientation) $ let hexacycle = cyclePathPositions orientation pos in if (orientation == PointingLeft) && usableCycle hexacycle pToC then Just hexacycle else Nothing -- warning: cyclic! usableCycle :: [Position] -> PositionToColorMap -> Bool usableCycle ps ptoc = -- fixme: inefficient list access let colorAtPos pos = mpmget pos ptoc in let colorAt i = colorAtPos (ps !! i) in let hexagon = take 6 ps in let hexagonColors = map colorAtPos hexagon in let colorNub = nub hexagonColors in -- T.trace ("hexagon : " ++ show hexagon) $ all (isValidPosition ptoc) hexagon -- Our "upper-left corner, PointingLeft" convention means that only 'red' and 'blue' corners are valid && ( -- T.trace ("hexagonColors : " ++ show hexagonColors) $ (hexagonColors !! 0) `elem` [Red, Blue]) && wellCycledColors hexagonColors -- adjacent colors are same/diff/... around cycle wellCycledColors :: Eq a => [a] -> Bool -- [a] must be cyclic! -- 5/tail because the first pairing is checked to establish parity. wellCycledColors (x1:x2:xs) = wellCycledColors' 5 (tail (cycle xs)) (x1 == x2) --FIXME wellCycledColors' 0 xs _ = True wellCycledColors' n (x1:x2:xs) parity = ((x1 == x2) == not parity) && wellCycledColors' (n-1) (x2:xs) (not parity) isValidPosition :: Map a -> Position -> Bool isValidPosition validPositionSet p = isJust $ M.lookup (posToInt p) validPositionSet
misterbeebee/calisson-hs
src/Hexagrid/Tiling.hs
bsd-3-clause
11,889
0
40
2,897
2,555
1,341
1,214
-1
-1
module Main where import Control.Applicative import Control.Monad import qualified System.Environment import Path import Run import qualified Paths_runstaskell getBinDir :: IO (Path Bin) getBinDir = Path <$> Paths_runstaskell.getBinDir getProgName :: IO (Path ProgName) getProgName = Path <$> System.Environment.getProgName getDataDir :: IO (Path DataDir) getDataDir = Path <$> Paths_runstaskell.getDataDir main :: IO () main = join (run <$> getProgName <*> getBinDir <*> getDataDir)
soenkehahn/runstaskell
src/Main.hs
bsd-3-clause
532
0
9
109
139
77
62
15
1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -Wextra #-} -- Development-only muffles. {-# OPTIONS_GHC -Wno-unused-binds -Wno-unused-matches #-} -- -- Flex: a flexbox layout implementation, based on github.com/xamarin/flex, -- and https://www.w3.org/TR/css-flexbox-1/ -- -- Two caveats: -- -- 1. Order property and size callbacks are not implemented. -- 2. Initially, this is a very direct translation from C -- and it shows a lot. -- module Graphics.Flex ( -- * Language of Geo LRTB(..), left, right, top, bottom , Alignment(..) , Direction(..) , Positioning(..) , Wrapping(..) , child , walk , dump, ppItemArea, showItemArea, ppItemSize -- , Geo(..), defGeo, defGeoDiff, ppdefGeoDiff , padding , margin , absolute , justify'content , align'content , align'items , align'self , positioning , direction , wrap , grow , shrink , order , basis -- -- * Flex class , Flex(..) -- * Layout API , layout ) where import qualified Data.Text as T import ExternalImports import Graphics.Flatland -- * A language of Geo -- data LRTB a where LRTB ∷ { _left ∷ a , _right ∷ a , _top ∷ a , _bottom ∷ a } β†’ LRTB a deriving (Functor, Show) makeLenses ''LRTB instance Applicative LRTB where pure x = LRTB x x x x LRTB f0 f1 f2 f3 <*> LRTB v0 v1 v2 v3 = LRTB (f0 v0) (f1 v1) (f2 v2) (f3 v3) data Alignment where AlignAuto ∷ Alignment AlignStretch ∷ Alignment AlignCenter ∷ Alignment AlignStart ∷ Alignment AlignEnd ∷ Alignment AlignSpaceBetween ∷ Alignment AlignSpaceAround ∷ Alignment AlignSpaceEvenly ∷ Alignment deriving (Eq, Show) data Direction where DirColumn ∷ Direction DirColumnReverse ∷ Direction DirRow ∷ Direction DirRowReverse ∷ Direction deriving (Eq, Show) data Positioning where Relative ∷ Positioning Absolute ∷ Positioning deriving (Eq, Show) data Wrapping where NoWrap ∷ Wrapping Wrap ∷ Wrapping ReverseWrap ∷ Wrapping deriving (Eq, Show) data Geo where Geo ∷ { _padding ∷ LRTB Double , _margin ∷ LRTB Double , _absolute ∷ LRTB (Maybe Double) , _justify'content ∷ Alignment , _align'content ∷ Alignment , _align'items ∷ Alignment , _align'self ∷ Alignment , _positioning ∷ Positioning , _direction ∷ Direction , _wrap ∷ Wrapping , _grow ∷ Int , _shrink ∷ Int , _order ∷ Maybe Int , _basis ∷ Double } β†’ Geo deriving (Show) makeLenses ''Geo deriving instance Eq (LRTB Double) deriving instance Eq (LRTB (Maybe Double)) data GeoFieldValue = GPadding (LRTB Double) | GMargin (LRTB Double) | GAbsolute (LRTB (Maybe Double)) | GJustifyContent Alignment | GAlignContent Alignment | GAlignItems Alignment | GAlignSelf Alignment | GPositioning Positioning | GDirection Direction | GWrap Wrapping | GGrow Int | GShrink Int | GOrder (Maybe Int) | GBasis Double deriving (Show) defGeo ∷ Geo defGeo = Geo { _padding = LRTB 0 0 0 0 , _margin = LRTB 0 0 0 0 , _absolute = LRTB Nothing Nothing Nothing Nothing , _justify'content = AlignStart , _align'content = AlignStretch , _align'items = AlignStart , _align'self = AlignAuto , _positioning = Relative , _direction = DirColumn , _wrap = NoWrap , _grow = 0 , _shrink = 1 , _order = Nothing , _basis = 0 } defGeoDiff ∷ Geo β†’ [GeoFieldValue] defGeoDiff g = ( let x = _padding g in [GPadding x | x β‰’ _padding defGeo]) <> (let x = _margin g in [GMargin x | x β‰’ _margin defGeo]) <> (let x = _absolute g in [GAbsolute x | x β‰’ _absolute defGeo]) <> (let x = _justify'content g in [GJustifyContent x | x β‰’ _justify'content defGeo]) <> (let x = _align'content g in [GAlignContent x | x β‰’ _align'content defGeo]) <> (let x = _align'items g in [GAlignItems x | x β‰’ _align'items defGeo]) <> (let x = _align'self g in [GAlignSelf x | x β‰’ _align'self defGeo]) <> (let x = _positioning g in [GPositioning x | x β‰’ _positioning defGeo]) <> (let x = _direction g in [GDirection x | x β‰’ _direction defGeo]) <> (let x = _wrap g in [GWrap x | x β‰’ _wrap defGeo]) <> (let x = _grow g in [GGrow x | x β‰’ _grow defGeo]) <> (let x = _shrink g in [GShrink x | x β‰’ _shrink defGeo]) <> (let x = _order g in [GOrder x | x β‰’ _order defGeo]) <> (let x = _basis g in [GBasis x | x β‰’ _basis defGeo]) ppdefGeoDiff ∷ Geo β†’ String ppdefGeoDiff g = intercalate "." $ show <$> defGeoDiff g -- * API -- class Flex a where geo ∷ Lens' a Geo size ∷ Lens' a (Di (Maybe Double)) children ∷ Lens' a [a] area ∷ Lens' a (Area'LU Double) child ∷ Flex a β‡’ Int β†’ Traversal' a a child n = children ∘ ix n walk ∷ (Flex a, Monad m) β‡’ ([Int] β†’ a β†’ m ()) β†’ a β†’ m () walk action f = loop [0] f where loop trace f = do action trace f sequence $ zip (f^.children) [0..] <&> \(f', n) β†’ loop (n:trace) f' pure () ppItemSize ∷ Flex a β‡’ a β†’ String ppItemSize x = T.unpack ∘ renderStrict ∘ layoutCompact $ pretty'mdi $ x^.size ppItemArea ∷ Flex a β‡’ a β†’ String ppItemArea x = T.unpack ∘ renderStrict ∘ layoutCompact $ pretty'Area'Int $ x^.area showItemArea ∷ Flex a β‡’ a β†’ String showItemArea x = show $ x^.area dump ∷ (Flex a, MonadIO m) β‡’ (Flex a β‡’ a β†’ String) β†’ a β†’ m () dump ppf = walk (\trace f' β†’ liftIO $ do putStrLn $ (concat $ take (length trace - 1) (repeat " ")) <> (show $ head trace) <> " " <> ppf f') -- * Instances -- -- instance Pretty a β‡’ Pretty (a) where -- pretty = unreadable "" ∘ pretty'item -- -- * no user-serviceable parts below, except for the 'layout' function at the very bottom. -- pretty'mdouble ∷ Maybe Double β†’ Doc ann pretty'mdouble Nothing = pretty '*' pretty'mdouble (Just x) = pretty $ T.pack $ printf "%3d" (floor x ∷ Int) pretty'mdi ∷ Di (Maybe Double) β†’ Doc ann pretty'mdi (Di (V2 ma mb)) = pretty'mdouble ma <> pretty ':' <> pretty'mdouble mb pretty'item ∷ Flex a β‡’ a β†’ Doc ann pretty'item item = pretty @Text "Item size:" <> pretty'mdi (item^.size) <+> pretty'Area'Int (item^.area) item'marginLT, item'marginRB ∷ Flex a β‡’ a β†’ Vertical β†’ Reverse β†’ Double item'marginLT item Vertical Forward = item^.geo.margin.left item'marginLT item Vertical Reverse = item^.geo.margin.top item'marginLT item Horisontal Forward = item^.geo.margin.top item'marginLT item Horisontal Reverse = item^.geo.margin.left item'marginRB item Vertical Forward = item^.geo.margin.right item'marginRB item Vertical Reverse = item^.geo.margin.bottom item'marginRB item Horisontal Forward = item^.geo.margin.bottom item'marginRB item Horisontal Reverse = item^.geo.margin.right item'size ∷ Flex a β‡’ Major β†’ Lens' a Double item'size (Major axis) = area ∘ area'b ∘ size'di ∘ di'd axis item'size2 ∷ Flex a β‡’ Minor β†’ Lens' a Double item'size2 (Minor axis) = area ∘ area'b ∘ size'di ∘ di'd axis item'pos ∷ Flex a β‡’ Major β†’ Lens' a Double item'pos (Major axis) = area ∘ area'a ∘ lu'po ∘ po'd axis item'pos2 ∷ Flex a β‡’ Minor β†’ Lens' a Double item'pos2 (Minor axis) = area ∘ area'a ∘ lu'po ∘ po'd axis data Vertical = Horisontal | Vertical deriving (Eq, Show) data Reverse = Forward | Reverse deriving (Eq, Show) data LayoutLine where LayoutLine ∷ { _li'nchildren ∷ Int , _li'size ∷ Double } β†’ LayoutLine deriving (Show) makeLenses ''LayoutLine data Layout where Layout ∷ { _la'wrap ∷ Bool , _la'reverse ∷ Reverse , _la'reverse2 ∷ Reverse , _la'vertical ∷ Vertical , _la'major ∷ Major , _la'minor ∷ Minor , _la'size'dim ∷ Double -- major axis parent size , _la'align'dim ∷ Double -- minor axis parent size , _la'line'dim ∷ Double -- minor axis size , _la'flex'dim ∷ Double -- flexible part of the major axis size , _la'extra'flex'dim ∷ Double -- sizes of flexible items , _la'flex'grows ∷ Int , _la'flex'shrinks ∷ Int , _la'pos2 ∷ Double -- minor axis position , _la'lines ∷ [LayoutLine] , _la'lines'sizes ∷ Double } β†’ Layout deriving (Show) makeLenses ''Layout pretty'layout ∷ Layout β†’ Doc ann pretty'layout Layout{..} = let axes = pretty $ T.pack (show $ fromMajor _la'major) <> ":" <> T.pack (show $ fromMinor _la'minor) wrap = if _la'wrap then pretty @Text " Wrap" else mempty dir = pretty $ T.take 4 $ T.pack $ show _la'vertical revMj = pretty $ (<>) "Maj" $ T.take 4 $ T.pack $ show _la'reverse revMi = pretty $ (<>) "Min" $ T.take 4 $ T.pack $ show _la'reverse2 in pretty @Text "Layout " <> wrap <+> axes <+> dir <+> revMj <+> revMi <+> pretty ("par:" <> ppV2 (V2 _la'size'dim _la'align'dim)) <+> pretty ("chi:" <> ppV2 (V2 _la'flex'dim _la'line'dim)) <+> pretty ("efd:" <> T.pack (show _la'extra'flex'dim)) <+> pretty ("g/s:" <> ppV2 (V2 _la'flex'grows _la'flex'shrinks)) <+> pretty @Text ("pos2:") <> pretty _la'pos2 instance Pretty Layout where pretty x = pretty '#' <> angles (pretty'layout x) mkLayout ∷ Flex a β‡’ a β†’ Layout mkLayout item = let V2 width' height' = item^.area.area'b.size'di.di'v Geo{..} = item^.geo width = width' - (_padding^.left + _padding^.right) height = height' - (_padding^.top + _padding^.bottom) (,,,,,) _la'major _la'minor _la'vertical _la'reverse _la'size'dim _la'align'dim = case _direction of DirRow β†’ (Major X, Minor Y, Horisontal, Forward, width, height) DirRowReverse β†’ (Major X, Minor Y, Vertical, Reverse, width, height) DirColumn β†’ (Major Y, Minor X, Vertical, Forward, height, width) DirColumnReverse β†’ (Major Y, Minor X, Vertical, Reverse, height, width) -- NB: child order property implementation has been skipped. (,,,,) _la'flex'grows _la'flex'shrinks _la'flex'dim _la'extra'flex'dim _la'line'dim = (,,,,) 0 0 0 0 (if _la'wrap then 0 else _la'align'dim) -- XXX: βŠ₯ in original code _la'wrap = _wrap β‰’ NoWrap reverse'wrapping = _wrap ≑ ReverseWrap _la'reverse2 = if _la'wrap ∧ reverse'wrapping then Reverse else Forward _la'pos2 = case _la'wrap of True β†’ if reverse'wrapping then _la'align'dim else 0 -- XXX: βŠ₯ in original code False β†’ if _la'vertical ≑ Vertical then _padding^.left else _padding^.top _la'lines = [] _la'lines'sizes = 0 in Layout{..} layout'reset ∷ Layout β†’ Layout layout'reset l@Layout{..} = l & la'line'dim .~ (if _la'wrap then 0 else _la'align'dim) & la'flex'dim .~ _la'size'dim & la'extra'flex'dim .~ 0 & la'flex'grows .~ 0 & la'flex'shrinks .~ 0 -- | Yield (Position, Spacing) layout'align ∷ Alignment β†’ Double β†’ Int β†’ Bool β†’ Maybe (Double, Double) layout'align _ 0 _ _ = Nothing layout'align a flex'dim c d = layout'align' a flex'dim c d layout'align' ∷ Alignment β†’ Double β†’ Int β†’ Bool β†’ Maybe (Double, Double) layout'align' align flex'dim nchilds stretch'allowed | AlignStart ← align = Just $ (,) 0 0 | AlignEnd ← align = Just $ (,) flex'dim 0 | AlignCenter ← align = Just $ (,) (flex'dim / 2) 0 | AlignSpaceBetween ← align = Just $ (0,) $ if (nchilds ≑ 0) then 0 else (flex'dim / fromIntegral (nchilds - 1)) | AlignSpaceAround ← align = Just $ if (nchilds ≑ 0) then (0, 0) else let spacing = flex'dim / fromIntegral nchilds in (spacing / 2, spacing) | AlignSpaceEvenly ← align = Just $ if (nchilds ≑ 0) then (0, 0) else let spacing = flex'dim / fromIntegral (nchilds + 1) in (spacing, spacing) | AlignStretch ← align = if not stretch'allowed then Nothing else Just (0, flex'dim / fromIntegral nchilds) | AlignAuto ← align = Nothing count'relatives ∷ Flex a β‡’ [a] β†’ Int count'relatives = length ∘ filter ((≑Relative) ∘ (^.geo.positioning)) layout_items ∷ Flex a β‡’ a β†’ [a] β†’ Layout β†’ (Layout, [a]) layout_items _ [] l = (,) l [] layout_items item children l@Layout{..} = -- Determine the major axis initial position and optional spacing. let Geo{..} = item^.geo flex'dim1 = _la'flex'dim + if _la'flex'dim > 0 ∧ _la'extra'flex'dim > 0 -- If the container has a positive flexible space, let's add to it the sizes of all flexible children. then _la'extra'flex'dim else 0 (pos1, spacing1) = if _la'flex'grows ≑ 0 ∧ flex'dim1 > 0 then let may'aligned = layout'align _justify'content flex'dim1 (count'relatives children) False (pos', spacing') = flip fromMaybe may'aligned $ error "incorrect justify_content" in (, spacing') $ if _la'reverse ≑ Reverse then _la'size'dim - pos' else pos' else (,) 0 0 pos2 = if _la'reverse ≑ Reverse then pos1 - if _la'vertical ≑ Vertical then _padding^.bottom else _padding^.right else pos1 + if _la'vertical ≑ Vertical then _padding^.top else _padding^.left -- This is suspicious: line 455 in flex.c l' = (if _la'wrap ∧ _la'reverse2 ≑ Reverse -- line 454: lβ†’wrap implied by lβ†’reverse2 then l & la'pos2 -~ _la'line'dim else l) & la'flex'dim .~ flex'dim1 layout'children ∷ Flex a β‡’ Double β†’ [a] β†’ [a] β†’ (Double, [a]) layout'children pos [] acc = (,) pos (reverse acc) layout'children pos (c@((^.geo.positioning) β†’ Absolute):rest) acc = layout'children pos rest (c:acc) -- Already positioned. layout'children pos (c:rest) acc = -- Grow or shrink the major axis item size if needed. let flex'size = if | l'^.la'flex'dim > 0 ∧ c^.geo.grow β‰’ 0 β†’ (l'^.la'flex'dim) β‹… fromIntegral (c^.geo.grow) / fromIntegral (l'^.la'flex'grows) | l'^.la'flex'dim < 0 ∧ c^.geo.shrink β‰’ 0 β†’ (l'^.la'flex'dim) β‹… fromIntegral (c^.geo.shrink) / fromIntegral (l'^.la'flex'shrinks) | otherwise β†’ 0 child'size0 = if | l'^.la'flex'dim > 0 ∧ c^.geo.grow β‰’ 0 β†’ 0 | otherwise β†’ c ^. item'size _la'major c1 = c & item'size _la'major .~ child'size0 + flex'size -- Set the minor axis position (and stretch the minor axis size if needed). align'size = c1 ^. item'size2 _la'minor c'align = if c1^.geo.align'self ≑ AlignAuto then item^.geo.align'items else c1^.geo.align'self margin'LT = item'marginLT c1 _la'vertical Forward margin'RB = item'marginRB c1 _la'vertical Forward c2 = if c'align ≑ AlignStretch ∧ align'size ≑ 0 then c1 & item'size2 _la'minor .~ (l'^.la'line'dim - margin'LT - margin'RB) else c1 align'pos'Ξ΄ = if | c'align ≑ AlignEnd β†’ l'^.la'line'dim - align'size - margin'RB | c'align ≑ AlignCenter β†’ margin'LT + (l'^.la'line'dim - align'size) / 2 - margin'RB | c'align ≑ AlignStretch ∨ c'align ≑ AlignStart β†’ margin'LT | otherwise β†’ error "invalid align_self" align'pos = l'^.la'pos2 + align'pos'Ξ΄ c3 = c2 & item'pos2 _la'minor .~ align'pos -- Set the main axis position. margin'LTr = item'marginLT c3 _la'vertical Reverse margin'RBr = item'marginRB c3 _la'vertical Reverse pos' = if _la'reverse ≑ Reverse then pos - margin'RBr - c3^.item'size _la'major else pos + margin'LTr c4 = c3 & item'pos _la'major .~ pos' pos'' = if _la'reverse ≑ Reverse then pos' - spacing1 - margin'LTr else pos' + c4^.item'size _la'major + spacing1 + margin'RBr in layout'children pos'' rest $ (:acc) $ layout_item c4 children' = snd $ layout'children pos2 children [] l'' = if not _la'wrap ∨ _la'reverse2 ≑ Reverse then l' else l' & la'pos2 +~ (l'^.la'line'dim) l''' = if not _la'wrap ∨ _align'content ≑ AlignStart then l'' else l'' & la'lines %~ (LayoutLine (length children') (l''^.la'line'dim) :) & la'lines'sizes +~ l''^.la'line'dim in (,) l''' children' layout_item ∷ βˆ€ a. Flex a β‡’ a β†’ a layout_item p@((^.children) β†’ []) = p layout_item p = let cstr = p^.area.area'b assign'sizes ∷ [a] β†’ Layout β†’ [a] β†’ [a] β†’ (Layout, [a], [a]) assign'sizes [] l sized positioned = (,,) l (reverse sized) positioned assign'sizes (c@((^.geo.positioning) β†’ Absolute):rest) l@Layout{..} sized positioned = let abs'size (Just val) _ _ _ = val abs'size Nothing (Just pos1) (Just pos2) dim = dim - pos2 - pos1 abs'size _ _ _ _ = 0 abs'pos (Just pos1) _ _ _ = pos1 abs'pos Nothing (Just pos2) (Just size) dim = dim - size - pos2 abs'pos _ _ _ _ = 0 (pos, dim) = (c^.geo.absolute, c^.size) c' = c & area .~ Area (LU $ Po $ V2 (abs'pos (pos^.left) (pos^.right) (dim^.di'd X) (cstr^.size'di.di'd X)) (abs'pos (pos^.top) (pos^.bottom) (dim^.di'd Y) (cstr^.size'di.di'd Y))) (Size $ Di $ V2 (abs'size (dim^.di'd X) (pos^.left) (pos^.right) (cstr^.size'di.di'd X)) (abs'size (dim^.di'd Y) (pos^.top) (pos^.bottom) (cstr^.size'di.di'd Y))) & layout_item in assign'sizes rest l (c':sized) positioned assign'sizes (c:rest) l@Layout{..} sized positioned = let c'size = fromMaybe 0 $ partial (>0) (c^.geo.basis) <|> (c^.size.di'd (fromMajor _la'major)) c'size2 = flip fromMaybe (c^.size.di'd (fromMinor _la'minor)) (cstr^.size'di.di'd (if _la'vertical ≑ Vertical then X else Y) - item'marginLT c _la'vertical Forward - item'marginRB c _la'vertical Forward) -- NB: self_sizing callback implementation ignored (,,) sized' positioned' l' = if not _la'wrap ∨ l^.la'flex'dim β‰₯ c'size then (,,) sized positioned l else let (,) lay' positioned' = layout_items (p) (reverse sized) l in (,,) [] (positioned <> positioned') (layout'reset lay') l'' = l' & la'line'dim %~ (\line'dimβ†’ if not _la'wrap ∨ c'size2 ≀ line'dim then line'dim else c'size2) & la'flex'grows +~ c'^.geo.grow & la'flex'shrinks +~ c'^.geo.shrink & la'flex'dim -~ c'size + item'marginLT c' _la'vertical Reverse + item'marginRB c' _la'vertical Reverse & la'extra'flex'dim +~ if c'size > 0 ∧ c'^.geo.grow > 0 then c'size else 0 c' = c & item'size _la'major .~ c'size & item'size2 _la'minor .~ c'size2 in assign'sizes rest l'' (c':sized') positioned' -- 1. Assign sizes (and some of positions, if wrapping): (,,) lay sized positioned = assign'sizes (p^.children) (layout'reset $ mkLayout p) [] [] ∷ (Layout, [a], [a]) -- 2. Assign remainder of positions: (,) lay'@Layout{..} positioned' = layout_items p sized lay -- 3. Merge wrap-generated positionals & the results of remainder processing: children' = positioned <> positioned' -- 4. In wrap mode if the 'align_content' property changed from its default -- value, we need to tweak the position of each line accordingly. align'children ∷ Layout β†’ [a] β†’ [a] align'children Layout{..} cs = let flex'dim = _la'align'dim - _la'lines'sizes may'aligned = layout'align (p^.geo.align'content) flex'dim (length _la'lines) True (,) pos' spacing' = if flex'dim ≀ 0 then (,) 0 0 else flip fromMaybe may'aligned $ error "incorrect align_content" (,) pos'' old'pos = if _la'reverse2 β‰’ Reverse then (,) pos' 0 else (,) (_la'align'dim - pos') _la'align'dim line'step ∷ [LayoutLine] β†’ [a] β†’ [[a]] β†’ Double β†’ Double β†’ ([a], Double, Double) line'step [] [] acc pos old'pos = (,,) (concat $ reverse acc) pos old'pos line'step [] (u:us) _ _ _ = error $ printf "Invariant failed: %d children left unaccounted for." (length us + 1) line'step (LayoutLine{..}:ls) cs acc pos old'pos = let (,) pos' old'pos' = if _la'reverse2 β‰’ Reverse then (,) pos old'pos else (,) (pos - _li'size - spacing') (old'pos - _li'size) (,) line rest = splitAt _li'nchildren cs -- Re-position the children of this line, honoring any child alignment previously set within the line line' = line <&> \cβ†’ if c^.geo.positioning ≑ Absolute then c else c & item'pos2 _la'minor +~ pos' - old'pos' (,) pos'' old'pos'' = if _la'reverse2 ≑ Reverse then (,) pos' old'pos' else (,) (pos + _li'size + spacing') (old'pos + _li'size) in line'step ls rest (line':acc) pos'' old'pos'' in (^._1) $ line'step (reverse _la'lines) cs [] pos'' old'pos in p & children .~ if _la'wrap ∧ p^.geo.align'content β‰’ AlignStart then align'children lay' children' else children' -- | Lay out children according to their and item's properties. -- Origin is fixed to 0:0. layout ∷ Flex a β‡’ Size Double β†’ a β†’ a layout dim x = layout_item $ x & area.area'b .~ dim
deepfire/mood
src/Graphics/Flex.hs
agpl-3.0
24,940
24
31
8,899
7,176
3,796
3,380
-1
-1
#!/usr/bin/env stack -- stack runghc --package universum --package lens --package lens-aeson --package time --package cassava --package split --package text --package fmt --package directory --package filepath --package megaparsec {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ViewPatterns #-} import Universum import Unsafe import qualified Control.Lens as L import qualified Data.Aeson.Lens as L import qualified Data.Csv as CSV import Data.List (isInfixOf) import qualified Data.List.Split as Split import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import qualified Data.Text.Lazy.IO as TL import qualified Data.Time as Time import Fmt (Buildable (..), genericF) import qualified System.Directory as Dir import System.FilePath (takeFileName, (</>)) import qualified Text.Megaparsec as P import Text.Megaparsec.Text () -- Usage: Give it path to the directory with logs main :: IO () main = do [logsDir] <- getArgs logs <- readLogFiles logsDir putStrLn . TL.decodeUtf8 $ CSV.encodeDefaultOrderedByName (concatMap processLog logs) type Log = (FilePath, (LText, LText), LText) -- | Each tuple contains directory, client.info & payload.json, and log. readLogFiles :: FilePath -> IO [Log] readLogFiles dir = do ds <- map (dir </>) <$> Dir.listDirectory dir fmap catMaybes $ mapM readLogDir ds readLogDir :: FilePath -> IO (Maybe Log) readLogDir dir = do fs <- Dir.listDirectory dir clientInfo <- if "client.info" `elem` fs then Just <$> TL.readFile (dir </> "client.info") else pure Nothing payload <- if "payload.json" `elem` fs then Just <$> TL.readFile (dir </> "payload.json") else pure Nothing logFile <- case find ("main" `isPrefixOf`) fs of Just f -> Just <$> TL.readFile (dir </> f) Nothing -> pure Nothing pure $ (takeFileName dir,,) <$> ((,) <$> clientInfo <*> payload) <*> logFile -- | Extract IP, OS, and version from JSON files. getClientInfo :: (LText, LText) -> Maybe (Text, Text, Text) getClientInfo (info, payload) = (,,) <$> (info ^? strKey "addr" . L.to (T.takeWhile (/= ':'))) <*> (payload ^? strKey "os") <*> (payload ^? strKey "version") where strKey k = L.key k . L._String data Event = NodeStart | WalletStart | Adoption Count deriving (Eq, Show, Generic) instance Buildable Event where build = genericF data Count = One | Many deriving (Eq, Show, Generic) instance Buildable Count where build = genericF type Line = (Time.UTCTime, Event) parseLine :: Text -> Maybe Line parseLine = P.parseMaybe @P.Dec $ do let inside a b = P.char a >> P.manyTill P.anyChar (P.char b) inside '[' ']' >> P.space time <- maybe empty pure . readMaybe =<< inside '[' ']' msg <- P.manyTill P.anyChar P.eof if | "Generated dht key" `isInfixOf` msg -> pure (time, NodeStart) | "DAEDALUS has STARTED" `isInfixOf` msg -> pure (time, WalletStart) | "Blocks have been adopted" `isInfixOf` msg -> pure (time, Adoption Many) | "Block has been adopted" `isInfixOf` msg -> pure (time, Adoption One) | otherwise -> P.parserFail "unknown event type" type Run = [Line] getRuns :: [Line] -> [Run] getRuns = Split.split (Split.dropInitBlank $ Split.keepDelimsL $ Split.whenElt ((== NodeStart) . snd)) getWalletStartingTime :: Run -> Maybe Time.NominalDiffTime getWalletStartingTime r = do (t1, _) <- head r (t2, _) <- find ((== WalletStart) . snd) r pure (Time.diffUTCTime t2 t1) getBlocksLoadingTime :: Run -> Maybe Time.NominalDiffTime getBlocksLoadingTime r = do (t1, _) <- head r (t2, _) <- lastMay (filter ((== Adoption Many) . snd) r) pure (Time.diffUTCTime t2 t1) isValidRun :: Run -> Bool isValidRun [] = False isValidRun (map snd -> (x:xs)) = and [ x == NodeStart , count WalletStart xs <= 1 , dedup [a | Adoption a <- xs] `elem` [[], [One], [Many], [Many,One]] ] data Entry = Entry { logDir :: FilePath , clientIP :: Text , clientOS :: Text , clientVer :: Text , walletStartingTime :: Maybe Time.NominalDiffTime , blocksLoadingTime :: Maybe Time.NominalDiffTime } deriving (Eq, Show, Generic) instance CSV.ToNamedRecord Entry instance CSV.DefaultOrdered Entry processLog :: Log -> [Entry] processLog (logDir, clientInfo, logFile) = do (clientIP, clientOS, clientVer) <- maybeToList (getClientInfo clientInfo) run <- getRuns $ mapMaybe (parseLine . toText) (TL.lines logFile) guard (isValidRun run) let walletStartingTime = getWalletStartingTime run blocksLoadingTime = getBlocksLoadingTime run pure Entry{..} ---------------------------------------------------------------------------- -- Utils ---------------------------------------------------------------------------- count :: Eq a => a -> [a] -> Int count x = length . filter (x ==) dedup :: Eq a => [a] -> [a] dedup = map unsafeHead . group ---------------------------------------------------------------------------- -- Instances ---------------------------------------------------------------------------- instance CSV.ToField Time.NominalDiffTime where toField = CSV.toField @Double . realToFrac
input-output-hk/cardano-sl
scripts/analyze/logs.hs
apache-2.0
5,696
0
15
1,296
1,673
908
765
-1
-1
module Proc.Util (mkProc, mkLambda, procUtilTests) where import Common import Proc.Compiled import Proc.Params import Data.IORef import Control.Monad.Error import TclErr import Util import Internal.Types (CmdCore(..)) import qualified TclObj as T import Test.HUnit mkLambda :: T.TclObj -> TclM ([T.TclObj] -> TclM T.TclObj) mkLambda fn = do lst <- T.asList fn case lst of [al,body] -> do pr <- mkProc (pack "lambda") al body nsr <- getCurrNS return $ withProcScope (procArgs pr) nsr (procAction pr) (pack "lambda") _ -> fail "invalid lambda" useCompiledProcs = True ref = io . newIORef readRef = io . readIORef (.<-) r v = io $ (writeIORef r) v (.^^) r f = io $ (modifyIORef r) f mkProc pname alst body = do params <- parseParams pname alst if useCompiledProcs then do cproc <- ref Nothing count <- ref (0 :: Int) let procInner = procRunner cproc count params body return $! ProcCore bsbody params (procCatcher procInner) else return $! ProcCore bsbody params (procCatcher (evalTcl body)) where bsbody = T.asBStr body cMAX_ATTEMPTS = 1 procRunner compref attempts params body = do num_attempts <- readRef attempts if num_attempts > cMAX_ATTEMPTS then (io $ putStrLn "reached max attempts") >> runInterp else do cp <- readRef compref case cp of Nothing -> compileAndExec `orElse` (incrAttempts >> runInterp) Just p -> runCompiled p where runInterp = evalTcl body incrAttempts = attempts .^^ (+ 1) compileAndExec = do cp <- compileProc params body compref .<- Just cp runCompiled cp procCatcher f = f `catchError` herr where herr (ErrTramp e) = throwError e herr e = case toEnum (errCode e) of EReturn -> return $! (errData e) EBreak -> tclErr "invoked \"break\" outside of a loop" EContinue -> tclErr "invoked \"continue\" outside of a loop" _ -> throwError e {-# INLINE procCatcher #-} procUtilTests = TestList []
strepo/hiccup
Proc/Util.hs
lgpl-2.1
2,159
0
15
638
689
348
341
59
5
module SubPatternIn1 where data T = C1 [Int] Int [Float] | C2 Int g :: Int -> T -> Int g z (C1 x b c) = case c of c@[] -> b c@(b_1 : b_2) -> b g z (C1 x b c) = b g z (C2 x) = x f :: [Int] -> Int f x@[] = (hd x) + (hd (tl x)) f x@((y : ys)) = (hd x) + (hd (tl x)) hd x = head x tl x = tail x
mpickering/HaRe
old/testing/introCase/SubPatternIn1AST.hs
bsd-3-clause
334
0
10
130
240
127
113
14
2
{-# LANGUAGE ScopedTypeVariables, TypeSynonymInstances, FlexibleInstances #-} -- |Binary serialization/deserialization utilities for types used in -- ROS messages. This module is used by generated code for .msg types. -- NOTE: The native byte ordering of the host is used to support the -- common scenario of same-machine transport. module Ros.Internal.RosBinary where import Control.Applicative ((<$>), (<*>)) import Control.Monad (replicateM) import Data.Binary.Get import Data.Binary.Put import Data.Int import qualified Data.Vector.Storable as V import Data.Word import Unsafe.Coerce (unsafeCoerce) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC8 import Foreign.Storable (sizeOf, Storable) import Ros.Internal.RosTypes import Ros.Internal.Util.BytesToVector -- |A type class for binary serialization of ROS messages. Very like -- the standard Data.Binary type class, but with different, more -- compact, instances for base types and an extra class method for -- dealing with message headers. class RosBinary a where -- |Serialize a value to a ByteString. put :: a -> Put -- |Deserialize a value from a ByteString. get :: Get a -- |Serialize a ROS message given a sequence number. This number -- may be used by message types with headers. The default -- implementation ignores the sequence number. putMsg :: Word32 -> a -> Put putMsg _ = put instance RosBinary Bool where put True = putWord8 1 put False = putWord8 0 get = (> 0) <$> getWord8 instance RosBinary Int8 where put = putWord8 . fromIntegral get = fromIntegral <$> getWord8 instance RosBinary Word8 where put = putWord8 get = getWord8 instance RosBinary Int16 where put = putWord16host . fromIntegral get = fromIntegral <$> getWord16host instance RosBinary Word16 where put = putWord16host get = getWord16host instance RosBinary Int where put = putWord32host . fromIntegral get = fromIntegral <$> getWord32host instance RosBinary Word32 where put = putWord32host get = getWord32host instance RosBinary Int64 where put = putWord64host . fromIntegral get = fromIntegral <$> getWord64host instance RosBinary Word64 where put = putWord64host get = getWord64host instance RosBinary Float where put = putWord32le . unsafeCoerce get = unsafeCoerce <$> getWord32le instance RosBinary Double where put = putWord64le . unsafeCoerce get = unsafeCoerce <$> getWord64le getAscii :: Get Char getAscii = toEnum . fromEnum <$> getWord8 putAscii :: Char -> Put putAscii = putWord8 . toEnum . fromEnum putUnit :: Put putUnit = putWord8 0 getUnit :: Get () getUnit = getWord8 >> return () instance RosBinary String where put s = let s' = BC8.pack s in putInt32 (BC8.length s') >> putByteString s' get = getInt32 >>= (BC8.unpack <$>) . getByteString instance RosBinary B.ByteString where put b = putInt32 (B.length b) >> putByteString b get = getInt32 >>= getByteString instance RosBinary ROSTime where put (s,n) = putWord32host s >> putWord32host n get = (,) <$> getWord32host <*> getWord32host putList :: RosBinary a => [a] -> Put putList xs = putInt32 (length xs) >> mapM_ put xs getList :: RosBinary a => Get [a] getList = getInt32 >>= flip replicateM get putFixedList :: RosBinary a => [a] -> Put putFixedList = mapM_ put getFixedList :: RosBinary a => Int -> Get [a] getFixedList = flip replicateM get {- instance RosBinary ROSDuration where put (s,n) = putWord32host s >> putWord32host n get = (,) <$> getWord32host <*> getWord32host -} getInt32 :: Get Int getInt32 = fromIntegral <$> getWord32le putInt32 :: Int -> Put putInt32 = putWord32le . fromIntegral instance (RosBinary a, Storable a) => RosBinary (V.Vector a) where put v = putInt32 (V.length v) >> putByteString (vectorToBytes v) get = getInt32 >>= getFixed getFixed :: forall a. Storable a => Int -> Get (V.Vector a) getFixed n = bytesToVector n <$> getByteString (n*(sizeOf (undefined::a))) putFixed :: (Storable a, RosBinary a) => V.Vector a -> Put putFixed = putByteString . vectorToBytes
bitemyapp/roshask
src/Ros/Internal/RosBinary.hs
bsd-3-clause
4,152
0
12
817
1,043
566
477
91
1
module T15723A where {-# INLINE foo #-} foo :: Int -> Int foo x = {-# SCC foo1 #-} bar x {-# NOINLINE bar #-} bar :: Int -> Int bar x = x
sdiehl/ghc
testsuite/tests/codeGen/should_compile/T15723A.hs
bsd-3-clause
140
0
5
36
44
25
19
-1
-1
{-# LANGUAGE CPP #-} module Vectorise.Utils.Base ( voidType , newLocalVVar , mkDataConTag, dataConTagZ , mkWrapType , mkClosureTypes , mkPReprType , mkPDataType, mkPDatasType , splitPrimTyCon , mkBuiltinCo , wrapNewTypeBodyOfWrap , unwrapNewTypeBodyOfWrap , wrapNewTypeBodyOfPDataWrap , unwrapNewTypeBodyOfPDataWrap , wrapNewTypeBodyOfPDatasWrap , unwrapNewTypeBodyOfPDatasWrap , pdataReprTyCon , pdataReprTyConExact , pdatasReprTyConExact , pdataUnwrapScrut , preprSynTyCon ) where import Vectorise.Monad import Vectorise.Vect import Vectorise.Builtins import CoreSyn import CoreUtils import FamInstEnv import Coercion import Type import TyCon import DataCon import MkId import DynFlags import FastString #include "HsVersions.h" -- Simple Types --------------------------------------------------------------- voidType :: VM Type voidType = mkBuiltinTyConApp voidTyCon [] -- Name Generation ------------------------------------------------------------ newLocalVVar :: FastString -> Type -> VM VVar newLocalVVar fs vty = do lty <- mkPDataType vty vv <- newLocalVar fs vty lv <- newLocalVar fs lty return (vv,lv) -- Constructors --------------------------------------------------------------- mkDataConTag :: DynFlags -> DataCon -> CoreExpr mkDataConTag dflags = mkIntLitInt dflags . dataConTagZ dataConTagZ :: DataCon -> Int dataConTagZ con = dataConTag con - fIRST_TAG -- Type Construction ---------------------------------------------------------- -- |Make an application of the 'Wrap' type constructor. -- mkWrapType :: Type -> VM Type mkWrapType ty = mkBuiltinTyConApp wrapTyCon [ty] -- |Make an application of the closure type constructor. -- mkClosureTypes :: [Type] -> Type -> VM Type mkClosureTypes = mkBuiltinTyConApps closureTyCon -- |Make an application of the 'PRepr' type constructor. -- mkPReprType :: Type -> VM Type mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty] -- | Make an appliction of the 'PData' tycon to some argument. -- mkPDataType :: Type -> VM Type mkPDataType ty = mkBuiltinTyConApp pdataTyCon [ty] -- | Make an application of the 'PDatas' tycon to some argument. -- mkPDatasType :: Type -> VM Type mkPDatasType ty = mkBuiltinTyConApp pdatasTyCon [ty] -- Make an application of a builtin type constructor to some arguments. -- mkBuiltinTyConApp :: (Builtins -> TyCon) -> [Type] -> VM Type mkBuiltinTyConApp get_tc tys = do { tc <- builtin get_tc ; return $ mkTyConApp tc tys } -- Make a cascading application of a builtin type constructor. -- mkBuiltinTyConApps :: (Builtins -> TyCon) -> [Type] -> Type -> VM Type mkBuiltinTyConApps get_tc tys ty = do { tc <- builtin get_tc ; return $ foldr (mk tc) ty tys } where mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2] -- Type decomposition --------------------------------------------------------- -- |Checks if a type constructor is defined in 'GHC.Prim' (e.g., 'Int#'); if so, returns it. -- splitPrimTyCon :: Type -> Maybe TyCon splitPrimTyCon ty | Just (tycon, []) <- splitTyConApp_maybe ty , isPrimTyCon tycon = Just tycon | otherwise = Nothing -- Coercion Construction ----------------------------------------------------- -- |Make a representational coersion to some builtin type. -- mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion mkBuiltinCo get_tc = do { tc <- builtin get_tc ; return $ mkTyConAppCo Representational tc [] } -- Wrapping and unwrapping the 'Wrap' newtype --------------------------------- -- |Apply the constructor wrapper of the 'Wrap' /newtype/. -- wrapNewTypeBodyOfWrap :: CoreExpr -> Type -> VM CoreExpr wrapNewTypeBodyOfWrap e ty = do { wrap_tc <- builtin wrapTyCon ; return $ wrapNewTypeBody wrap_tc [ty] e } -- |Strip the constructor wrapper of the 'Wrap' /newtype/. -- unwrapNewTypeBodyOfWrap :: CoreExpr -> Type -> VM CoreExpr unwrapNewTypeBodyOfWrap e ty = do { wrap_tc <- builtin wrapTyCon ; return $ unwrapNewTypeBody wrap_tc [ty] e } -- |Apply the constructor wrapper of the 'PData' /newtype/ instance of 'Wrap'. -- wrapNewTypeBodyOfPDataWrap :: CoreExpr -> Type -> VM CoreExpr wrapNewTypeBodyOfPDataWrap e ty = do { wrap_tc <- builtin wrapTyCon ; pwrap_tc <- pdataReprTyConExact wrap_tc ; return $ wrapNewTypeBody pwrap_tc [ty] e } -- |Strip the constructor wrapper of the 'PData' /newtype/ instance of 'Wrap'. -- unwrapNewTypeBodyOfPDataWrap :: CoreExpr -> Type -> VM CoreExpr unwrapNewTypeBodyOfPDataWrap e ty = do { wrap_tc <- builtin wrapTyCon ; pwrap_tc <- pdataReprTyConExact wrap_tc ; return $ unwrapNewTypeBody pwrap_tc [ty] (unwrapFamInstScrut pwrap_tc [ty] e) } -- |Apply the constructor wrapper of the 'PDatas' /newtype/ instance of 'Wrap'. -- wrapNewTypeBodyOfPDatasWrap :: CoreExpr -> Type -> VM CoreExpr wrapNewTypeBodyOfPDatasWrap e ty = do { wrap_tc <- builtin wrapTyCon ; pwrap_tc <- pdatasReprTyConExact wrap_tc ; return $ wrapNewTypeBody pwrap_tc [ty] e } -- |Strip the constructor wrapper of the 'PDatas' /newtype/ instance of 'Wrap'. -- unwrapNewTypeBodyOfPDatasWrap :: CoreExpr -> Type -> VM CoreExpr unwrapNewTypeBodyOfPDatasWrap e ty = do { wrap_tc <- builtin wrapTyCon ; pwrap_tc <- pdatasReprTyConExact wrap_tc ; return $ unwrapNewTypeBody pwrap_tc [ty] (unwrapFamInstScrut pwrap_tc [ty] e) } -- 'PData' representation types ---------------------------------------------- -- |Get the representation tycon of the 'PData' data family for a given type. -- -- This tycon does not appear explicitly in the source program β€” see Note [PData TyCons] in -- 'Vectorise.Generic.Description': -- -- @pdataReprTyCon {Sum2} = {PDataSum2}@ -- -- The type for which we look up a 'PData' instance may be more specific than the type in the -- instance declaration. In that case the second component of the result will be more specific than -- a set of distinct type variables. -- pdataReprTyCon :: Type -> VM (TyCon, [Type]) pdataReprTyCon ty = do { FamInstMatch { fim_instance = famInst , fim_tys = tys } <- builtin pdataTyCon >>= (`lookupFamInst` [ty]) ; return (dataFamInstRepTyCon famInst, tys) } -- |Get the representation tycon of the 'PData' data family for a given type constructor. -- -- For example, for a binary type constructor 'T', we determine the representation type constructor -- for 'PData (T a b)'. -- pdataReprTyConExact :: TyCon -> VM TyCon pdataReprTyConExact tycon = do { -- look up the representation tycon; if there is a match at all, it will be be exact ; -- (i.e.,' _tys' will be distinct type variables) ; (ptycon, _tys) <- pdataReprTyCon (tycon `mkTyConApp` mkTyVarTys (tyConTyVars tycon)) ; return ptycon } -- |Get the representation tycon of the 'PDatas' data family for a given type constructor. -- -- For example, for a binary type constructor 'T', we determine the representation type constructor -- for 'PDatas (T a b)'. -- pdatasReprTyConExact :: TyCon -> VM TyCon pdatasReprTyConExact tycon = do { -- look up the representation tycon; if there is a match at all, it will be be exact ; (FamInstMatch { fim_instance = ptycon }) <- pdatasReprTyCon (tycon `mkTyConApp` mkTyVarTys (tyConTyVars tycon)) ; return $ dataFamInstRepTyCon ptycon } where pdatasReprTyCon ty = builtin pdatasTyCon >>= (`lookupFamInst` [ty]) -- |Unwrap a 'PData' representation scrutinee. -- pdataUnwrapScrut :: VExpr -> VM (CoreExpr, CoreExpr, DataCon) pdataUnwrapScrut (ve, le) = do { (tc, arg_tys) <- pdataReprTyCon ty ; let [dc] = tyConDataCons tc ; return (ve, unwrapFamInstScrut tc arg_tys le, dc) } where ty = exprType ve -- 'PRepr' representation types ---------------------------------------------- -- |Get the representation tycon of the 'PRepr' type family for a given type. -- preprSynTyCon :: Type -> VM FamInstMatch preprSynTyCon ty = builtin preprTyCon >>= (`lookupFamInst` [ty])
spacekitteh/smcghc
compiler/vectorise/Vectorise/Utils/Base.hs
bsd-3-clause
8,068
3
13
1,550
1,548
841
707
130
1