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 OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | DBSocketT transformer which signs and issues network requests. ----------------------------------------------------------------------------- module Azure.DocDB.SocketMonad.DBSocketT ( DBSocketState, DBSocketT, execDBSocketT, mkDBSocketState ) where import Control.Applicative import Control.Lens (Lens', lens, (%~), (.=), (%=)) import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State import Control.Monad.Catch (MonadThrow) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Time.Clock (getCurrentTime) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Encoding as T import Network.HTTP.Client as HC import qualified Network.HTTP.Types as HT import Web.HttpApiData (ToHttpApiData(..)) import Azure.DocDB.Auth import Azure.DocDB.ResourceId import qualified Azure.DocDB.ServiceHeader as AH import Azure.DocDB.SocketMonad.Class -- | Socket state for DB connections data DBSocketState = DBSocketState { dbSSRequest :: Request, -- ^ Verb, uri, body, and additional headers being sent sbSSSigning :: SigningParams -> DocDBSignature, -- ^ Method to sign requests sendHttps :: Request -> IO (Response L.ByteString) } newtype DBSocketT m a = DBSocketT { runDBSocketT :: ExceptT DBError (ReaderT DBSocketState m) a } deriving (Functor, Applicative, Monad, MonadIO) instance MonadTrans DBSocketT where lift = DBSocketT . lift . lift -- Lenses for a request method' :: Lens' Request HT.Method method' = lens method (\req m -> req { method = m }) path' :: Lens' Request B.ByteString path' = lens path (\req m -> req { path = m }) requestBody' :: Lens' Request RequestBody requestBody' = lens requestBody (\req m -> req { requestBody = m }) requestHeaders' :: Lens' Request [HT.Header] requestHeaders' = lens requestHeaders (\req m -> req { requestHeaders = m }) -- | Execute the DB operation execDBSocketT :: MonadIO m => DBSocketT m a -> DBSocketState -> m (Either DBError a) execDBSocketT (DBSocketT m) = runReaderT (runExceptT m) --- | DBSocketState constructor mkDBSocketState :: (MonadThrow m, MonadIO m, Alternative m) => B.ByteString -- ^ Signing key -> T.Text -- ^ Root url -> Manager -- ^ Network manager -> m DBSocketState mkDBSocketState signingKey root mgr = do r <- parseRequest $ T.unpack root return DBSocketState { dbSSRequest = r { requestHeaders = [AH.version] } , sbSSSigning = signRequestInfo signingKey , sendHttps = mkDebuggable (`httpLbs` mgr) } -- | Add IO printing to network activity mkDebuggable :: MonadIO m => (Request -> m (Response L.ByteString)) -> Request -> m (Response L.ByteString) mkDebuggable f req = do liftIO $ do print req T.putStrLn (case requestBody req of RequestBodyLBS lb -> T.decodeUtf8 $ L.toStrict lb RequestBodyBS sb -> T.decodeUtf8 sb _ -> "Unknown response") rspTmp <- f req liftIO $ print rspTmp return rspTmp instance Monad m => MonadError DBError (DBSocketT m) where throwError e = DBSocketT $ throwError e catchError (DBSocketT ma) fema = DBSocketT $ catchError ma (runDBSocketT . fema) instance MonadIO m => DBSocketMonad (DBSocketT m) where sendSocketRequest socketRequest = DBSocketT $ do (DBSocketState req fsign sendHttpsProc) <- ask -- Pick a timestamp for signing now <- MSDate <$> liftIO getCurrentTime -- Sign the request let signature = fsign SigningParams { spMethod = srMethod socketRequest, spResourceType = srResourceType socketRequest, spPath = srResourceLink socketRequest, spWhen = now } -- Build and issue the request response <- liftIO . sendHttpsProc . applySocketRequest . applySignature now signature $ req let status = responseStatus response let statusText = T.decodeUtf8 . HT.statusMessage $ status case HT.statusCode status of 403 -> throwError DBForbidden 404 -> throwError DBNotFound 409 -> throwError DBConflict 412 -> throwError DBPreconditionFailure 413 -> throwError DBEntityTooLarge code | code >= 400 && code < 500 -> throwError $ DBBadRequest statusText code | code >= 500 -> throwError $ DBServiceError statusText _ -> return . responseToSocketResponse $ response -- where -- Update the request to match the top level socketRequest parameters applySocketRequest :: Request -> Request applySocketRequest = execState $ do method' .= HT.renderStdMethod (srMethod socketRequest) path' %= (</> T.encodeUtf8 (srUriPath socketRequest)) requestBody' .= RequestBodyLBS (srContent socketRequest) requestHeaders' %= (srHeaders socketRequest ++) -- Apply the signature info applySignature :: ToHttpApiData a => MSDate -> a -> Request -> Request applySignature dateWhen docDBSignature = requestHeaders' %~ execState (do AH.header' AH.msDate .= Just (toHeader dateWhen) AH.header' HT.hAuthorization .= Just (toHeader docDBSignature) ) responseToSocketResponse :: Response L.ByteString -> SocketResponse responseToSocketResponse response = SocketResponse (HT.statusCode $ responseStatus response) (responseHeaders response) (responseBody response)
jnonce/azure-docdb
lib/Azure/DocDB/SocketMonad/DBSocketT.hs
bsd-3-clause
5,678
0
17
1,211
1,436
765
671
115
3
import Test.Hspec import Control.Comonad.Cofree.Cofreer.Spec import Control.Monad.Free.Freer.Spec import GL.Shader.Spec import UI.Layout.Spec main :: IO () main = hspec . parallel $ do describe "Control.Comonad.Cofree.Cofreer.Spec" Control.Comonad.Cofree.Cofreer.Spec.spec describe "Control.Monad.Free.Freer.Spec" Control.Monad.Free.Freer.Spec.spec describe "GL.Shader.Spec" GL.Shader.Spec.spec describe "UI.Layout.Spec" UI.Layout.Spec.spec
robrix/ui-effects
test/Spec.hs
bsd-3-clause
450
0
9
42
109
63
46
11
1
-- | A name binding context, or environment. module Hpp.Env where import Hpp.Types (Macro) -- | A macro binding environment. type Env = [(String, Macro)] -- | Delete an entry from an association list. deleteKey :: Eq a => a -> [(a,b)] -> [(a,b)] deleteKey k = go where go [] = [] go (h@(x,_) : xs) = if x == k then xs else h : go xs -- | Looks up a value in an association list. If the key is found, the -- value is returned along with an updated association list with that -- key at the front. lookupKey :: Eq a => a -> [(a,b)] -> Maybe (b, [(a,b)]) lookupKey k = go id where go _ [] = Nothing go acc (h@(x,v) : xs) | k == x = Just (v, h : acc [] ++ xs) | otherwise = go (acc . (h:)) xs
bitemyapp/hpp
src/Hpp/Env.hs
bsd-3-clause
731
0
13
194
295
165
130
13
3
module Dice where import Control.Monad (liftM) import Control.Monad.Random import Data.List (intercalate) data DiceBotCmd = Start | Quit | Roll { cmdDice :: [Die] } | None | Bad { cmdBad :: String } deriving (Show, Eq) data Die = Const { dieConst :: Int } | Die { dieNum :: Int, dieType :: Int } deriving (Show, Eq) showDice :: [Die] -> String showDice = intercalate " + " . map showDie where showDie (Const n) = show n showDie (Die n t) = show n ++ "d" ++ show t showResult :: [Int] -> String showResult = intercalate " + " . map show randomFace :: RandomGen g => Int -> Rand g Int randomFace t = getRandomR (1, t) rollDie :: RandomGen g => Die -> Rand g [Int] rollDie (Const n) = return [n] rollDie (Die n t) = sequence . replicate n $ randomFace t rollDice :: [Die] -> IO [Int] rollDice = evalRandIO . liftM concat . mapM rollDie
haskell-ro/hs-dicebot
Dice.hs
bsd-3-clause
873
0
9
204
374
200
174
28
2
import Data.Either import Test.Hspec import qualified Text.Parsec as P import Lib import Lexer as L import Parser as P program = unlines [ "dong inflate." , "[ 3 ] value." , "[ :x | x name ] value: 9." ] lexerSpec = do describe "parseToken" $ do let parseToken = P.parse L.parseToken "(spec)" it "parses LBracket" $ do parseToken "[" `shouldBe` Right LBracket it "parses RBracket" $ do parseToken "]" `shouldBe` Right RBracket it "parses Period" $ do parseToken "." `shouldBe` Right Period it "parses Pipe" $ do parseToken "|" `shouldBe` Right Pipe it "parses Bind" $ do parseToken ":=" `shouldBe` Right Bind it "parses Name" $ do parseToken "abc" `shouldBe` Right (Name "abc") it "parses a Name with a number" $ do parseToken "abc1" `shouldBe` Right (Name "abc1") it "parses Keyword" $ do parseToken "abc:" `shouldBe` Right (Keyword "abc") it "parses Arg" $ do parseToken ":abc" `shouldBe` Right (Arg "abc") it "parses Symbol" $ do parseToken "+" `shouldBe` Right (Symbol "+") it "parses StringLiteral" $ do parseToken "'hello'" `shouldBe` Right (StringLiteral "hello") it "parses CharLiteral" $ do parseToken "$a" `shouldBe` Right (CharLiteral 'a') it "parses Number" $ do parseToken "32" `shouldBe` Right (Number 32) parserSpec = do let parse p s = do lexed <- P.parse L.parseTokens "(spec)" s P.parse p "(spec)" lexed describe "parseLiteral" $ do let parseLiteral = parse P.parseLiteral it "parses string literal" $ do parseLiteral "'hi'" `shouldBe` Right (LiteralString "hi") it "parses number literal" $ do parseLiteral "23" `shouldBe` Right (LiteralNumber 23) describe "parseStatement" $ do let parseStatement = parse P.parseStatement it "parses unary message" $ do parseStatement "abc def." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "abc") [UnaryMessage "def"] [] [])] Nothing) it "parses binary message" $ do parseStatement "abc + def." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "abc") [] [BinaryMessage "+" (OperandIdentifier "def")] [])] Nothing) it "parses keyword message" $ do parseStatement "abc def: xyz." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "abc") [] [] [KeywordMessage "def" (OperandIdentifier "xyz")])] Nothing) it "parses combined message" $ do parseStatement "a b - c d: e." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "a") [UnaryMessage "b"] [BinaryMessage "-" (OperandIdentifier "c")] [KeywordMessage "d" (OperandIdentifier "e")])] Nothing) it "parses message to nested expression" $ do parseStatement "(a b) c." `shouldBe` Right (Statement [(ExpressionSend (OperandNested (ExpressionSend (OperandIdentifier "a") [UnaryMessage "b"] [] [])) [UnaryMessage "c"] [] [])] Nothing) it "parses a naked expression as a statement" $ do parseStatement "3" `shouldBe` Right (Statement [] (Just $ ExpressionSend (OperandLiteral (LiteralNumber 3)) [] [] [])) it "parses block without args" $ do parseStatement "[ 3 ]" `shouldBe` Right (Statement [] (Just $ (ExpressionSend (OperandBlock (Block [] [Statement [] (Just $ ExpressionSend (OperandLiteral (LiteralNumber 3)) [] [] [])])) [] [] [] ) )) it "parses block with args" $ do parseStatement "[ :x | x ]" `shouldBe` Right (Statement [] (Just $ (ExpressionSend (OperandBlock (Block ["x"] [Statement [] (Just $ ExpressionSend (OperandIdentifier "x") [] [] [])]) ) [] [] [] ))) it "parses block with multiple args and statements" $ do parseStatement "[ :x :y | 2 negate. x + y / 2 ]" `shouldBe` Right (Statement [] (Just $ ExpressionSend (OperandBlock (Block ["x", "y"] [Statement [ExpressionSend (OperandLiteral (LiteralNumber 2)) [UnaryMessage "negate"] [] []] (Just $ ExpressionSend (OperandIdentifier "x") [] [BinaryMessage "+" (OperandIdentifier "y"), BinaryMessage "/" (OperandLiteral (LiteralNumber 2))] [] )] ) ) [] [] [])) it "does not parse statement with malformed binop" $ do parseStatement "a + + b" `shouldSatisfy` isLeft it "does not parse statement with malformed keyword message" $ do parseStatement "a b: c: d" `shouldSatisfy` isLeft main = do hspec lexerSpec hspec parserSpec
rjeli/luatalk
test/Spec.hs
bsd-3-clause
5,511
0
34
2,053
1,546
738
808
111
1
{-# LANGUAGE LambdaCase #-} module Main (main) where import System.Environment (getArgs) eyes = cycle ["⦿⦿", "⦾⦾", "⟐⟐", "⪽⪾", "⨷⨷", "⨸⨸", "☯☯", "⊙⊙", "⊚⊚", "⊛⊛", "⨕⨕", "⊗⊗", "⊘⊘", "⊖⊖", "⁌⁍", "✩✩", "❈❈"] shells = cycle ["()", "{}", "[]", "⨭⨮", "⨴⨵", "⊆⊇", "∣∣"] bodies = cycle ["███", "XXX", "⧱⧰⧱", "⧯⧮⧯", "⧲⧳⧲","🁢🁢🁢", "✚✚✚", "⧓⧒⧑", "⦁⦁⦁", "☗☗☗", "❝❝❝"] arthropod k = (face k):(repeat $ body k) face k = let (l:r:[]) = eyes !! k in "╚" ++ l:" " ++ r:"╝" body k = let (l:r:[]) = shells !! k c = bodies !! k in "╚═" ++ l:c ++ r:"═╝" wiggle = map (flip replicate ' ') (4 : cycle [2,1,0,1,2,3,4,3]) millipede = zipWith (++) wiggle . arthropod main :: IO () main = getArgs >>= \case [] -> beautiful $ millipede 0 (x:[]) -> beautiful $ millipede (read x) where beautiful = putStrLn . unlines . take 20
getmillipede/millipede-haskell
app/Main.hs
bsd-3-clause
1,023
0
12
214
442
246
196
19
2
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} -- | This module builds Docker (OpenContainer) images. module Stack.Image (stageContainerImageArtifacts, createContainerImageFromStage, imgCmdName, imgDockerCmdName, imgOptsFromMonoid, imgDockerOptsFromMonoid, imgOptsParser, imgDockerOptsParser) where import Control.Applicative import Control.Exception.Lifted hiding (finally) import Control.Monad import Control.Monad.Catch hiding (bracket) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Char (toLower) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Monoid import qualified Data.Text as T import Data.Typeable import Options.Applicative import Path import Path.Extra import Path.IO import Stack.Constants import Stack.Types import Stack.Types.Internal import System.Process.Run type Build e m = (HasBuildConfig e, HasConfig e, HasEnvConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadReader e m) type Assemble e m = (HasConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadMask m, MonadReader e m) -- | Stages the executables & additional content in a staging -- directory under '.stack-work' stageContainerImageArtifacts :: Build e m => m () stageContainerImageArtifacts = do imageDir <- imageStagingDir <$> getWorkingDir removeTreeIfExists imageDir createTree imageDir stageExesInDir imageDir syncAddContentToDir imageDir -- | Builds a Docker (OpenContainer) image extending the `base` image -- specified in the project's stack.yaml. Then new image will be -- extended with an ENTRYPOINT specified for each `entrypoint` listed -- in the config file. createContainerImageFromStage :: Assemble e m => m () createContainerImageFromStage = do imageDir <- imageStagingDir <$> getWorkingDir createDockerImage imageDir extendDockerImageWithEntrypoint imageDir -- | Stage all the Package executables in the usr/local/bin -- subdirectory of a temp directory. stageExesInDir :: Build e m => Path Abs Dir -> m () stageExesInDir dir = do srcBinPath <- (</> $(mkRelDir "bin")) <$> installationRootLocal let destBinPath = dir </> $(mkRelDir "usr/local/bin") createTree destBinPath copyDirectoryRecursive srcBinPath destBinPath -- | Add any additional files into the temp directory, respecting the -- (Source, Destination) mapping. syncAddContentToDir :: Build e m => Path Abs Dir -> m () syncAddContentToDir dir = do config <- asks getConfig bconfig <- asks getBuildConfig let imgAdd = maybe Map.empty imgDockerAdd (imgDocker (configImage config)) forM_ (Map.toList imgAdd) (\(source,dest) -> do sourcePath <- parseRelDir source destPath <- parseAbsDir dest let destFullPath = dir </> dropRoot destPath createTree destFullPath copyDirectoryRecursive (bcRoot bconfig </> sourcePath) destFullPath) -- | Derive an image name from the project directory. imageName :: Path Abs Dir -> String imageName = map toLower . toFilePathNoTrailingSep . dirname -- | Create a general purpose docker image from the temporary -- directory of executables & static content. createDockerImage :: Assemble e m => Path Abs Dir -> m () createDockerImage dir = do menv <- getMinimalEnvOverride config <- asks getConfig let dockerConfig = imgDocker (configImage config) case imgDockerBase =<< dockerConfig of Nothing -> throwM StackImageDockerBaseUnspecifiedException Just base -> do liftIO (writeFile (toFilePath (dir </> $(mkRelFile "Dockerfile"))) (unlines ["FROM " ++ base, "ADD ./ /"])) callProcess Nothing menv "docker" [ "build" , "-t" , fromMaybe (imageName (parent (parent dir))) (imgDockerImageName =<< dockerConfig) , toFilePathNoTrailingSep dir] -- | Extend the general purpose docker image with entrypoints (if -- specified). extendDockerImageWithEntrypoint :: Assemble e m => Path Abs Dir -> m () extendDockerImageWithEntrypoint dir = do menv <- getMinimalEnvOverride config <- asks getConfig let dockerConfig = imgDocker (configImage config) let dockerImageName = fromMaybe (imageName (parent (parent dir))) (imgDockerImageName =<< dockerConfig) let imgEntrypoints = maybe Nothing imgDockerEntrypoints dockerConfig case imgEntrypoints of Nothing -> return () Just eps -> forM_ eps (\ep -> do liftIO (writeFile (toFilePath (dir </> $(mkRelFile "Dockerfile"))) (unlines [ "FROM " ++ dockerImageName , "ENTRYPOINT [\"/usr/local/bin/" ++ ep ++ "\"]" , "CMD []"])) callProcess Nothing menv "docker" [ "build" , "-t" , dockerImageName ++ "-" ++ ep , toFilePathNoTrailingSep dir]) -- | The command name for dealing with images. imgCmdName :: String imgCmdName = "image" -- | The command name for building a docker container. imgDockerCmdName :: String imgDockerCmdName = "container" -- | A parser for ImageOptsMonoid. imgOptsParser :: Parser ImageOptsMonoid imgOptsParser = ImageOptsMonoid <$> optional (subparser (command imgDockerCmdName (info imgDockerOptsParser (progDesc "Create a container image (EXPERIMENTAL)")))) -- | A parser for ImageDockerOptsMonoid. imgDockerOptsParser :: Parser ImageDockerOptsMonoid imgDockerOptsParser = ImageDockerOptsMonoid <$> optional (option str (long (imgDockerCmdName ++ "-" ++ T.unpack imgDockerBaseArgName) <> metavar "NAME" <> help "Docker base image name")) <*> pure Nothing <*> pure Nothing <*> pure Nothing -- | Convert image opts monoid to image options. imgOptsFromMonoid :: ImageOptsMonoid -> ImageOpts imgOptsFromMonoid ImageOptsMonoid{..} = ImageOpts { imgDocker = imgDockerOptsFromMonoid <$> imgMonoidDocker } -- | Convert Docker image opts monoid to Docker image options. imgDockerOptsFromMonoid :: ImageDockerOptsMonoid -> ImageDockerOpts imgDockerOptsFromMonoid ImageDockerOptsMonoid{..} = ImageDockerOpts { imgDockerBase = emptyToNothing imgDockerMonoidBase , imgDockerEntrypoints = emptyToNothing imgDockerMonoidEntrypoints , imgDockerAdd = fromMaybe Map.empty imgDockerMonoidAdd , imgDockerImageName = emptyToNothing imgDockerMonoidImageName } where emptyToNothing Nothing = Nothing emptyToNothing (Just s) | null s = Nothing | otherwise = Just s -- | Stack image exceptions. data StackImageException = StackImageDockerBaseUnspecifiedException deriving (Typeable) instance Exception StackImageException instance Show StackImageException where show StackImageDockerBaseUnspecifiedException = "You must specify a base docker image on which to place your haskell executables."
rvion/stack
src/Stack/Image.hs
bsd-3-clause
8,426
0
24
2,650
1,539
789
750
178
2
{-# LANGUAGE ViewPatterns #-} module Run.Test (runTest) where import Prelude hiding (writeFile, length) import Data.ByteString.Lazy hiding (putStrLn) import Data.List hiding (length) import Data.Maybe import Control.Monad import System.Directory import Test.QuickFuzz.Gen.FormatInfo import Args import Debug import Exception import Process import Utils -- |Return a lazy list of steps to execute getSteps :: QFCommand -> [Int] getSteps (maxTries -> Nothing) = [1..] getSteps (maxTries -> Just n) = [1..n] -- Run test subcommand runTest :: (Show actions, Show base) => QFCommand -> FormatInfo base actions -> IO () runTest cmd fmt = do debug (show cmd) when (hasActions fmt) (putStrLn "Selected format supports actions based generation/shrinking!") createDirectoryIfMissing True (outDir cmd) mkName <- nameMaker cmd fmt (shcmd, testname) <- prepareCli cmd fmt let cleanup = when (usesFile cmd) $ removeFile testname -- Generation-execution-report loop forM_ (getSteps cmd) $ \n -> handleSigInt cleanup $ do let size = sawSize cmd n -- Generate a value and encode it in a bytestring. -- This fully evaluates the generated value, and retry -- the generation if the value cant be encoded. (mbacts, encoded, seed) <- strictGenerate cmd fmt size -- Fuzz the generated value if required. fuzzed <- if usesFuzzer cmd then fuzz (fromJust (fuzzer cmd)) encoded seed else return encoded -- Execute the command using either a file or stdin. exitcode <- if usesFile cmd then writeFile testname fuzzed >> execute (verbose cmd) shcmd else executeFromStdin (verbose cmd) shcmd fuzzed -- Report and move failed test cases. when (hasFailed exitcode) $ do let failname = mkName n seed size mapM_ putStrLn [ "Test case number " ++ show n ++ " has failed. " , "Moving to " ++ failname ] if usesFile cmd then renameFile testname failname else writeFile failname fuzzed -- Shrink if necessary when (hasFailed exitcode && shrinking cmd) $ do -- Execute a shrinking stategy acordingly to the -a/--actions flag (smallest, nshrinks, nfails) <- if hasActions fmt then runShrinkActions cmd fmt shcmd testname (fromJust mbacts) (diff encoded fuzzed) else runShrinkByteString cmd shcmd testname fuzzed printShrinkingFinished -- Report the shrinking results let shrinkName = mkName n seed size ++ ".reduced" mapM_ putStrLn [ "Reduced from " ++ show (length fuzzed) ++ " bytes" ++ " to " ++ show (length smallest) ++ " bytes" , "After executing " ++ show nshrinks ++ " shrinks with " ++ show nfails ++ " failing shrinks. " , "Saving to " ++ shrinkName ] writeFile shrinkName smallest when (not $ verbose cmd) (printTestStep n) -- Clean up the mess cleanup printFinished
elopez/QuickFuzz
app/Run/Test.hs
gpl-3.0
3,314
0
24
1,092
768
386
382
60
5
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} -- | Inquiry to Nirum version. module Nirum.Version (version, versionString, versionText) where import Data.Maybe (mapMaybe) import Data.Version (versionBranch, versionTags) import qualified Data.SemVer as SV import Data.Text (Text, pack) import qualified Paths_nirum as P -- Special module provided by Cabal -- See also: http://stackoverflow.com/a/2892624/383405 -- | The semantic version of the running Nirum. version :: SV.Version version = case branch of [major, minor, patch] -> if length relTags == length tags then SV.version major minor patch relTags [] else error ("invalid release identifiers: " ++ show relTags) [_, _] -> error ("patch version is missing: " ++ show branch) [_] -> error ("minor version is missing: " ++ show branch) [] -> error "major version is missing" _ -> error ("too precise version for semver: " ++ show branch) where branch :: [Int] branch = versionBranch P.version tags :: [String] tags = versionTags P.version relTags :: [SV.Identifier] relTags = mapMaybe (SV.textual . pack) tags -- | The string representation of 'version'. versionString :: String versionString = SV.toString version -- | The text representation of 'version'. versionText :: Text versionText = SV.toText version
spoqa/nirum
src/Nirum/Version.hs
gpl-3.0
1,346
0
12
261
325
182
143
27
6
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ECS.DeregisterTaskDefinition -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | NOT YET IMPLEMENTED. -- -- Deregisters the specified task definition. You will no longer be able to run -- tasks from this definition after deregistration. -- -- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeregisterTaskDefinition.html> module Network.AWS.ECS.DeregisterTaskDefinition ( -- * Request DeregisterTaskDefinition -- ** Request constructor , deregisterTaskDefinition -- ** Request lenses , dtd1TaskDefinition -- * Response , DeregisterTaskDefinitionResponse -- ** Response constructor , deregisterTaskDefinitionResponse -- ** Response lenses , dtdrTaskDefinition ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.ECS.Types import qualified GHC.Exts newtype DeregisterTaskDefinition = DeregisterTaskDefinition { _dtd1TaskDefinition :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeregisterTaskDefinition' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dtd1TaskDefinition' @::@ 'Text' -- deregisterTaskDefinition :: Text -- ^ 'dtd1TaskDefinition' -> DeregisterTaskDefinition deregisterTaskDefinition p1 = DeregisterTaskDefinition { _dtd1TaskDefinition = p1 } -- | The 'family' and 'revision' ('family:revision') or full Amazon Resource Name (ARN) -- of the task definition that you want to deregister. dtd1TaskDefinition :: Lens' DeregisterTaskDefinition Text dtd1TaskDefinition = lens _dtd1TaskDefinition (\s a -> s { _dtd1TaskDefinition = a }) newtype DeregisterTaskDefinitionResponse = DeregisterTaskDefinitionResponse { _dtdrTaskDefinition :: Maybe TaskDefinition } deriving (Eq, Read, Show) -- | 'DeregisterTaskDefinitionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dtdrTaskDefinition' @::@ 'Maybe' 'TaskDefinition' -- deregisterTaskDefinitionResponse :: DeregisterTaskDefinitionResponse deregisterTaskDefinitionResponse = DeregisterTaskDefinitionResponse { _dtdrTaskDefinition = Nothing } -- | The full description of the deregistered task. dtdrTaskDefinition :: Lens' DeregisterTaskDefinitionResponse (Maybe TaskDefinition) dtdrTaskDefinition = lens _dtdrTaskDefinition (\s a -> s { _dtdrTaskDefinition = a }) instance ToPath DeregisterTaskDefinition where toPath = const "/" instance ToQuery DeregisterTaskDefinition where toQuery = const mempty instance ToHeaders DeregisterTaskDefinition instance ToJSON DeregisterTaskDefinition where toJSON DeregisterTaskDefinition{..} = object [ "taskDefinition" .= _dtd1TaskDefinition ] instance AWSRequest DeregisterTaskDefinition where type Sv DeregisterTaskDefinition = ECS type Rs DeregisterTaskDefinition = DeregisterTaskDefinitionResponse request = post "DeregisterTaskDefinition" response = jsonResponse instance FromJSON DeregisterTaskDefinitionResponse where parseJSON = withObject "DeregisterTaskDefinitionResponse" $ \o -> DeregisterTaskDefinitionResponse <$> o .:? "taskDefinition"
romanb/amazonka
amazonka-ecs/gen/Network/AWS/ECS/DeregisterTaskDefinition.hs
mpl-2.0
4,182
0
9
798
453
277
176
58
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Auxilary definitions for 'Semigroup' -- -- This module provides some @newtype@ wrappers and helpers which are -- reexported from the "Data.Semigroup" module or imported directly -- by some other modules. -- -- This module also provides internal definitions related to the -- 'Semigroup' class some. -- -- This module exists mostly to simplify or workaround import-graph -- issues; there is also a .hs-boot file to allow "GHC.Base" and other -- modules to import method default implementations for 'stimes' -- -- @since 4.11.0.0 module Data.Semigroup.Internal where import GHC.Base hiding (Any) import GHC.Enum import GHC.Num import GHC.Read import GHC.Show import GHC.Generics import GHC.Real -- | This is a valid definition of 'stimes' for an idempotent 'Semigroup'. -- -- When @x <> x = x@, this definition should be preferred, because it -- works in /O(1)/ rather than /O(log n)/. stimesIdempotent :: Integral b => b -> a -> a stimesIdempotent n x | n <= 0 = errorWithoutStackTrace "stimesIdempotent: positive multiplier expected" | otherwise = x -- | This is a valid definition of 'stimes' for an idempotent 'Monoid'. -- -- When @mappend x x = x@, this definition should be preferred, because it -- works in /O(1)/ rather than /O(log n)/ stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a stimesIdempotentMonoid n x = case compare n 0 of LT -> errorWithoutStackTrace "stimesIdempotentMonoid: negative multiplier" EQ -> mempty GT -> x -- | This is a valid definition of 'stimes' for a 'Monoid'. -- -- Unlike the default definition of 'stimes', it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a stimesMonoid n x0 = case compare n 0 of LT -> errorWithoutStackTrace "stimesMonoid: negative multiplier" EQ -> mempty GT -> f x0 n where f x y | even y = f (x `mappend` x) (y `quot` 2) | y == 1 = x | otherwise = g (x `mappend` x) (y `quot` 2) x -- See Note [Half of y - 1] g x y z | even y = g (x `mappend` x) (y `quot` 2) z | y == 1 = x `mappend` z | otherwise = g (x `mappend` x) (y `quot` 2) (x `mappend` z) -- See Note [Half of y - 1] -- this is used by the class definitionin GHC.Base; -- it lives here to avoid cycles stimesDefault :: (Integral b, Semigroup a) => b -> a -> a stimesDefault y0 x0 | y0 <= 0 = errorWithoutStackTrace "stimes: positive multiplier expected" | otherwise = f x0 y0 where f x y | even y = f (x <> x) (y `quot` 2) | y == 1 = x | otherwise = g (x <> x) (y `quot` 2) x -- See Note [Half of y - 1] g x y z | even y = g (x <> x) (y `quot` 2) z | y == 1 = x <> z | otherwise = g (x <> x) (y `quot` 2) (x <> z) -- See Note [Half of y - 1] {- Note [Half of y - 1] ~~~~~~~~~~~~~~~~~~~~~ Since y is guaranteed to be odd and positive here, half of y - 1 can be computed as y `quot` 2, optimising subtraction away. -} stimesMaybe :: (Integral b, Semigroup a) => b -> Maybe a -> Maybe a stimesMaybe _ Nothing = Nothing stimesMaybe n (Just a) = case compare n 0 of LT -> errorWithoutStackTrace "stimes: Maybe, negative multiplier" EQ -> Nothing GT -> Just (stimes n a) stimesList :: Integral b => b -> [a] -> [a] stimesList n x | n < 0 = errorWithoutStackTrace "stimes: [], negative multiplier" | otherwise = rep n where rep 0 = [] rep i = x ++ rep (i - 1) -- | The dual of a 'Monoid', obtained by swapping the arguments of 'mappend'. -- -- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" newtype Dual a = Dual { getDual :: a } deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1) -- | @since 4.9.0.0 instance Semigroup a => Semigroup (Dual a) where Dual a <> Dual b = Dual (b <> a) stimes n (Dual a) = Dual (stimes n a) -- | @since 2.01 instance Monoid a => Monoid (Dual a) where mempty = Dual mempty -- | @since 4.8.0.0 instance Functor Dual where fmap = coerce -- | @since 4.8.0.0 instance Applicative Dual where pure = Dual (<*>) = coerce -- | @since 4.8.0.0 instance Monad Dual where m >>= k = k (getDual m) -- | The monoid of endomorphisms under composition. -- -- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!") -- >>> appEndo computation "Haskell" -- "Hello, Haskell!" newtype Endo a = Endo { appEndo :: a -> a } deriving (Generic) -- | @since 4.9.0.0 instance Semigroup (Endo a) where (<>) = coerce ((.) :: (a -> a) -> (a -> a) -> (a -> a)) stimes = stimesMonoid -- | @since 2.01 instance Monoid (Endo a) where mempty = Endo id -- | Boolean monoid under conjunction ('&&'). -- -- >>> getAll (All True <> mempty <> All False) -- False -- -- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False newtype All = All { getAll :: Bool } deriving (Eq, Ord, Read, Show, Bounded, Generic) -- | @since 4.9.0.0 instance Semigroup All where (<>) = coerce (&&) stimes = stimesIdempotentMonoid -- | @since 2.01 instance Monoid All where mempty = All True -- | Boolean monoid under disjunction ('||'). -- -- >>> getAny (Any True <> mempty <> Any False) -- True -- -- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True newtype Any = Any { getAny :: Bool } deriving (Eq, Ord, Read, Show, Bounded, Generic) -- | @since 4.9.0.0 instance Semigroup Any where (<>) = coerce (||) stimes = stimesIdempotentMonoid -- | @since 2.01 instance Monoid Any where mempty = Any False -- | Monoid under addition. -- -- >>> getSum (Sum 1 <> Sum 2 <> mempty) -- 3 newtype Sum a = Sum { getSum :: a } deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1, Num) -- | @since 4.9.0.0 instance Num a => Semigroup (Sum a) where (<>) = coerce ((+) :: a -> a -> a) stimes n (Sum a) = Sum (fromIntegral n * a) -- | @since 2.01 instance Num a => Monoid (Sum a) where mempty = Sum 0 -- | @since 4.8.0.0 instance Functor Sum where fmap = coerce -- | @since 4.8.0.0 instance Applicative Sum where pure = Sum (<*>) = coerce -- | @since 4.8.0.0 instance Monad Sum where m >>= k = k (getSum m) -- | Monoid under multiplication. -- -- >>> getProduct (Product 3 <> Product 4 <> mempty) -- 12 newtype Product a = Product { getProduct :: a } deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1, Num) -- | @since 4.9.0.0 instance Num a => Semigroup (Product a) where (<>) = coerce ((*) :: a -> a -> a) stimes n (Product a) = Product (a ^ n) -- | @since 2.01 instance Num a => Monoid (Product a) where mempty = Product 1 -- | @since 4.8.0.0 instance Functor Product where fmap = coerce -- | @since 4.8.0.0 instance Applicative Product where pure = Product (<*>) = coerce -- | @since 4.8.0.0 instance Monad Product where m >>= k = k (getProduct m) -- | Monoid under '<|>'. -- -- @since 4.8.0.0 newtype Alt f a = Alt {getAlt :: f a} deriving (Generic, Generic1, Read, Show, Eq, Ord, Num, Enum, Monad, MonadPlus, Applicative, Alternative, Functor) -- | @since 4.9.0.0 instance Alternative f => Semigroup (Alt f a) where (<>) = coerce ((<|>) :: f a -> f a -> f a) stimes = stimesMonoid -- | @since 4.8.0.0 instance Alternative f => Monoid (Alt f a) where mempty = Alt empty
ezyang/ghc
libraries/base/Data/Semigroup/Internal.hs
bsd-3-clause
7,619
0
13
1,898
2,062
1,126
936
130
3
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "System/Process/Common.hs" #-} {-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} module System.Process.Common ( CreateProcess (..) , CmdSpec (..) , StdStream (..) , ProcessHandle(..) , ProcessHandle__(..) , ProcRetHandles (..) , withFilePathException , PHANDLE , modifyProcessHandle , withProcessHandle , fd_stdin , fd_stdout , fd_stderr , mbFd , mbPipe , pfdToHandle -- Avoid a warning on Windows , CGid ) where import Control.Concurrent import Control.Exception import Data.String import Foreign.Ptr import Foreign.Storable import System.Posix.Internals import GHC.IO.Exception import GHC.IO.Encoding import qualified GHC.IO.FD as FD import GHC.IO.Device import GHC.IO.Handle.FD import GHC.IO.Handle.Internals import GHC.IO.Handle.Types hiding (ClosedHandle) import System.IO.Error import Data.Typeable import GHC.IO.IOMode -- We do a minimal amount of CPP here to provide uniform data types across -- Windows and POSIX. import System.Posix.Types type PHANDLE = CPid data CreateProcess = CreateProcess{ cmdspec :: CmdSpec, -- ^ Executable & arguments, or shell command. If 'cwd' is 'Nothing', relative paths are resolved with respect to the current working directory. If 'cwd' is provided, it is implementation-dependent whether relative paths are resolved with respect to 'cwd' or the current working directory, so absolute paths should be used to ensure portability. cwd :: Maybe FilePath, -- ^ Optional path to the working directory for the new process env :: Maybe [(String,String)], -- ^ Optional environment (otherwise inherit from the current process) std_in :: StdStream, -- ^ How to determine stdin std_out :: StdStream, -- ^ How to determine stdout std_err :: StdStream, -- ^ How to determine stderr close_fds :: Bool, -- ^ Close all file descriptors except stdin, stdout and stderr in the new process (on Windows, only works if std_in, std_out, and std_err are all Inherit) create_group :: Bool, -- ^ Create a new process group delegate_ctlc:: Bool, -- ^ Delegate control-C handling. Use this for interactive console processes to let them handle control-C themselves (see below for details). -- -- On Windows this has no effect. -- -- @since 1.2.0.0 detach_console :: Bool, -- ^ Use the windows DETACHED_PROCESS flag when creating the process; does nothing on other platforms. -- -- @since 1.3.0.0 create_new_console :: Bool, -- ^ Use the windows CREATE_NEW_CONSOLE flag when creating the process; does nothing on other platforms. -- -- Default: @False@ -- -- @since 1.3.0.0 new_session :: Bool, -- ^ Use posix setsid to start the new process in a new session; does nothing on other platforms. -- -- @since 1.3.0.0 child_group :: Maybe GroupID, -- ^ Use posix setgid to set child process's group id; does nothing on other platforms. -- -- Default: @Nothing@ -- -- @since 1.4.0.0 child_user :: Maybe UserID, -- ^ Use posix setuid to set child process's user id; does nothing on other platforms. -- -- Default: @Nothing@ -- -- @since 1.4.0.0 use_process_jobs :: Bool -- ^ On Windows systems this flag indicates that we should wait for the entire process tree -- to finish before unblocking. On POSIX systems this flag is ignored. -- -- Default: @False@ -- -- @since 1.5.0.0 } deriving (Show, Eq) -- | contains the handles returned by a call to createProcess_Internal data ProcRetHandles = ProcRetHandles { hStdInput :: Maybe Handle , hStdOutput :: Maybe Handle , hStdError :: Maybe Handle , procHandle :: ProcessHandle } data CmdSpec = ShellCommand String -- ^ A command line to execute using the shell | RawCommand FilePath [String] -- ^ The name of an executable with a list of arguments -- -- The 'FilePath' argument names the executable, and is interpreted -- according to the platform's standard policy for searching for -- executables. Specifically: -- -- * on Unix systems the -- <http://pubs.opengroup.org/onlinepubs/9699919799/functions/execvp.html execvp(3)> -- semantics is used, where if the executable filename does not -- contain a slash (@/@) then the @PATH@ environment variable is -- searched for the executable. -- -- * on Windows systems the Win32 @CreateProcess@ semantics is used. -- Briefly: if the filename does not contain a path, then the -- directory containing the parent executable is searched, followed -- by the current directory, then some standard locations, and -- finally the current @PATH@. An @.exe@ extension is added if the -- filename does not already have an extension. For full details -- see the -- <http://msdn.microsoft.com/en-us/library/windows/desktop/aa365527%28v=vs.85%29.aspx documentation> -- for the Windows @SearchPath@ API. deriving (Show, Eq) -- | construct a `ShellCommand` from a string literal -- -- @since 1.2.1.0 instance IsString CmdSpec where fromString = ShellCommand data StdStream = Inherit -- ^ Inherit Handle from parent | UseHandle Handle -- ^ Use the supplied Handle | CreatePipe -- ^ Create a new pipe. The returned -- @Handle@ will use the default encoding -- and newline translation mode (just -- like @Handle@s created by @openFile@). | NoStream -- ^ No stream handle will be passed deriving (Eq, Show) -- ---------------------------------------------------------------------------- -- ProcessHandle type {- | A handle to a process, which can be used to wait for termination of the process using 'System.Process.waitForProcess'. None of the process-creation functions in this library wait for termination: they all return a 'ProcessHandle' which may be used to wait for the process later. On Windows a second wait method can be used to block for event completion. This requires two handles. A process job handle and a events handle to monitor. -} data ProcessHandle__ = OpenHandle PHANDLE | OpenExtHandle PHANDLE PHANDLE PHANDLE | ClosedHandle ExitCode data ProcessHandle = ProcessHandle { phandle :: !(MVar ProcessHandle__) , mb_delegate_ctlc :: !Bool , waitpidLock :: !(MVar ()) } withFilePathException :: FilePath -> IO a -> IO a withFilePathException fpath act = handle mapEx act where mapEx ex = ioError (ioeSetFileName ex fpath) modifyProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO (ProcessHandle__, a)) -> IO a modifyProcessHandle (ProcessHandle m _ _) io = modifyMVar m io withProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO a) -> IO a withProcessHandle (ProcessHandle m _ _) io = withMVar m io fd_stdin, fd_stdout, fd_stderr :: FD fd_stdin = 0 fd_stdout = 1 fd_stderr = 2 mbFd :: String -> FD -> StdStream -> IO FD mbFd _ _std CreatePipe = return (-1) mbFd _fun std Inherit = return std mbFd _fn _std NoStream = return (-2) mbFd fun _std (UseHandle hdl) = withHandle fun hdl $ \Handle__{haDevice=dev,..} -> case cast dev of Just fd -> do -- clear the O_NONBLOCK flag on this FD, if it is set, since -- we're exposing it externally (see #3316) fd' <- FD.setNonBlockingMode fd False return (Handle__{haDevice=fd',..}, FD.fdFD fd') Nothing -> ioError (mkIOError illegalOperationErrorType "createProcess" (Just hdl) Nothing `ioeSetErrorString` "handle is not a file descriptor") mbPipe :: StdStream -> Ptr FD -> IOMode -> IO (Maybe Handle) mbPipe CreatePipe pfd mode = fmap Just (pfdToHandle pfd mode) mbPipe _std _pfd _mode = return Nothing pfdToHandle :: Ptr FD -> IOMode -> IO Handle pfdToHandle pfd mode = do fd <- peek pfd let filepath = "fd:" ++ show fd (fD,fd_type) <- FD.mkFD (fromIntegral fd) mode (Just (Stream,0,0)) -- avoid calling fstat() False {-is_socket-} False {-non-blocking-} fD' <- FD.setNonBlockingMode fD True -- see #3316 enc <- getLocaleEncoding mkHandleFromFD fD' fd_type filepath mode False {-is_socket-} (Just enc)
phischu/fragnix
tests/packages/scotty/System.Process.Common.hs
bsd-3-clause
9,966
0
15
3,536
1,211
710
501
132
2
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ko-KR"> <title>Revisit | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
0xkasun/security-tools
src/org/zaproxy/zap/extension/revisit/resources/help_ko_KR/helpset_ko_KR.hs
apache-2.0
969
80
66
159
413
209
204
-1
-1
import Graphics.UI.Gtk main :: IO () main = do initGUI window <- windowNew set window [windowTitle := "Paned Window", containerBorderWidth := 10, windowDefaultWidth := 400, windowDefaultHeight := 400 ] pw <- vPanedNew panedSetPosition pw 250 containerAdd window pw af <- aspectFrameNew 0.5 0.5 (Just 3.0) frameSetLabel af "Aspect Ratio: 3.0" frameSetLabelAlign af 1.0 0.0 panedAdd1 pw af da <- drawingAreaNew containerAdd af da widgetModifyBg da StateNormal (Color 65535 0 0) tv <- textViewNew panedAdd2 pw tv buf <- textViewGetBuffer tv onBufferChanged buf $ do cn <- textBufferGetCharCount buf putStrLn (show cn) widgetShowAll window onDestroy window mainQuit mainGUI
thiagoarrais/gtk2hs
docs/tutorial/Tutorial_Port/Example_Code/GtkChap6-4.hs
lgpl-2.1
830
0
12
257
246
107
139
25
1
{-# LANGUAGE TypeOperators, MultiParamTypeClasses, FlexibleInstances #-} {-# OPTIONS_GHC -Wall #-} module Mixin where import Prelude hiding (log) class a <: b where up :: a -> b instance (t1 <: t2) => (t -> t1) <: (t -> t2) where up f = up . f instance (t1 <: t2) => (t2 -> t) <: (t1 -> t) where up f = f . up type Class t = t -> t type Mixin s t = s -> t -> t new :: Class a -> a new f = let r = f r in r with :: (t <: s) => Class s -> Mixin s t -> Class t klass `with` mixin = \this -> mixin (klass (up this)) this -- The below provides an example. fib' :: Class (Int -> Int) fib' _ 1 = 1 fib' _ 2 = 1 fib' this n = this (n-1) + this (n-2) instance (Int, String) <: Int where up = fst logging :: Mixin (Int -> Int) (Int -> (Int, String)) logging super _ 1 = (super 1, "1") logging super _ 2 = (super 2, "2 1") logging super this n = (super n, show n ++ " " ++ log1 ++ " " ++ log2) where (_, log1) = this (n-1) (_, log2) = this (n-2) fibWithLogging :: Int -> (Int, String) fibWithLogging = new (fib' `with` logging)
bixuanzju/fcore
lib/Mixin.hs
bsd-2-clause
1,062
0
10
278
541
290
251
30
1
module Head where {-@ measure hd :: [a] -> a hd (x:xs) = x @-} -- Strengthened constructors -- data [a] where -- [] :: [a] -- as before -- (:) :: x:a -> xs:[a] -> {v:[a] | hd v = x} {-@ cons :: x:a -> _ -> {v:[a] | hd v = x} @-} cons x xs = x : xs {-@ test :: {v:_ | hd v = 0} @-} test :: [Int] test = cons 0 [1,2,3,4]
abakst/liquidhaskell
tests/todo/partialmeasureOld.hs
bsd-3-clause
356
0
6
118
55
35
20
4
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} module Bug where import Data.Kind type HRank1 ty = forall k1. k1 -> ty type HRank2 ty = forall k2. k2 -> ty data HREFL11 :: HRank1 (HRank1 Type) -- FAILS data HREFL12 :: HRank1 (HRank2 Type) data HREFL21 :: HRank2 (HRank1 Type) data HREFL22 :: HRank2 (HRank2 Type) -- FAILS
sdiehl/ghc
testsuite/tests/polykinds/T14515.hs
bsd-3-clause
359
0
7
66
106
63
43
-1
-1
module Main where import GHC import MonadUtils import System.Environment main :: IO () main = do [libdir] <- getArgs runGhc (Just libdir) doit doit :: Ghc () doit = do getSessionDynFlags >>= setSessionDynFlags dyn <- dynCompileExpr "()" liftIO $ print dyn
siddhanathan/ghc
testsuite/tests/ghc-api/dynCompileExpr/dynCompileExpr.hs
bsd-3-clause
278
0
9
63
96
48
48
12
1
{-# LANGUAGE TypeFamilies #-} module T1897b where import Control.Monad import Data.Maybe class Bug s where type Depend s next :: s -> Depend s -> Maybe s start :: s -- isValid :: (Bug s) => [Depend s] -> Bool -- Inferred type should be rejected as ambiguous isValid ds = isJust $ foldM next start ds
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/indexed-types/should_fail/T1897b.hs
bsd-3-clause
316
0
9
73
73
40
33
9
1
{-# OPTIONS_GHC -fno-safe-infer #-} -- | Basic test to see if no safe infer flag compiles -- This module would usually infer safely, so it shouldn't be safe now. -- We don't actually check that here though, see test '' for that. module SafeFlags27 where f :: Int f = 1
wxwxwwxxx/ghc
testsuite/tests/safeHaskell/flags/SafeFlags27.hs
bsd-3-clause
271
0
4
53
18
13
5
4
1
{-# OPTIONS_GHC -Wno-overlapping-patterns -Wno-incomplete-patterns -Wno-incomplete-uni-patterns -Wno-incomplete-record-updates #-} -- | Index simplification mechanics. module Futhark.Optimise.Simplify.Rules.Index ( IndexResult (..), simplifyIndexing, ) where import Data.Maybe import Futhark.Analysis.PrimExp.Convert import qualified Futhark.Analysis.SymbolTable as ST import Futhark.Construct import Futhark.IR import Futhark.Optimise.Simplify.Rules.Simple import Futhark.Util isCt1 :: SubExp -> Bool isCt1 (Constant v) = oneIsh v isCt1 _ = False isCt0 :: SubExp -> Bool isCt0 (Constant v) = zeroIsh v isCt0 _ = False -- | Some index expressions can be simplified to t'SubExp's, while -- others produce another index expression (which may be further -- simplifiable). data IndexResult = IndexResult Certs VName (Slice SubExp) | SubExpResult Certs SubExp -- | Try to simplify an index operation. simplifyIndexing :: MonadBuilder m => ST.SymbolTable (Rep m) -> TypeLookup -> VName -> Slice SubExp -> Bool -> Maybe (m IndexResult) simplifyIndexing vtable seType idd (Slice inds) consuming = case defOf idd of _ | Just t <- seType (Var idd), Slice inds == fullSlice t [] -> Just $ pure $ SubExpResult mempty $ Var idd | Just inds' <- sliceIndices (Slice inds), Just (ST.Indexed cs e) <- ST.index idd inds' vtable, worthInlining e, all (`ST.elem` vtable) (unCerts cs) -> Just $ SubExpResult cs <$> toSubExp "index_primexp" e | Just inds' <- sliceIndices (Slice inds), Just (ST.IndexedArray cs arr inds'') <- ST.index idd inds' vtable, all (worthInlining . untyped) inds'', arr `ST.available` vtable, all (`ST.elem` vtable) (unCerts cs) -> Just $ IndexResult cs arr . Slice . map DimFix <$> mapM (toSubExp "index_primexp") inds'' Nothing -> Nothing Just (SubExp (Var v), cs) -> Just $ pure $ IndexResult cs v $ Slice inds Just (Iota _ x s to_it, cs) | [DimFix ii] <- inds, Just (Prim (IntType from_it)) <- seType ii -> Just $ let mul = BinOpExp $ Mul to_it OverflowWrap add = BinOpExp $ Add to_it OverflowWrap in fmap (SubExpResult cs) $ toSubExp "index_iota" $ ( sExt to_it (primExpFromSubExp (IntType from_it) ii) `mul` primExpFromSubExp (IntType to_it) s ) `add` primExpFromSubExp (IntType to_it) x | [DimSlice i_offset i_n i_stride] <- inds -> Just $ do i_offset' <- asIntS to_it i_offset i_stride' <- asIntS to_it i_stride let mul = BinOpExp $ Mul to_it OverflowWrap add = BinOpExp $ Add to_it OverflowWrap i_offset'' <- toSubExp "iota_offset" $ ( primExpFromSubExp (IntType to_it) x `mul` primExpFromSubExp (IntType to_it) s ) `add` primExpFromSubExp (IntType to_it) i_offset' i_stride'' <- letSubExp "iota_offset" $ BasicOp $ BinOp (Mul Int64 OverflowWrap) s i_stride' fmap (SubExpResult cs) $ letSubExp "slice_iota" $ BasicOp $ Iota i_n i_offset'' i_stride'' to_it -- A rotate cannot be simplified away if we are slicing a rotated dimension. Just (Rotate offsets a, cs) | not $ or $ zipWith rotateAndSlice offsets inds -> Just $ do dims <- arrayDims <$> lookupType a let adjustI i o d = do i_p_o <- letSubExp "i_p_o" $ BasicOp $ BinOp (Add Int64 OverflowWrap) i o letSubExp "rot_i" (BasicOp $ BinOp (SMod Int64 Unsafe) i_p_o d) adjust (DimFix i, o, d) = DimFix <$> adjustI i o d adjust (DimSlice i n s, o, d) = DimSlice <$> adjustI i o d <*> pure n <*> pure s IndexResult cs a . Slice <$> mapM adjust (zip3 inds offsets dims) where rotateAndSlice r DimSlice {} = not $ isCt0 r rotateAndSlice _ _ = False Just (Index aa ais, cs) -> Just $ IndexResult cs aa <$> subExpSlice (sliceSlice (primExpSlice ais) (primExpSlice (Slice inds))) Just (Replicate (Shape [_]) (Var vv), cs) | [DimFix {}] <- inds, not consuming, ST.available vv vtable -> Just $ pure $ SubExpResult cs $ Var vv | DimFix {} : is' <- inds, not consuming, ST.available vv vtable -> Just $ pure $ IndexResult cs vv $ Slice is' Just (Replicate (Shape [_]) val@(Constant _), cs) | [DimFix {}] <- inds, not consuming -> Just $ pure $ SubExpResult cs val Just (Replicate (Shape ds) v, cs) | (ds_inds, rest_inds) <- splitAt (length ds) inds, (ds', ds_inds') <- unzip $ mapMaybe index ds_inds, ds' /= ds -> Just $ do arr <- letExp "smaller_replicate" $ BasicOp $ Replicate (Shape ds') v return $ IndexResult cs arr $ Slice $ ds_inds' ++ rest_inds where index DimFix {} = Nothing index (DimSlice _ n s) = Just (n, DimSlice (constant (0 :: Int64)) n s) Just (Rearrange perm src, cs) | rearrangeReach perm <= length (takeWhile isIndex inds) -> let inds' = rearrangeShape (rearrangeInverse perm) inds in Just $ pure $ IndexResult cs src $ Slice inds' where isIndex DimFix {} = True isIndex _ = False Just (Copy src, cs) | Just dims <- arrayDims <$> seType (Var src), length inds == length dims, -- It is generally not safe to simplify a slice of a copy, -- because the result may be used in an in-place update of the -- original. But we know this can only happen if the original -- is bound the same depth as we are! all (isJust . dimFix) inds || maybe True ((ST.loopDepth vtable /=) . ST.entryDepth) (ST.lookup src vtable), not consuming, ST.available src vtable -> Just $ pure $ IndexResult cs src $ Slice inds Just (Reshape newshape src, cs) | Just newdims <- shapeCoercion newshape, Just olddims <- arrayDims <$> seType (Var src), changed_dims <- zipWith (/=) newdims olddims, not $ or $ drop (length inds) changed_dims -> Just $ pure $ IndexResult cs src $ Slice inds | Just newdims <- shapeCoercion newshape, Just olddims <- arrayDims <$> seType (Var src), length newshape == length inds, length olddims == length newdims -> Just $ pure $ IndexResult cs src $ Slice inds Just (Reshape [_] v2, cs) | Just [_] <- arrayDims <$> seType (Var v2) -> Just $ pure $ IndexResult cs v2 $ Slice inds Just (Concat d x xs _, cs) | -- HACK: simplifying the indexing of an N-array concatenation -- is going to produce an N-deep if expression, which is bad -- when N is large. To try to avoid that, we use the -- heuristic not to simplify as long as any of the operands -- are themselves Concats. The hope it that this will give -- simplification some time to cut down the concatenation to -- something smaller, before we start inlining. not $ any isConcat $ x : xs, Just (ibef, DimFix i, iaft) <- focusNth d inds, Just (Prim res_t) <- (`setArrayDims` sliceDims (Slice inds)) <$> ST.lookupType x vtable -> Just $ do x_len <- arraySize d <$> lookupType x xs_lens <- mapM (fmap (arraySize d) . lookupType) xs let add n m = do added <- letSubExp "index_concat_add" $ BasicOp $ BinOp (Add Int64 OverflowWrap) n m return (added, n) (_, starts) <- mapAccumLM add x_len xs_lens let xs_and_starts = reverse $ zip xs starts let mkBranch [] = letSubExp "index_concat" $ BasicOp $ Index x $ Slice $ ibef ++ DimFix i : iaft mkBranch ((x', start) : xs_and_starts') = do cmp <- letSubExp "index_concat_cmp" $ BasicOp $ CmpOp (CmpSle Int64) start i (thisres, thisstms) <- collectStms $ do i' <- letSubExp "index_concat_i" $ BasicOp $ BinOp (Sub Int64 OverflowWrap) i start letSubExp "index_concat" . BasicOp . Index x' $ Slice $ ibef ++ DimFix i' : iaft thisbody <- mkBodyM thisstms [subExpRes thisres] (altres, altstms) <- collectStms $ mkBranch xs_and_starts' altbody <- mkBodyM altstms [subExpRes altres] letSubExp "index_concat_branch" $ If cmp thisbody altbody $ IfDec [primBodyType res_t] IfNormal SubExpResult cs <$> mkBranch xs_and_starts Just (ArrayLit ses _, cs) | DimFix (Constant (IntValue (Int64Value i))) : inds' <- inds, Just se <- maybeNth i ses -> case inds' of [] -> Just $ pure $ SubExpResult cs se _ | Var v2 <- se -> Just $ pure $ IndexResult cs v2 $ Slice inds' _ -> Nothing -- Indexing single-element arrays. We know the index must be 0. _ | Just t <- seType $ Var idd, isCt1 $ arraySize 0 t, DimFix i : inds' <- inds, not $ isCt0 i -> Just . pure . IndexResult mempty idd . Slice $ DimFix (constant (0 :: Int64)) : inds' _ -> Nothing where defOf v = do (BasicOp op, def_cs) <- ST.lookupExp v vtable return (op, def_cs) worthInlining e | primExpSizeAtLeast 20 e = False -- totally ad-hoc. | otherwise = worthInlining' e worthInlining' (BinOpExp Pow {} _ _) = False worthInlining' (BinOpExp FPow {} _ _) = False worthInlining' (BinOpExp _ x y) = worthInlining' x && worthInlining' y worthInlining' (CmpOpExp _ x y) = worthInlining' x && worthInlining' y worthInlining' (ConvOpExp _ x) = worthInlining' x worthInlining' (UnOpExp _ x) = worthInlining' x worthInlining' FunExp {} = False worthInlining' _ = True isConcat v | Just (Concat {}, _) <- defOf v = True | otherwise = False
HIPERFIT/futhark
src/Futhark/Optimise/Simplify/Rules/Index.hs
isc
10,142
0
27
3,150
3,402
1,634
1,768
206
31
module Extras where import Data.Char class Show a => PrettyShow a where prettyShow :: a -> String prettyShow x = show x unique :: Eq a => [a] -> [a] unique [] = [] unique (x:xs) = if x `elem` xs then unique xs else (x:unique xs) toLowercase :: String -> String toLowercase = map toLower trimLeft :: String -> String trimLeft [] = [] trimLeft xx@(x:xs) | isSpace x = trimLeft xs | otherwise = xx trimRight :: String -> String trimRight = reverse . trimLeft . reverse trim :: String -> String trim = trimLeft . trimRight
fredmorcos/attic
snippets/haskell/QuickCheck/Extras.hs
isc
538
0
8
118
238
124
114
19
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} -- | This module defines a convenience typeclass for creating -- normalised programs. -- -- See "Futhark.Construct" for a high-level description. module Futhark.Builder.Class ( Buildable (..), mkLet, mkLet', MonadBuilder (..), insertStms, insertStm, letBind, letBindNames, collectStms_, bodyBind, attributing, auxing, module Futhark.MonadFreshNames, ) where import qualified Data.Kind import Futhark.IR import Futhark.MonadFreshNames -- | The class of representations that can be constructed solely from -- an expression, within some monad. Very important: the methods -- should not have any significant side effects! They may be called -- more often than you think, and the results thrown away. If used -- exclusively within a 'MonadBuilder' instance, it is acceptable for -- them to create new bindings, however. class ( ASTRep rep, FParamInfo rep ~ DeclType, LParamInfo rep ~ Type, RetType rep ~ DeclExtType, BranchType rep ~ ExtType, SetType (LetDec rep) ) => Buildable rep where mkExpPat :: [Ident] -> Exp rep -> Pat rep mkExpDec :: Pat rep -> Exp rep -> ExpDec rep mkBody :: Stms rep -> Result -> Body rep mkLetNames :: (MonadFreshNames m, HasScope rep m) => [VName] -> Exp rep -> m (Stm rep) -- | A monad that supports the creation of bindings from expressions -- and bodies from bindings, with a specific rep. This is the main -- typeclass that a monad must implement in order for it to be useful -- for generating or modifying Futhark code. Most importantly -- maintains a current state of 'Stms' (as well as a 'Scope') that -- have been added with 'addStm'. -- -- Very important: the methods should not have any significant side -- effects! They may be called more often than you think, and the -- results thrown away. It is acceptable for them to create new -- bindings, however. class ( ASTRep (Rep m), MonadFreshNames m, Applicative m, Monad m, LocalScope (Rep m) m ) => MonadBuilder m where type Rep m :: Data.Kind.Type mkExpDecM :: Pat (Rep m) -> Exp (Rep m) -> m (ExpDec (Rep m)) mkBodyM :: Stms (Rep m) -> Result -> m (Body (Rep m)) mkLetNamesM :: [VName] -> Exp (Rep m) -> m (Stm (Rep m)) -- | Add a statement to the 'Stms' under construction. addStm :: Stm (Rep m) -> m () addStm = addStms . oneStm -- | Add multiple statements to the 'Stms' under construction. addStms :: Stms (Rep m) -> m () -- | Obtain the statements constructed during a monadic action, -- instead of adding them to the state. collectStms :: m a -> m (a, Stms (Rep m)) -- | Add the provided certificates to any statements added during -- execution of the action. certifying :: Certs -> m a -> m a certifying = censorStms . fmap . certify -- | Apply a function to the statements added by this action. censorStms :: MonadBuilder m => (Stms (Rep m) -> Stms (Rep m)) -> m a -> m a censorStms f m = do (x, stms) <- collectStms m addStms $ f stms return x -- | Add the given attributes to any statements added by this action. attributing :: MonadBuilder m => Attrs -> m a -> m a attributing attrs = censorStms $ fmap onStm where onStm (Let pat aux e) = Let pat aux {stmAuxAttrs = attrs <> stmAuxAttrs aux} e -- | Add the certificates and attributes to any statements added by -- this action. auxing :: MonadBuilder m => StmAux anyrep -> m a -> m a auxing (StmAux cs attrs _) = censorStms $ fmap onStm where onStm (Let pat aux e) = Let pat aux' e where aux' = aux { stmAuxAttrs = attrs <> stmAuxAttrs aux, stmAuxCerts = cs <> stmAuxCerts aux } -- | Add a statement with the given pattern and expression. letBind :: MonadBuilder m => Pat (Rep m) -> Exp (Rep m) -> m () letBind pat e = addStm =<< Let pat <$> (defAux <$> mkExpDecM pat e) <*> pure e -- | Construct a 'Stm' from identifiers for the context- and value -- part of the pattern, as well as the expression. mkLet :: Buildable rep => [Ident] -> Exp rep -> Stm rep mkLet ids e = let pat = mkExpPat ids e dec = mkExpDec pat e in Let pat (defAux dec) e -- | Like mkLet, but also take attributes and certificates from the -- given 'StmAux'. mkLet' :: Buildable rep => [Ident] -> StmAux a -> Exp rep -> Stm rep mkLet' ids (StmAux cs attrs _) e = let pat = mkExpPat ids e dec = mkExpDec pat e in Let pat (StmAux cs attrs dec) e -- | Add a statement with the given pattern element names and -- expression. letBindNames :: MonadBuilder m => [VName] -> Exp (Rep m) -> m () letBindNames names e = addStm =<< mkLetNamesM names e -- | As 'collectStms', but throw away the ordinary result. collectStms_ :: MonadBuilder m => m a -> m (Stms (Rep m)) collectStms_ = fmap snd . collectStms -- | Add the statements of the body, then return the body result. bodyBind :: MonadBuilder m => Body (Rep m) -> m Result bodyBind (Body _ stms res) = do addStms stms pure res -- | Add several bindings at the outermost level of a t'Body'. insertStms :: Buildable rep => Stms rep -> Body rep -> Body rep insertStms stms1 (Body _ stms2 res) = mkBody (stms1 <> stms2) res -- | Add a single binding at the outermost level of a t'Body'. insertStm :: Buildable rep => Stm rep -> Body rep -> Body rep insertStm = insertStms . oneStm
HIPERFIT/futhark
src/Futhark/Builder/Class.hs
isc
5,424
0
13
1,270
1,421
722
699
-1
-1
-- | Multicore imperative code. module Futhark.CodeGen.ImpCode.Multicore ( Program, Function, FunctionT (Function), Code, Multicore (..), Scheduling (..), SchedulerInfo (..), AtomicOp (..), ParallelTask (..), module Futhark.CodeGen.ImpCode, ) where import Futhark.CodeGen.ImpCode hiding (Code, Function) import qualified Futhark.CodeGen.ImpCode as Imp import Futhark.Util.Pretty -- | An imperative program. type Program = Imp.Functions Multicore -- | An imperative function. type Function = Imp.Function Multicore -- | A piece of imperative code, with multicore operations inside. type Code = Imp.Code Multicore -- | A multicore operation. data Multicore = Segop String [Param] ParallelTask (Maybe ParallelTask) [Param] SchedulerInfo | ParLoop String VName Code Code Code [Param] VName | Atomic AtomicOp -- | Atomic operations return the value stored before the update. -- This old value is stored in the first 'VName'. The second 'VName' -- is the memory block to update. The 'Exp' is the new value. data AtomicOp = AtomicAdd IntType VName VName (Count Elements (Imp.TExp Int32)) Exp | AtomicSub IntType VName VName (Count Elements (Imp.TExp Int32)) Exp | AtomicAnd IntType VName VName (Count Elements (Imp.TExp Int32)) Exp | AtomicOr IntType VName VName (Count Elements (Imp.TExp Int32)) Exp | AtomicXor IntType VName VName (Count Elements (Imp.TExp Int32)) Exp | AtomicXchg PrimType VName VName (Count Elements (Imp.TExp Int32)) Exp | AtomicCmpXchg PrimType VName VName (Count Elements (Imp.TExp Int32)) VName Exp deriving (Show) instance FreeIn AtomicOp where freeIn' (AtomicAdd _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x freeIn' (AtomicSub _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x freeIn' (AtomicAnd _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x freeIn' (AtomicOr _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x freeIn' (AtomicXor _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x freeIn' (AtomicCmpXchg _ _ arr i retval x) = freeIn' arr <> freeIn' i <> freeIn' x <> freeIn' retval freeIn' (AtomicXchg _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x data SchedulerInfo = SchedulerInfo { nsubtasks :: VName, -- The variable that describes how many subtasks the scheduler created iterations :: Imp.Exp, -- The number of total iterations for a task scheduling :: Scheduling -- The type scheduling for the task } data ParallelTask = ParallelTask { task_code :: Code, flatTid :: VName -- The variable for the thread id execution the code } -- | Whether the Scheduler should schedule the tasks as Dynamic -- or it is restainted to Static data Scheduling = Dynamic | Static instance Pretty Scheduling where ppr Dynamic = text "Dynamic" ppr Static = text "Static" -- TODO fix all of this! instance Pretty SchedulerInfo where ppr (SchedulerInfo nsubtask i sched) = text "SchedulingInfo" <+> text "number of subtasks" <+> ppr nsubtask <+> text "scheduling" <+> ppr sched <+> text "iter" <+> ppr i instance Pretty ParallelTask where ppr (ParallelTask code _) = ppr code instance Pretty Multicore where ppr (Segop s free _par_code seq_code retval scheduler) = text "parfor" <+> ppr scheduler <+> ppr free <+> text s <+> text "seq_code" <+> nestedBlock "{" "}" (ppr seq_code) <+> text "retvals" <+> ppr retval ppr (ParLoop s i prebody body postbody params info) = text "parloop" <+> ppr s <+> ppr i <+> ppr prebody <+> ppr params <+> ppr info <+> langle <+> nestedBlock "{" "}" (ppr body) <+> ppr postbody ppr (Atomic _) = text "AtomicOp" instance FreeIn SchedulerInfo where freeIn' (SchedulerInfo nsubtask iter _) = freeIn' iter <> freeIn' nsubtask instance FreeIn ParallelTask where freeIn' (ParallelTask code _) = freeIn' code instance FreeIn Multicore where freeIn' (Segop _ _ par_code seq_code _ info) = freeIn' par_code <> freeIn' seq_code <> freeIn' info freeIn' (ParLoop _ _ prebody body postbody _ _) = freeIn' prebody <> fvBind (Imp.declaredIn prebody) (freeIn' $ body <> postbody) freeIn' (Atomic aop) = freeIn' aop
HIPERFIT/futhark
src/Futhark/CodeGen/ImpCode/Multicore.hs
isc
4,250
0
14
932
1,286
658
628
96
0
-- The task is to refactor given functions into more Haskell idiomatic style ------------------------ (1) ---------------------------- -- Before: fun1 :: [Integer] -> Integer fun1 [] = 1 fun1 (x:xs) | even x = (x - 2) * fun1 xs | otherwise = fun1 xs -- After: fun1' :: [Integer] -> Integer fun1' = product . map (subtract 2) . (filter even) ------------------------ (2) ---------------------------- -- Before: fun2 :: Integer -> Integer fun2 1 = 0 fun2 n | even n = n + fun2 (n `div` 2) | otherwise = fun2 (3 * n + 1) -- After fun2' :: Integer -> Integer fun2' = sum .filter even .takeWhile (>1) .iterate (\x -> if (even x) then (x `div` 2) else (3*x + 1))
vaibhav276/haskell_cs194_assignments
higher_order/Wholemeal.hs
mit
702
3
11
169
272
144
128
16
2
module Instances where import Language.Haskell.Syntax import qualified Language.Haskell.Pretty as P import Niz import Data.List ------------------------------------------------------------------------------- ---------------- INSTANCE DECLARATIONS ---------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ---------------------- LENGTH OF HSEXP -------------------------------------- ------------------------------------------------------------------------------- --class Size a where -- size :: a -> Int instance Size HsName where size _ = 1 instance Size HsQName where -- size (Special HsCons) = 0 size _ = 1 instance Size HsLiteral where size (HsInt i) = length $ show i size _ = 1 instance Size HsQualType where size _ = 1 instance Size HsQOp where size (HsQVarOp x) = size x size (HsQConOp x) = size x instance Size HsExp where size e = case e of HsVar n -> size n HsCon n -> size n HsLit x -> size x HsInfixApp e1 op e2 -> size e1 + size e2 + size op HsApp (HsVar _) e2 -> size e2 + 1 HsApp (HsCon _) e2 -> size e2 + 1 HsApp e1 e2 -> size e1 + size e2 HsNegApp e -> 1 + size e HsLambda _ pats e -> size e + size pats HsLet decs e -> size e + size decs HsIf e1 e2 e3 -> 1 + size e1 + size e2 + size e3 HsCase e alts -> size e + size alts HsDo stmts -> size stmts HsTuple es -> sum $ map size es HsList [] -> 1 HsList es -> sum $ map size es -- size es HsParen e -> size e HsLeftSection e op -> size e + size op HsRightSection op e -> size e + size op HsRecConstr n fields -> size n + size fields HsRecUpdate e fields -> size e + size fields HsEnumFrom e -> 1 + size e HsEnumFromTo e1 e2 -> 1 + size e1 + size e2 HsEnumFromThen e1 e2 -> 1 + size e1 + size e2 HsEnumFromThenTo e1 e2 e3 -> 1 + size e1 + size e2 + size e3 HsListComp e stmts -> size e + size stmts HsExpTypeSig _ e t -> size e + size t HsAsPat n e -> size n + size e HsWildCard -> 0 HsIrrPat e -> size e instance Size HsStmt where size s = case s of HsGenerator _ p e -> size p + size e HsQualifier e -> size e HsLetStmt decs -> size decs instance Size HsPat where size p = case p of HsPVar n -> size n HsPLit l -> size l HsPNeg p -> 1 + size p HsPInfixApp p1 n p2 -> size p1 + size n + size p2 HsPApp n pats -> 1 + (sum $ map size pats) HsPTuple pats -> sum $ map size pats HsPList [] -> 1 HsPList pats -> sum $ map size pats HsPParen p -> size p HsPRec n fields -> size n + size fields HsPAsPat n p -> size n + size p HsPWildCard -> 0 HsPIrrPat p -> size p instance Size HsPatField where size (HsPFieldPat n p) = size n + size p instance Size HsDecl where size d = case d of HsTypeDecl _ name names htype -> size name + size names + size htype HsDataDecl _ ss name names cons qnames -> size name + size names + size cons + size qnames + size ss HsInfixDecl _ assoc _ ops -> 2 + size ops HsNewTypeDecl _ c name names con qname -> size c + size name + size names + size con + size qname HsClassDecl _ c name names decs -> size c + size name + size names + size decs HsInstDecl _ c qname types decs -> size c + size qname + size types + size decs HsDefaultDecl _ types -> size types HsTypeSig _ names qtype -> size qtype + size names HsFunBind ms -> sum $ map size ms HsPatBind _ pat rhs decs -> size pat + size rhs + size decs HsForeignImport _ s1 safety s2 hname htype -> 3 + size hname + size htype HsForeignExport _ s1 s2 name htype -> 2 + size name + size htype instance Size HsType where size t = case t of HsTyFun t1 t2 -> size t1 + size t2 HsTyTuple types -> size types HsTyApp t1 t2 -> size t1 + size t2 HsTyVar n -> size n HsTyCon n -> size n instance (Size a, Size b) => Size (a,b) where size (a,b) = size a + size b -- instance Size a => Size [a] where -- size xs = sum (map size xs) instance Size HsMatch where size (HsMatch _ name pats rhs decs) = 1 + sum (map size pats) + size rhs instance Size HsRhs where size (HsUnGuardedRhs e) = size e size (HsGuardedRhss x) = size x instance Size HsGuardedRhs where size (HsGuardedRhs _ e1 e2) = size e1 + size e2 instance Size HsConDecl where size (HsConDecl _ name list) = size name + size list size (HsRecDecl _ name list) = size name + size list instance Size HsBangType where size (HsBangedTy x) = size x size (HsUnBangedTy x) = size x instance Size HsOp where size (HsVarOp x) = size x size (HsConOp x) = size x instance Size HsAlt where size (HsAlt _ pat alts decs) = size pat + size alts + size decs instance Size HsGuardedAlts where size (HsUnGuardedAlt exp) = size exp size (HsGuardedAlts xs) = size xs instance Size HsGuardedAlt where size (HsGuardedAlt _ e1 e2) = size e1 + size e2 instance Size HsFieldUpdate where size (HsFieldUpdate qname exp) = size qname + size exp instance Ord HsLiteral where compare (HsChar x) (HsChar y) = compare x y compare (HsChar _) _ = LT compare _ (HsChar _) = GT compare (HsString x) (HsString y) = compare x y compare (HsString _) _ = LT compare _ (HsString _) = GT compare (HsInt x) (HsInt y) = compare x y compare (HsInt _) _ = LT compare _ (HsInt _) = GT compare (HsFrac x) (HsFrac y) = compare x y compare (HsFrac _) _ = LT compare _ (HsFrac _) = GT compare (HsCharPrim x) (HsCharPrim y) = compare x y compare (HsCharPrim _) _ = LT compare _ (HsCharPrim _) = GT compare (HsStringPrim x) (HsStringPrim y) = compare x y compare (HsStringPrim _) _ = LT compare _ (HsStringPrim _) = GT compare (HsIntPrim x) (HsIntPrim y) = compare x y compare (HsIntPrim _) _ = LT compare _ (HsIntPrim _) = GT compare (HsFloatPrim x) (HsFloatPrim y) = compare x y compare (HsFloatPrim _) _ = LT compare _ (HsFloatPrim _) = GT compare (HsDoublePrim x) (HsDoublePrim y) = compare x y instance Ord HsPat where compare (HsPVar x) (HsPVar y) = compare x y compare (HsPVar _) _ = LT compare _ (HsPVar _) = GT compare (HsPLit x) (HsPLit y) = compare x y compare (HsPLit _) _ = LT compare _ (HsPLit _) = GT compare (HsPNeg x) (HsPNeg y) = compare x y compare (HsPNeg _) _ = LT compare _ (HsPNeg _) = GT compare (HsPInfixApp p1 n1 q1) (HsPInfixApp p2 n2 q2) | n1 == n2 = compare [p1,q1] [p2,q2] compare (HsPInfixApp _ n1 _) (HsPInfixApp _ n2 _) = compare n1 n2 compare (HsPInfixApp _ _ _) _ = LT compare _ (HsPInfixApp _ _ _) = GT compare (HsPApp n1 p1) (HsPApp n2 p2) | n1 == n2 = compare p1 p2 compare (HsPApp n1 _) (HsPApp n2 _) = compare n1 n2 compare (HsPApp _ _) _ = LT compare _ (HsPApp _ _) = GT compare (HsPTuple p1) (HsPTuple p2) = compare p1 p2 compare (HsPTuple _) _ = LT compare _ (HsPTuple _) = GT compare (HsPList p1) (HsPList p2) = compare p1 p2 compare (HsPList _) _ = LT compare _ (HsPList _) = GT compare (HsPParen p1) (HsPParen p2) = compare p1 p2 compare (HsPParen _) _ = LT compare _ (HsPParen _) = GT compare (HsPRec n1 p1) (HsPRec n2 p2) | n1 == n2 = compare p1 p2 compare (HsPRec n1 _) (HsPRec n2 _) = compare n1 n2 compare (HsPRec _ _) _ = LT compare _ (HsPRec _ _) = GT compare (HsPAsPat n1 p1) (HsPAsPat n2 p2) | n1 == n2 = compare p1 p2 compare (HsPAsPat n1 _) (HsPAsPat n2 _) = compare n1 n2 compare (HsPAsPat _ _) _ = LT compare _ (HsPAsPat _ _) = GT compare HsPWildCard _ = LT compare _ HsPWildCard = GT compare (HsPIrrPat x) (HsPIrrPat y) = compare x y instance Ord HsPatField where compare (HsPFieldPat n1 p1) (HsPFieldPat n2 p2) | n1 == n2 = compare p1 p2 compare (HsPFieldPat n1 _) (HsPFieldPat n2 _) = compare n1 n2 instance Ord HsExp where compare (HsLit x) (HsLit y) = compare x y compare (HsLit _) _ = LT compare _ (HsLit _) = GT compare (HsCon x) (HsCon y) = compare x y compare (HsCon _) _ = LT compare _ (HsCon _) = GT compare (HsVar x) (HsVar y) = compare x y compare (HsVar _) _ = LT compare _ (HsVar _) = GT compare (HsParen x) (HsParen y) = compare x y compare (HsParen _) _ = LT compare _ (HsParen _) = GT compare (HsNegApp x) (HsNegApp y) = compare x y compare (HsNegApp _) _ = LT compare _ (HsNegApp _) = GT compare (HsApp x1 x2) (HsApp y1 y2) = compare [x1,x2] [y1,y2] compare (HsApp _ _) _ = LT compare _ (HsApp _ _) = GT compare (HsTuple x) (HsTuple y) = compare x y compare (HsTuple _) _ = LT compare _ (HsTuple _) = GT compare (HsList x) (HsList y) = compare x y compare (HsList _) _ = LT compare _ (HsList _) = GT compare HsWildCard _ = LT compare _ HsWildCard = GT compare (HsAsPat n1 x) (HsAsPat n2 y) | n1 == n2 = compare x y compare (HsAsPat n1 _) (HsAsPat n2 _) = compare n1 n2 compare (HsAsPat _ _) _ = LT compare _ (HsAsPat _ _) = GT compare (HsLambda a b c) (HsLambda x y z) | a == x && b == y = compare c z compare (HsLambda a b c) (HsLambda x y z) | a == x = compare b y compare (HsLambda a b c) (HsLambda x y z) = compare a x compare (HsLambda _ _ _) _ = LT compare _ (HsLambda _ _ _) = GT compare (HsInfixApp x y z) (HsInfixApp a b c) | y == b = compare [x,z] [a,c] compare (HsInfixApp x y z) (HsInfixApp a b c) = compare y b compare (HsInfixApp _ _ _) _ = LT compare _ (HsInfixApp _ _ _) = GT compare (HsLet a b) (HsLet x y) = compare (a,b) (x,y) compare (HsLet _ _) _ = LT compare _ (HsLet _ _) = GT compare (HsIf a b c) (HsIf x y z) = compare (a,b,c) (x,y,z) compare (HsIf _ _ _) _ = LT compare _ (HsIf _ _ _) = GT compare (HsCase a b) (HsCase x y) = compare (a,b) (x,y) compare (HsCase _ _) _ = LT compare _ (HsCase _ _) = GT compare (HsDo x) (HsDo y) = compare x y compare (HsDo _) _ = LT compare _ (HsDo _) = GT compare (HsLeftSection a b) (HsLeftSection x y) = compare (a,b) (x,y) compare (HsLeftSection _ _) _ = LT compare _ (HsLeftSection _ _) = GT compare (HsRightSection a b) (HsRightSection x y) = compare (a,b) (x,y) compare (HsRightSection _ _) _ = LT compare _ (HsRightSection _ _) = GT compare (HsRecConstr a b) (HsRecConstr x y) = compare (a,b) (x,y) compare (HsRecConstr _ _) _ = LT compare _ (HsRecConstr _ _) = GT compare (HsRecUpdate a b) (HsRecUpdate x y) = compare (a,b) (x,y) compare (HsRecUpdate _ _) _ = LT compare _ (HsRecUpdate _ _) = GT compare (HsEnumFrom x) (HsEnumFrom y) = compare x y compare (HsEnumFrom _) _ = LT compare _ (HsEnumFrom _) = GT compare (HsEnumFromTo a b) (HsEnumFromTo x y) = compare (a,b) (x,y) compare (HsEnumFromTo _ _) _ = LT compare _ (HsEnumFromTo _ _) = GT compare (HsEnumFromThen a b) (HsEnumFromThen x y) = compare (a,b) (x,y) compare (HsEnumFromThen _ _) _ = LT compare _ (HsEnumFromThen _ _) = GT compare (HsEnumFromThenTo a b c) (HsEnumFromThenTo x y z) = compare (a,b,c) (x,y,z) compare (HsEnumFromThenTo _ _ _) _ = LT compare _ (HsEnumFromThenTo _ _ _) = GT compare (HsListComp a b) (HsListComp x y) = compare (a,b) (x,y) compare (HsListComp _ _) _ = LT compare _ (HsListComp _ _) = GT compare (HsExpTypeSig a b c) (HsExpTypeSig x y z) = compare (a,b,c) (x,y,z) compare (HsExpTypeSig _ _ _) _ = LT compare _ (HsExpTypeSig _ _ _) = GT compare (HsIrrPat x) (HsIrrPat y) = compare x y instance Ord HsDecl where compare (HsTypeDecl a b c d) (HsTypeDecl w x y z) = compare (a,b,c,d) (w,x,y,z) compare (HsTypeDecl _ _ _ _) _ = LT compare _ (HsTypeDecl _ _ _ _) = GT compare (HsDataDecl a b c d e f) (HsDataDecl m n o p q r) = compare (a,b,c,d,e,f) (m,n,o,p,q,r) compare (HsDataDecl _ _ _ _ _ _) _ = LT compare _ (HsDataDecl _ _ _ _ _ _) = GT compare (HsInfixDecl a b c d) (HsInfixDecl w x y z) = compare (a,b,c,d) (w,x,y,z) compare (HsInfixDecl _ _ _ _) _ = LT compare _ (HsInfixDecl _ _ _ _) = GT compare (HsNewTypeDecl a b c d e f) (HsNewTypeDecl m n o p q r) = compare (a,b,c,d,e,f) (m,n,o,p,q,r) compare (HsNewTypeDecl _ _ _ _ _ _) _ = LT compare _ (HsNewTypeDecl _ _ _ _ _ _) = GT compare (HsClassDecl a b c d e) (HsClassDecl m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q) compare (HsClassDecl _ _ _ _ _) _ = LT compare _ (HsClassDecl _ _ _ _ _) = GT compare (HsInstDecl a b c d e) (HsInstDecl m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q) compare (HsInstDecl _ _ _ _ _) _ = LT compare _ (HsInstDecl _ _ _ _ _) = GT compare (HsDefaultDecl a b) (HsDefaultDecl x y) = compare (a,b) (x,y) compare (HsDefaultDecl _ _) _ = LT compare _ (HsDefaultDecl _ _) = GT compare (HsTypeSig a b c) (HsTypeSig x y z) = compare (a,b,c) (x,y,z) compare (HsTypeSig _ _ _) _ = LT compare _ (HsTypeSig _ _ _) = GT compare (HsFunBind a) (HsFunBind x) = compare a x compare (HsFunBind _) _ = LT compare _ (HsFunBind _) = GT compare (HsPatBind a b c d) (HsPatBind w x y z) = compare (a,b,c,d) (w,x,y,z) compare (HsPatBind _ _ _ _) _ = LT compare _ (HsPatBind _ _ _ _) = GT compare (HsForeignImport a b c d e f) (HsForeignImport m n o p q r) = compare (a,b,c,d,e,f) (m,n,o,p,q,r) compare (HsForeignImport _ _ _ _ _ _) _ = LT compare _ (HsForeignImport _ _ _ _ _ _) = GT compare (HsForeignExport a b c d e) (HsForeignExport m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q) instance Ord HsRhs where compare (HsUnGuardedRhs x) (HsUnGuardedRhs y) = compare x y compare (HsGuardedRhss x) (HsGuardedRhss y) = compare x y instance Ord HsGuardedRhs where compare (HsGuardedRhs a b c) (HsGuardedRhs x y z) = compare (a,b,c) (x,y,z) instance Ord HsMatch where compare (HsMatch a b c d e) (HsMatch m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q) instance Ord HsQualType where compare (HsQualType a b) (HsQualType x y) = compare (a,b) (x,y) instance Ord HsType where compare (HsTyFun a b) (HsTyFun x y) = compare (a,b) (x,y) compare (HsTyFun _ _) _ = LT compare _ (HsTyFun _ _) = GT compare (HsTyTuple x) (HsTyTuple y) = compare x y compare (HsTyTuple _) _ = LT compare _ (HsTyTuple _) = GT compare (HsTyApp a b) (HsTyApp x y) = compare (a,b) (x,y) compare (HsTyApp _ _) _ = LT compare _ (HsTyApp _ _) = GT compare (HsTyVar x) (HsTyVar y) = compare x y compare (HsTyVar _) _ = LT compare _ (HsTyVar _) = GT compare (HsTyCon x) (HsTyCon y) = compare x y instance Ord HsAssoc where compare HsAssocNone HsAssocNone = EQ compare HsAssocNone _ = LT compare _ HsAssocNone = GT compare HsAssocLeft HsAssocLeft = EQ compare HsAssocLeft _ = LT compare _ HsAssocLeft = GT compare HsAssocRight HsAssocRight = EQ instance Ord HsConDecl where compare (HsConDecl a b c) (HsConDecl x y z) = compare (a,b,c) (x,y,z) compare (HsConDecl _ _ _) _ = LT compare _ (HsConDecl _ _ _) = GT compare (HsRecDecl a b c) (HsRecDecl x y z) = compare (a,b,c) (x,y,z) instance Ord HsBangType where compare (HsBangedTy x) (HsBangedTy y) = compare x y compare (HsBangedTy _) _ = LT compare _ (HsBangedTy _) = GT compare (HsUnBangedTy x) (HsUnBangedTy y) = compare x y instance Ord HsFieldUpdate where compare (HsFieldUpdate a b) (HsFieldUpdate x y) = compare (a,b) (x,y) instance Ord HsStmt where compare (HsGenerator a b c) (HsGenerator x y z) = compare (a,b,c) (x,y,z) compare (HsGenerator _ _ _) _ = LT compare _ (HsGenerator _ _ _) = GT compare (HsQualifier x) (HsQualifier y) = compare x y compare (HsQualifier _) _ = LT compare _ (HsQualifier _) = GT compare (HsLetStmt x) (HsLetStmt y) = compare x y instance Ord HsAlt where compare (HsAlt a b c d) (HsAlt w x y z) = compare (a,b,c,d) (w,x,y,z) instance Ord HsGuardedAlts where compare (HsUnGuardedAlt x) (HsUnGuardedAlt y) = compare x y compare (HsUnGuardedAlt _) _ = LT compare _ (HsUnGuardedAlt _) = GT compare (HsGuardedAlts x) (HsGuardedAlts y) = compare x y instance Ord HsGuardedAlt where compare (HsGuardedAlt a b c) (HsGuardedAlt x y z) = compare (a,b,c) (x,y,z) class Pretty a where pretty :: a -> String instance Pretty HsModule where pretty x = P.prettyPrint x instance Pretty HsExportSpec where pretty x = P.prettyPrint x instance Pretty HsImportDecl where pretty x = P.prettyPrint x instance Pretty HsImportSpec where pretty x = P.prettyPrint x instance Pretty HsAssoc where pretty x = P.prettyPrint x instance Pretty HsDecl where pretty x = P.prettyPrint x instance Pretty HsConDecl where pretty x = P.prettyPrint x instance Pretty HsBangType where pretty x = P.prettyPrint x instance Pretty HsMatch where --pretty (HsMatch pos f ps rhs whereDecls) -- = pretty f ++ " " ++ concat (intersperse " " (map pretty ps)) ++ " = " ++ pretty rhs pretty x = P.prettyPrint x instance Pretty HsRhs where pretty x = P.prettyPrint x instance Pretty HsGuardedRhs where pretty x = P.prettyPrint x instance Pretty HsSafety where pretty x = P.prettyPrint x instance Pretty HsQualType where pretty x = P.prettyPrint x instance Pretty HsType where pretty x = P.prettyPrint x instance Pretty HsExp where pretty x = case x of HsVar name -> pretty name HsCon name -> pretty name HsList list -> (all isChar list) ? (let s = [c | (HsLit (HsChar c)) <- list] in P.prettyPrint (HsLit (HsString s))) $ P.prettyPrint (HsList list) HsApp x arg -> pretty x ++ " (" ++ pretty arg ++ ")" HsNegApp e@(HsNegApp _) -> "-(" ++ pretty e ++ ")" HsNegApp e -> "-" ++ pretty e HsParen e -> "(" ++ pretty e ++ ")" HsInfixApp e1 (HsQConOp (Special HsCons)) (HsLit (HsInt i)) -> let p = pretty e1 in if take 1 p == "(" then p ++ ":" ++ show i else p ++ show i HsInfixApp e1 op e2 -> "(" ++ pretty e1 ++ P.prettyPrint op ++ pretty e2 ++ ")" e -> P.prettyPrint e isChar (HsLit (HsChar _)) = True isChar _ = False instance Pretty HsStmt where pretty x = P.prettyPrint x instance Pretty HsFieldUpdate where pretty x = P.prettyPrint x instance Pretty HsAlt where pretty x = P.prettyPrint x instance Pretty HsGuardedAlts where pretty x = P.prettyPrint x instance Pretty HsGuardedAlt where pretty x = P.prettyPrint x instance Pretty HsPat where pretty x = case x of (HsPInfixApp p1 op p2) -> "(" ++ pretty p1 ++ P.prettyPrint op ++ pretty p2 ++ ")" e -> P.prettyPrint e instance Pretty HsPatField where pretty x = P.prettyPrint x instance Pretty HsLiteral where pretty x = P.prettyPrint x instance Pretty Module where pretty x = P.prettyPrint x instance Pretty HsQName where pretty x = P.prettyPrint x instance Pretty HsName where pretty x = P.prettyPrint x instance Pretty HsQOp where pretty o = P.prettyPrint o instance Pretty HsOp where pretty o = P.prettyPrint o instance Pretty HsSpecialCon where pretty HsUnitCon = "()" pretty HsListCon = "[]" pretty HsFunCon = "->" pretty (HsTupleCon i) = "(" ++ take i (repeat ',') ++ ")" pretty HsCons = ":" instance Pretty HsCName where pretty n = P.prettyPrint n
arnizamani/occam
Instances.hs
mit
19,725
2
22
5,363
9,389
4,645
4,744
450
1
{-# LANGUAGE OverloadedStrings,NoImplicitPrelude #-} module TypePlay.Infer.HM where import Prelude hiding (map,concat) import Data.List (map,concat,nub,union,intersect) import Data.Text (Text) import qualified Data.Text as T import Data.Monoid ((<>),mconcat) type Id = Text enumId :: Int -> Id enumId = ("v" <>) . T.pack . show data Kind = Star | Kfun Kind Kind deriving (Eq,Show) data Type = TVar Tyvar | TCon Tycon | TAp Type Type | TGen Int deriving (Eq,Show) data Tyvar = Tyvar Id Kind deriving (Eq,Show) data Tycon = Tycon Id Kind deriving (Eq,Show) type Subst = [(Tyvar, Type)] data InferenceErr = SubstMerge | Unification Type Type | DoesNotOccur Tyvar [Tyvar] | KindsDontMatch Kind Kind | TypesDontMatch Type Type | ClassMisMatch Id Id | NoSuperClassFound Id | NoInstancesOfClass Id type Infer a = Either InferenceErr a instance Show InferenceErr where show SubstMerge = "Substitution Merge Failed" show (Unification t1 t2) = "Unable to unify" <> show t1 <> " with " <> show t2 show (DoesNotOccur tv t) = show t <> " not found in " <> show tv show (KindsDontMatch k1 k2) = mconcat [ "Incorrect Kind.\n Found (" , show k1 , ").\nExpected (" , show k2 ] show (TypesDontMatch t t') = mconcat [ "Could not match types:\n" , show t , " with " , show t' ] show (ClassMisMatch i i') = mconcat [ "Type Classes differ.\n Found(" , show i , "). Expected (" , show i' , ")." ] show (NoSuperClassFound i) = mconcat [ "No type class matching: " , show i , " found." ] show (NoInstancesOfClass i) = mconcat [ "No instances of " , show i , " found in current environment." ] typeConst :: Text -> Kind -> Type typeConst i = TCon . Tycon i tUnit = typeConst "()" Star tChar = typeConst "Char" Star tInt = typeConst "Int" Star tInteger = typeConst "Integer" Star tFloat = typeConst "Float" Star tDouble = typeConst "Double" Star tList = typeConst "[]" $ Kfun Star Star tArrow = typeConst "(->)" $ Kfun Star $ Kfun Star Star tTuple2 = typeConst "(,)" $ Kfun Star $ Kfun Star Star tString :: Type tString = list tChar infixr 4 `fn` fn :: Type -> Type -> Type a `fn` b = TAp (TAp tArrow a) b list :: Type -> Type list = TAp tList pair :: Type -> Type -> Type pair a b = TAp (TAp tTuple2 a) b class HasKind t where kind :: t -> Kind instance HasKind Tyvar where kind (Tyvar v k) = k instance HasKind Tycon where kind (Tycon v k) = k instance HasKind Type where kind (TCon tc) = kind tc kind (TVar u) = kind u kind (TAp t _) = case kind t of (Kfun _ k) -> k nullSubst :: Subst nullSubst = [] (+->) :: Tyvar -> Type -> Subst u +-> t = [(u,t)] class Types t where apply :: Subst -> t -> t tv :: t -> [Tyvar] instance Types Type where apply s (TVar u) = case lookup u s of Just t -> t Nothing -> TVar u apply s (TAp l r) = TAp (apply s l) (apply s r) apply s t = t tv (TVar u) = [u] tv (TAp l r) = tv l `union` tv r tv t = [] instance Types a => Types [a] where apply s = fmap (apply s) tv = nub . concat . fmap tv infixr 4 @@ (@@) :: Subst -> Subst -> Subst s1 @@ s2 = [ (u, apply s1 t) | (u,t) <- s2] <> s1 merge :: Subst -> Subst -> Infer Subst merge s1 s2 = if agree then Right $ s1 <> s2 else Left SubstMerge where agree = all (\v -> apply s1 (TVar v) == apply s2 (TVar v)) (gFst s1 `intersect` gFst s2) gFst = fmap fst mgu :: Type -> Type -> Infer Subst mgu (TAp l r) (TAp l' r') = do s1 <- mgu l l' s2 <- mgu (apply s1 r) (apply s1 r') return $ s2 @@ s1 mgu (TVar u) t = varBind u t mgu t (TVar u) = varBind u t mgu (TCon tc1) (TCon tc2) | tc1 == tc2 = return nullSubst mgu t1 t2 = Left $ Unification t1 t2 varBind :: Tyvar -> Type -> Infer Subst varBind u t | t == TVar u = return nullSubst | u `elem` tv t = Left $ DoesNotOccur u $ tv t | kind u /= kind t = Left $ KindsDontMatch (kind u) (kind t) | otherwise = return $ u +-> t match :: Type -> Type -> Infer Subst match (TAp l r) (TAp l' r') = do sl <- match l l' sr <- match r r' merge sl sr match (TVar u) t | kind u == kind t = return $ u +-> t match (TCon tcl) (TCon tcr) | tcl == tcr = return nullSubst match t1 t2 = Left $ TypesDontMatch t1 t2 -- Type Classes data Qual t = [Pred] :=> t deriving (Show,Eq) data Pred = IsIn Id Type deriving (Show,Eq) -- Example 'Num a => a -> Int' -- [IsIn "Num" (TVar (Tyvar "a" Star))] -- :=> (TVar (Tyvar "a" Star) 'fn' tInt) instance Types t => Types (Qual t) where apply s (ps :=> t) = apply s ps :=> apply s t tv (ps :=> t) = tv ps `union` tv t instance Types Pred where apply s (IsIn i t) = IsIn i (apply s t) tv (IsIn i t) = tv t mguPred :: Pred -> Pred -> Infer Subst mguPred = lift mgu matchPred :: Pred -> Pred -> Infer Subst matchPred = lift match lift :: (Type -> Type -> Infer b) -> Pred -> Pred -> Infer b lift m (IsIn i t) (IsIn i' t') | i == i' = m t t' | otherwise = Left $ ClassMisMatch i i' type Class = ([Id], [Inst]) type Inst = Qual Pred data ClassEnv = ClassEnv { classes :: Id -> Maybe Class , defaults :: [Type] } super :: ClassEnv -> Id -> Infer [Id] super ce i = case classes ce i of Just (is, its) -> return is Nothing -> Left $ NoSuperClassFound i insts :: ClassEnv -> Id -> Infer [Inst] insts ce i = case classes ce i of Just (is, its) -> return its Nothing -> Left $ NoInstancesOfClass i modify :: ClassEnv -> Id -> Class -> ClassEnv modify ce i c = ce { classes = \j -> if i == j then Just c else classes ce j } initialEnv :: ClassEnv initialEnv = ClassEnv { classes = \i -> Nothing , defaults = [tInteger, tDouble] }
mankyKitty/TypePlay
src/TypePlay/Infer/HM.hs
mit
6,014
0
13
1,814
2,536
1,299
1,237
198
2
import Data.Tree import Data.Tree.Zipper import Data.Maybe import Test.QuickCheck import System.Random import Text.Show.Functions instance Arbitrary a => Arbitrary (Tree a) where arbitrary = sized arbTree where arbTree n = do lbl <- arbitrary children <- resize (n-1) arbitrary return (Node lbl children) coarbitrary t = coarbitrary (rootLabel t) . variant (length (subForest t)) . flip (foldr coarbitrary) (subForest t) instance Arbitrary a => Arbitrary (TreeLoc a) where arbitrary = do tree <- resize 8 arbitrary lefts <- resize 5 arbitrary rights <- resize 5 arbitrary parents <- resize 3 arbitrary return (Loc tree lefts rights parents) prop_LeftRight :: TreeLoc Int -> Property prop_LeftRight loc = label "prop_LeftRight" $ case left loc of Just lloc -> right lloc == Just loc Nothing -> True prop_LeftFirst :: TreeLoc Int -> Property prop_LeftFirst loc = label "prop_LeftFirst" $ isFirst loc ==> left loc == Nothing prop_RightLast :: TreeLoc Int -> Property prop_RightLast loc = label "prop_RightLast" $ isLast loc ==> right loc == Nothing prop_RootParent :: TreeLoc Int -> Property prop_RootParent loc = label "prop_RootParent" $ isRoot loc ==> parent loc == Nothing prop_FirstChild :: TreeLoc Int -> Property prop_FirstChild loc = label "prop_FirstChild" $ case firstChild loc of Just floc -> parent floc == Just loc && left floc == Nothing Nothing -> isLeaf loc prop_LastChild :: TreeLoc Int -> Property prop_LastChild loc = label "prop_LastChild" $ case lastChild loc of Just lloc -> parent lloc == Just loc && right lloc == Nothing Nothing -> isLeaf loc prop_FindChild :: TreeLoc Int -> Property prop_FindChild loc = label "prop_FindChild" $ forAll arbitrary (\f -> maybe True (\sloc -> f (tree sloc) && parent sloc == Just loc) (findChild f loc)) prop_SetGetLabel :: TreeLoc Int -> Property prop_SetGetLabel loc = label "prop_SetGetLabel" $ forAll arbitrary (\x -> getLabel (setLabel x loc) == x) prop_ModifyLabel :: TreeLoc Int -> Property prop_ModifyLabel loc = label "prop_ModifyLabel" $ forAll arbitrary (\f -> getLabel (modifyLabel f loc) == f (getLabel loc)) prop_UpDown :: TreeLoc Int -> Property prop_UpDown loc = label "prop_UpDown" $ case parent loc of Just ploc -> getChild (getNodeIndex loc) ploc == Just loc Nothing -> True prop_RootChild :: TreeLoc Int -> Property prop_RootChild loc = label "prop_RootChild" $ isChild loc == not (isRoot loc) prop_ChildrenLeaf :: TreeLoc Int -> Property prop_ChildrenLeaf loc = label "prop_ChildrenLeaf" $ hasChildren loc == not (isLeaf loc) prop_FromToTree :: TreeLoc Int -> Property prop_FromToTree loc = label "prop_FromToTree" $ tree (fromTree (toTree loc)) == tree (root loc) prop_FromToForest :: TreeLoc Int -> Property prop_FromToForest loc = label "prop_FromToForest" $ isFirst (root loc) ==> fromForest (toForest loc) == Just (root loc) prop_FromTree :: Tree Int -> Property prop_FromTree tree = label "prop_FromTree" $ left (fromTree tree) == Nothing && right (fromTree tree) == Nothing && parent (fromTree tree) == Nothing prop_FromForest :: Property prop_FromForest = label "prop_FromForest" $ fromForest ([] :: Forest Int) == Nothing prop_InsertLeft :: TreeLoc Int -> Property prop_InsertLeft loc = label "prop_InsertLeft" $ forAll (resize 10 arbitrary) $ \t -> tree (insertLeft t loc) == t && rights (insertLeft t loc) == tree loc : rights loc prop_InsertRight :: TreeLoc Int -> Property prop_InsertRight loc = label "prop_InsertRight" $ forAll (resize 10 arbitrary) $ \t -> tree (insertRight t loc) == t && lefts (insertRight t loc) == tree loc : lefts loc prop_InsertDownFirst :: TreeLoc Int -> Property prop_InsertDownFirst loc = label "prop_InsertDownFirst" $ forAll (resize 10 arbitrary) $ \t -> tree (insertDownFirst t loc) == t && left (insertDownFirst t loc) == Nothing && fmap getLabel (parent (insertDownFirst t loc)) == Just (getLabel loc) && fmap tree (right (insertDownFirst t loc)) == fmap tree (firstChild loc) prop_InsertDownLast :: TreeLoc Int -> Property prop_InsertDownLast loc = label "prop_InsertDownLast" $ forAll (resize 10 arbitrary) $ \t -> tree (insertDownLast t loc) == t && right (insertDownLast t loc) == Nothing && fmap getLabel (parent (insertDownLast t loc)) == Just (getLabel loc) && fmap tree (left (insertDownLast t loc)) == fmap tree (lastChild loc) prop_InsertDownAt :: TreeLoc Int -> Property prop_InsertDownAt loc = label "prop_InsertDownAt" $ forAll (resize 10 arbitrary) $ \t -> forAll (resize 10 arbitrary) $ \n -> maybe t tree (insertDownAt n t loc) == t && fmap lefts (getChild n loc) == fmap lefts (insertDownAt n t loc) && fmap tree (getChild n loc) == fmap tree (insertDownAt n t loc >>= right) && fmap rights (getChild n loc) == fmap rights (insertDownAt n t loc >>= right) && maybe (getLabel loc) getLabel (insertDownAt n t loc >>= parent) == getLabel loc prop_Delete :: TreeLoc Int -> Property prop_Delete loc = label "prop_Delete" $ if not (isLast loc) then fmap (\loc -> tree loc : rights loc) (delete loc) == Just (rights loc) && fmap lefts (delete loc) == Just (lefts loc) else if not (isFirst loc) then fmap rights (delete loc) == Just (rights loc) && fmap (\loc -> tree loc : lefts loc) (delete loc) == Just (lefts loc) else fmap (insertDownFirst (tree loc)) (delete loc) == Just loc main = do testProp prop_LeftRight testProp prop_LeftFirst testProp prop_RightLast testProp prop_RootParent testProp prop_FirstChild testProp prop_LastChild testProp prop_FindChild testProp prop_SetGetLabel testProp prop_ModifyLabel testProp prop_UpDown testProp prop_RootChild testProp prop_ChildrenLeaf testProp prop_FromToTree testProp prop_FromToForest testProp prop_FromTree testProp prop_FromForest testProp prop_InsertLeft testProp prop_InsertRight testProp prop_InsertDownFirst testProp prop_InsertDownLast testProp prop_InsertDownAt testProp prop_Delete testProp :: Testable a => a -> IO () testProp = check (defaultConfig{-configEvery = \n args -> ""-})
yav/haskell-zipper
test.hs
mit
6,455
0
20
1,471
2,308
1,079
1,229
147
3
-- Examples from chapter 5 -- http://learnyouahaskell.com/recursion maximum' :: (Ord a) => [a] -> a maximum' [] = error "maximum of empty list" maximum' [x] = x maximum' (x:xs) = max x (maximum' xs) replicate' :: (Num i, Ord i) => i -> a -> [a] replicate' n x | n <= 0 = [] | otherwise = x:replicate' (n-1) x take' :: (Num i, Ord i) => i -> [a] -> [a] take' _ [] = [] take' n (x:xs) | n <= 0 = [] | otherwise = x : take' (n-1) xs reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x] repeat' :: a -> [a] repeat' x = x : repeat' x zip' :: [a] -> [b] -> [(a,b)] zip' [] _ = [] zip' _ [] = [] zip' (x:xs) (y:ys) = (x,y) : zip' xs ys quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = let smallerSorted = quicksort [a | a <- xs, a <= x] biggerSorted = quicksort [a | a <- xs, a > x] in smallerSorted ++ [x] ++ biggerSorted
Sgoettschkes/learning
haskell/LearnYouAHaskell/05.hs
mit
902
0
12
232
550
288
262
28
1
module Main (main) where import System.Console.GetOpt import System.IO import System.Environment import System.Exit import qualified System.IO as SIO import Data.ByteString import Data.Word import Data.ListLike.CharString import qualified Data.Iteratee as I import qualified Data.Iteratee.ListLike as IL import qualified Data.Iteratee.IO.Handle as IOH import Data.Iteratee.Base.ReadableChunk import Data.Iteratee ((><>),(<><)) import Data.Iteratee.Char import qualified Data.Iteratee.Char as IC main :: IO () main = do let enum = I.enumPure1Chunk [1..1000::Int] it = (I.joinI $ (I.take 15 ><> I.take 10) I.stream2list) rs <- enum it >>= I.run print rs -- handle <- openFile "iterdata/source.txt" ReadMode let enum2 = IL.take 20 it2 = I.joinI $ enum2 (I.stream2list::I.Iteratee ByteString IO [Word8]) i <- IOH.enumHandle 22 handle it2 >>= I.run str <- SIO.hGetLine handle SIO.putStr $ str ++ "\n" SIO.hClose handle -- Enumerating a handle over a finished iteratee doesn't read -- from the handle, and doesn't throw an exception handle <- openFile "iterdata/source.txt" ReadMode let finishediter = I.idone () (I.EOF Nothing::I.Stream [Word8]) i <- IOH.enumHandle 22 handle finishediter >>= I.run str <- SIO.hGetLine handle SIO.putStr $ str ++ "\n" SIO.hClose handle -- I wonder... can you compose an already "started" iteratee -- with another iteratee? handle <- openFile "iterdata/smallfile.txt" ReadMode let enum3 = IL.take 4 it3 = I.joinI $ enum3 (I.stream2list::I.Iteratee [Char] IO [Char]) enum4 = IL.take 4 it4 = I.joinI $ enum4 (I.stream2list::I.Iteratee [Char] IO [Char]) ii <- IOH.enumHandle 22 handle it3 SIO.hClose handle let combined = ii >> it4 handle <- openFile "iterdata/smallfile2.txt" ReadMode iii <- IOH.enumHandle 22 handle combined >>= I.run SIO.hClose handle print iii
danidiaz/haskell-sandbox
iteratee.hs
mit
2,218
0
16
676
634
327
307
52
1
-- Primes in numbers -- http://www.codewars.com/kata/54d512e62a5e54c96200019e/ module Codewars.Kata.PrFactors where import Data.List (unfoldr, findIndex, group) import Data.Maybe (fromJust) prime_factors :: Integer -> String prime_factors k | isPrime k = "("++ show k ++")" | otherwise = concatMap g . group . unfoldr f $ (k, 0) where primes = sieve [2..] sieve (n:ns) = n : sieve [n' | n' <- ns, n' `mod` n /= 0] isPrime x = all (\d -> x `mod` d /= 0) [2 .. floor . sqrt . fromIntegral $ x] f (1, _) = Nothing f (n, i) | isPrime n = Just (n, (1, 0)) | otherwise = if m == 0 then Just (primes !! i , (d, i)) else Just (primes !! newI, (n `div` (primes !! newI), newI) ) where (d, m) = n `divMod` (primes !! i) newI :: Int newI = succ . (+i) . fromJust . findIndex (\x-> n `mod` x == 0) . drop (i+1) $ primes g :: [Integer] -> String g ps = "(" ++ (show . head $ ps) ++ (if length ps > 1 then "**" ++ (show . length $ ps) else "") ++ ")"
gafiatulin/codewars
src/5 kyu/PrFactors.hs
mit
1,095
0
16
352
506
277
229
17
4
module Main where import Synonyms import Test.Hspec main :: IO () main = hspec $ do let d = Definition "foo" ["b"] in describe "lookupDefinition" $ do it "returns Nothing when no matches" $ lookupDefinition "a" [d] `shouldBe` Nothing it "returns Just Definition when found" $ lookupDefinition "foo" [d] `shouldBe` Just d describe "definitions" $ it "converts a list of definitions" $ definitions ["foo bar baz"] `shouldBe` [Definition "foo" ["bar", "baz"]] describe "convertToDefinition" $ it "converts to a definition" $ convertToDefinition "foo bar baz" `shouldBe` Definition "foo" ["bar", "baz"]
justincampbell/synonyms
Spec.hs
mit
720
0
16
210
191
96
95
17
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Simulation.Node.Service.Http ( HttpService , Service , Routes (..) , activate , as , toSnapRoutes , selfStore , basePrefix , module Snap.Core ) where import Control.Applicative (Applicative, Alternative, (<$>)) import Control.Monad (MonadPlus) import Control.Monad.Reader (ReaderT, MonadIO, runReaderT) import Control.Monad.Reader.Class (MonadReader, ask) import Control.Monad.CatchIO (MonadCatchIO) import qualified Data.ByteString.Char8 as BS import Snap.Core import Snap.Http.Server import System.FilePath ((</>)) -- | The HttpService monad. newtype HttpService a = HttpService { extractHttpService :: ReaderT HttpServiceApiParam Snap a } deriving ( Functor, Applicative, Alternative, Monad , MonadPlus, MonadReader HttpServiceApiParam , MonadIO, MonadCatchIO, MonadSnap ) -- | Record with api parameters for the execution of the HttpService monad. data HttpServiceApiParam = HttpServiceApiParam { selfStore_ :: !FilePath , basePrefix_ :: !String} deriving Show -- | A type describing a service's route mapping between an url and -- a handler for the request. newtype Routes a = Routes [ (BS.ByteString, HttpService a) ] -- | A type describing a prepared service, ready to install. newtype Service a = Service [ (BS.ByteString, HttpService a, String) ] -- | Activate the http services, at the given port, in the current -- thread. activate :: Int -> [Service ()] -> IO () activate port services = do let config = setPort port defaultConfig routes = toSnapRoutes services httpServe config $ route routes -- | Convert a set of routes and a prefix to a proper service. as :: Routes a -> BS.ByteString -> Service a as (Routes xs) prefix = let prefix' = prefix `BS.snoc` '/' in Service $ map (\(url, action) -> (prefix' `BS.append` url, action, BS.unpack prefix')) xs -- | Convert a list of installments to a list of proper snap -- routes. The HttpService monad will be evaluated down to the snap -- monad in this step. toSnapRoutes :: [Service a] -> [(BS.ByteString, Snap a)] toSnapRoutes = concatMap (\(Service xs') -> map toSnap xs') -- | Fetch own's self store position in the file system (relative to -- current working directory). E.g. if the service's name is foo the -- selfStore will return httpServices/foo/ as the directory where -- static data for the service can be stored. selfStore :: HttpService FilePath selfStore = selfStore_ <$> ask -- | Fetch own's base prefix url. This is to be used for any kind of -- linking to resources inside the own service to that the service -- name always become the prefix in the url. basePrefix :: HttpService String basePrefix = basePrefix_ <$> ask -- | Run an HttpService in the Snap monad. runHttpService :: HttpService a -> HttpServiceApiParam -> Snap a runHttpService action = runReaderT (extractHttpService action) toSnap :: (BS.ByteString, HttpService a, String) -> (BS.ByteString, Snap a) toSnap (url, action, prefix) = (url, runHttpService action makeParam) where makeParam :: HttpServiceApiParam makeParam = HttpServiceApiParam ("httpServices" </> prefix) ('/':prefix)
kosmoskatten/programmable-endpoint
src/Simulation/Node/Service/Http.hs
mit
3,288
0
13
673
695
401
294
59
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} module Alder.Html.Internal ( -- * Elements Node(..) -- * Attributes , Id , Handlers , Attributes(..) , defaultAttributes -- * Html , Html , HtmlM(..) , runHtml , parent , leaf , text -- * Event handlers , EventType(..) , Event(..) , Handler(..) -- * Setting attributes , Attribute , Attributable , (!) , (!?) , (!#) , (!.) , (!?.) , key -- * Creating attributes , attribute , boolean , onEvent ) where import Control.Applicative import Data.DList as DList import Data.Hashable import Data.HashMap.Strict as HashMap hiding ((!)) import Data.Monoid import Data.Text as Text import Data.Tree import Unsafe.Coerce import Alder.JavaScript infixl 1 !, !?, !#, !., !?. data Node = Element !Text Attributes | Text !Text type Id = Text type Handlers = HashMap EventType (JSObj -> IO ()) data Attributes = Attributes { elementId :: !(Maybe Id) , elementKey :: !(Maybe Int) , elementClass :: ![Text] , otherAttributes :: !(HashMap Text Text) , handlers :: !Handlers } defaultAttributes :: Attributes defaultAttributes = Attributes { elementId = Nothing , elementKey = Nothing , elementClass = [] , otherAttributes = HashMap.empty , handlers = HashMap.empty } type Html = HtmlM () newtype HtmlM a = HtmlM (Attributes -> DList (Tree Node)) deriving (Monoid) instance Functor HtmlM where fmap _ = unsafeCoerce instance Applicative HtmlM where pure _ = mempty (<*>) = appendHtml instance Monad HtmlM where return _ = mempty (>>) = appendHtml m >>= k = m `appendHtml` k (error "Alder.HtmlM: monadic bind") appendHtml :: HtmlM a -> HtmlM b -> HtmlM c appendHtml a b = unsafeCoerce a <> unsafeCoerce b runHtml :: Html -> Forest Node runHtml (HtmlM f) = DList.toList (f defaultAttributes) parent :: Text -> Html -> Html parent t h = HtmlM $ \a -> DList.singleton (Node (Element t a) (runHtml h)) leaf :: Text -> Html leaf t = HtmlM $ \a -> DList.singleton (Node (Element t a) []) text :: Text -> Html text t = HtmlM $ \_ -> DList.singleton (Node (Text t) []) addAttribute :: Attribute -> HtmlM a -> HtmlM a addAttribute (Attribute f) (HtmlM g) = HtmlM (g . f) data EventType = KeyDown | KeyPress | KeyUp | Focus | Blur | Input | Change | Submit | MouseDown | MouseUp | Click | DoubleClick | MouseMove | MouseEnter | MouseLeave deriving (Eq, Ord, Read, Show, Enum, Bounded) instance Hashable EventType where hashWithSalt s = hashWithSalt s . fromEnum class Event e where extractEvent :: JSObj -> IO e class Handler f where fire :: f e -> e -> IO () newtype Attribute = Attribute (Attributes -> Attributes) instance Monoid Attribute where mempty = Attribute id mappend (Attribute f) (Attribute g) = Attribute (f . g) class Attributable h where (!) :: h -> Attribute -> h instance Attributable (HtmlM a) where (!) = flip addAttribute instance Attributable h => Attributable (r -> h) where f ! a = (! a) . f (!?) :: Attributable h => h -> (Bool, Attribute) -> h h !? (p, a) = if p then h ! a else h (!#) :: Attributable h => h -> Text -> h h !# v = h ! Attribute addId where addId a = a { elementId = Just v } (!.) :: Attributable h => h -> Text -> h h !. v = h ! Attribute addClass where addClass a = a { elementClass = v : elementClass a } (!?.) :: Attributable h => h -> (Bool, Text) -> h h !?. (p, v) = if p then h !. v else h key :: Int -> Attribute key i = Attribute $ \a -> a { elementKey = Just i } attribute :: Text -> Text -> Attribute attribute k v = Attribute $ \a -> a { otherAttributes = HashMap.insert k v (otherAttributes a) } boolean :: Text -> Attribute boolean k = attribute k "" onEvent :: (Handler f, Event e) => EventType -> f e -> Attribute onEvent k handler = Attribute $ \a -> a { handlers = HashMap.insert k h (handlers a) } where h v = do e <- extractEvent v fire handler e
ghcjs/ghcjs-sodium
src/Alder/Html/Internal.hs
mit
4,281
0
11
1,225
1,538
846
692
141
2
module Main where data MyBool = MyTrue | MyFalse foo a MyFalse b = 0 foo c MyTrue d = 1 bar a = 2 main_ = foo 1 MyFalse 2
Ekleog/hasklate
examples/BasicPatternMatching.hs
mit
126
0
5
35
58
31
27
6
1
{-# LANGUAGE CPP, TypeFamilies, DeriveDataTypeable #-} module PGIP.GraphQL.Result.LocIdReference where import Data.Data newtype LocIdReference = LocIdReference { locId :: String } deriving (Show, Typeable, Data)
spechub/Hets
PGIP/GraphQL/Result/LocIdReference.hs
gpl-2.0
255
0
6
67
42
27
15
5
0
{-# LANGUAGE Arrows #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Main (main) where import Control.Lens import Control.Monad.State import Control.Wire import Data.Fixed import Linear import FreeGame import FRP.Netwire import System.Random import Prelude hiding ((.), id) data Item = Treasure | Fuel | Upgrade UpgradeType deriving Eq data UpgradeType = Ballast | Rotor | Tank deriving Eq newtype Space = Space {getItem :: Maybe (V2 Double, Item)} makeWrapped ''Space data Stream a = a :- Stream a deriving Functor data LZipper a = LZipper {_leftZ :: Stream a, _hereZ :: a, _rightZ :: Stream a} deriving Functor makeLenses ''LZipper zleft :: LZipper a -> LZipper a zleft LZipper{_leftZ = ls, _hereZ = l, _rightZ = (r :- rs)} = LZipper{_leftZ = l :- ls, _hereZ = r, _rightZ = rs} zright :: LZipper a -> LZipper a zright LZipper{_leftZ = (l :- ls), _hereZ = r, _rightZ = rs} = LZipper{_leftZ = ls, _hereZ = l, _rightZ = r :- rs} type MapM = State (Int, StdGen) newtype Map = Map {getMap :: LZipper (LZipper (Either (MapM Space) Space))} makeWrapped ''Map initialMap :: Map initialMap = Map $ allZ (allZ initialTile) where allS x = x :- allS x allZ x = LZipper {_leftZ = allS x, _hereZ = x, _rightZ = allS x} initialTile :: Either (MapM Space) Space initialTile = Left $ do _1 +~ 1 x <- _2 %%= randomR (0, 2::Int) (Space . Just . (,) (V2 120 90)) <$> case x of 0 -> return Treasure 1 -> return Fuel 2 -> Upgrade <$> do y <- _2 %%= randomR (0, 2::Int) case y of 0 -> return Ballast 1 -> return Rotor 2 -> return Tank normalize :: Map -> MapM Map normalize m0 = do m1 <- normalize1 (mapUp m0) m2 <- normalize1 (mapLeft m1) m3 <- normalize1 (mapDown m2) m4 <- normalize1 (mapDown m3) m5 <- normalize1 (mapRight m4) m6 <- normalize1 (mapRight m5) m7 <- normalize1 (mapUp m6) m8 <- normalize1 (mapUp m7) normalize1 (mapLeft . mapDown $ m8) where normalize1 m = do case m^._Wrapped.hereZ.hereZ of Left a -> do r <- a return $ m & _Wrapped.hereZ.hereZ .~ Right r Right{} -> return m mapRight :: Map -> Map mapRight Map{getMap = m} = Map{getMap = fmap zright m} mapLeft :: Map -> Map mapLeft Map{getMap = m} = Map{getMap = fmap zleft m} mapUp :: Map -> Map mapUp Map{getMap = m} = Map{getMap = zleft m} mapDown :: Map -> Map mapDown Map{getMap = m} = Map{getMap = zright m} computeVVel :: Int -> Double -> Int -> Double computeVVel dir fuel upgradeLevel | nearZero fuel = 0 | otherwise = fromIntegral (signum dir) * speed where speed = log . (+exp 1) . fromIntegral $ upgradeLevel computeVPos :: SimpleWire Double Double computeVPos = integral 0 normalizeVPos :: Double -> (Double, Ordering) normalizeVPos c = let adjusted = c `mod'` 180 in (adjusted, adjusted `compare` c) computeHAcc :: Int -> Double -> Double -> Int -> Double computeHAcc dir fuel vel upgradeLevel | dir == 0 || nearZero fuel = -0.25 * vel | otherwise = fromIntegral (signum dir) * accel where accel = log . (+exp 1) . fromIntegral $ upgradeLevel computeHVel :: SimpleWire Double Double computeHVel = integralWith correct 0 . arr (flip (,) ()) where correct _ n | n >= 50 = 50 | otherwise = n computeHPos :: SimpleWire Double Double computeHPos = integral 0 normalizeHPos :: Double -> (Double, Ordering) normalizeHPos c = let adjusted = c `mod'` 240 in (adjusted, adjusted `compare` c) itemCollision :: SimpleWire (Map, V2 (Double, Ordering)) (Event Item, Map) itemCollision = proc (m0, V2 (xpos, xoff) (ypos, yoff)) -> let m = case (yoff, xoff) of (EQ, EQ) -> m0 (EQ, GT) -> mapUp m0 (GT, GT) -> mapUp $ mapRight m0 (GT, EQ) -> mapRight m0 (GT, LT) -> mapDown $ mapRight m0 (EQ, LT) -> mapDown m0 (LT, LT) -> mapDown $ mapLeft m0 (LT, EQ) -> mapLeft m0 (LT, GT) -> mapUp $ mapLeft m0 t = preview (_Wrapped.hereZ.hereZ._Right._Wrapped._Just) m in case t of Just (p,i) | distance p (V2 xpos ypos) <= 5 -> let n = m & _Wrapped.hereZ.hereZ._Right._Wrapped .~ Nothing in do ei <- now -< i ns <- id -< n returnA -< (ei, ns) _ -> do ei <- never -< () ms <- id -< m returnA -< (ei, ms) countItem :: Item -> SimpleWire (Event Item) Int countItem item = krSwitch (pure 0) . second adjustWire . (pure () &&& filterE (== item)) where adjustWire = arr ((arr (+1) .) <$) computeScore :: SimpleWire (Event Item) Int computeScore = countItem Treasure * 100 computeBallastUpgrade :: SimpleWire (Event Item) Int computeBallastUpgrade = countItem $ Upgrade Ballast computeRotorUpgrade :: SimpleWire (Event Item) Int computeRotorUpgrade = countItem $ Upgrade Rotor computeTankUpgrade :: SimpleWire (Event Item) Int computeTankUpgrade = countItem $ Upgrade Tank rateOfFuelDecrease :: Bool -> Bool -> Double rateOfFuelDecrease True True = 1 rateOfFuelDecrease False False = 0.2 rateOfFuelDecrease _ _ = 0.6 fuelRegenEvent :: SimpleWire (Int, Event Item) (Event Double) fuelRegenEvent = undefined maxFuel :: Int -> Double maxFuel = (*100) . log . (+exp 1) . fromIntegral computeFuel :: SimpleWire (Double, Event Double) Double computeFuel = krSwitch (stopAtZero .integral 100 . arr negate) . second adjustWire where adjustWire = arr $ fmap (\i _ -> integral i . arr negate) stopAtZero = arr $ \r -> if r < 0 then 0 else r mainWire :: SimpleWire (Int, Int, Map) (Int, Map, Bool) mainWire = proc (x,y,m0) -> do rec { vinf <- arr normalizeVPos . computeVPos -< computeVVel y fuel ballastUpgrade; hvel <- computeHVel -< computeHAcc y fuel hvel rotorUpgrade; hinf <- arr normalizeHPos . computeHPos -< hvel; (ei, m1) <- itemCollision -< (m0, V2 hinf vinf); ballastUpgrade <- computeBallastUpgrade -< ei; rotorUpgrade <- computeRotorUpgrade -< ei; tankUpgrade <- computeTankUpgrade -< ei; ef <- fuelRegenEvent -< (tankUpgrade, ei); fuel <- computeFuel -< (maxFuel tankUpgrade, ef); } score <- computeScore -< ei returnA -< (score, m1, nearZero fuel) main :: IO () main = do Just _ <- runGame Windowed (BoundingBox 0 0 480 360) $ do setTitle "Submarine game!" setFPS 60 clearColor blue sessiin <- liftIO clockSession_ return () where gameLoop m0 g0 c0 w0 = do let (m, (g, c)) = runState (normalize m) (g, c) ks <- keyStates_ u <- ks ^?! ix KeyUp d <- ks ^?! ix KeyDown l <- ks ^?! ix KeyLeft r <- ks ^?! ix KeyRight let v = case (u, d) of (Down, Up) -> (-1) (Up, Down) -> 1 (_, _) -> 0 h = case (l, r) of (Down, Up) -> (-1) (Up, Down) -> 1 (_, _) -> 0 let Identity (Left (s, m1, e), w1) = stepWire w0
Taneb/LD29
src/Main.hs
gpl-2.0
7,122
3
21
1,874
2,890
1,500
1,390
-1
-1
{-| Scan clusters via RAPI or LUXI and write state data files. -} {- Copyright (C) 2009, 2010, 2011 Google Inc. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Main (main) where import Control.Monad import Data.Maybe (isJust, fromJust, fromMaybe) import System (exitWith, ExitCode(..)) import System.IO import System.FilePath import qualified System import Text.Printf (printf) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Cluster as Cluster import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Rapi as Rapi import qualified Ganeti.HTools.Luxi as Luxi import Ganeti.HTools.Loader (checkData, mergeData, ClusterData(..)) import Ganeti.HTools.Text (serializeCluster) import Ganeti.HTools.CLI import Ganeti.HTools.Types -- | Options list and functions options :: [OptType] options = [ oPrintNodes , oOutputDir , oLuxiSocket , oVerbose , oNoHeaders , oShowVer , oShowHelp ] -- | Return a one-line summary of cluster state printCluster :: Node.List -> Instance.List -> String printCluster nl il = let (bad_nodes, bad_instances) = Cluster.computeBadItems nl il ccv = Cluster.compCV nl nodes = Container.elems nl insts = Container.elems il t_ram = sum . map Node.tMem $ nodes t_dsk = sum . map Node.tDsk $ nodes f_ram = sum . map Node.fMem $ nodes f_dsk = sum . map Node.fDsk $ nodes in printf "%5d %5d %5d %5d %6.0f %6d %6.0f %6d %.8f" (length nodes) (length insts) (length bad_nodes) (length bad_instances) t_ram f_ram (t_dsk / 1024) (f_dsk `div` 1024) ccv -- | Replace slashes with underscore for saving to filesystem fixSlash :: String -> String fixSlash = map (\x -> if x == '/' then '_' else x) -- | Generates serialized data from loader input. processData :: ClusterData -> Result ClusterData processData input_data = do cdata@(ClusterData _ nl il _) <- mergeData [] [] [] [] input_data let (_, fix_nl) = checkData nl il return cdata { cdNodes = fix_nl } -- | Writes cluster data out writeData :: Int -> String -> Options -> Result ClusterData -> IO Bool writeData _ name _ (Bad err) = printf "\nError for %s: failed to load data. Details:\n%s\n" name err >> return False writeData nlen name opts (Ok cdata) = do let fixdata = processData cdata case fixdata of Bad err -> printf "\nError for %s: failed to process data. Details:\n%s\n" name err >> return False Ok processed -> writeDataInner nlen name opts cdata processed writeDataInner :: Int -> String -> Options -> ClusterData -> ClusterData -> IO Bool writeDataInner nlen name opts cdata fixdata = do let (ClusterData _ nl il _) = fixdata printf "%-*s " nlen name :: IO () hFlush stdout let shownodes = optShowNodes opts odir = optOutPath opts oname = odir </> fixSlash name putStrLn $ printCluster nl il hFlush stdout when (isJust shownodes) $ putStr $ Cluster.printNodes nl (fromJust shownodes) writeFile (oname <.> "data") (serializeCluster cdata) return True -- | Main function. main :: IO () main = do cmd_args <- System.getArgs (opts, clusters) <- parseOpts cmd_args "hscan" options let local = "LOCAL" let nlen = if null clusters then length local else maximum . map length $ clusters unless (optNoHeaders opts) $ printf "%-*s %5s %5s %5s %5s %6s %6s %6s %6s %10s\n" nlen "Name" "Nodes" "Inst" "BNode" "BInst" "t_mem" "f_mem" "t_disk" "f_disk" "Score" when (null clusters) $ do let lsock = fromMaybe defaultLuxiSocket (optLuxi opts) let name = local input_data <- Luxi.loadData lsock result <- writeData nlen name opts input_data unless result $ exitWith $ ExitFailure 2 results <- mapM (\name -> Rapi.loadData name >>= writeData nlen name opts) clusters unless (all id results) $ exitWith (ExitFailure 2)
ekohl/ganeti
htools/hscan.hs
gpl-2.0
4,879
0
15
1,240
1,181
608
573
105
2
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, FlexibleContexts, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, TypeSynonymInstances, ScopedTypeVariables #-} module Turing.Type ( module Turing.Type , module Autolib.Set , module Autolib.FiniteMap ) where -- $Id$ import Autolib.Set import Autolib.Size import Autolib.FiniteMap import Autolib.ToDoc import Autolib.Reader import Data.Typeable import Autolib.Xml data Bewegung = L | O | R deriving (Eq, Ord, Typeable) $(derives [makeReader, makeToDoc] [''Bewegung]) data TM = TM -- for challenger instances deriving (Eq, Ord, Typeable) $(derives [makeReader, makeToDoc] [''TM]) -- ohne methoden, soll nur die constraints aufsammeln class ( Ord y , Show y, Show [y] , ToDoc y, ToDoc [y] , Reader y, Reader [y] , Typeable y ) => UM y instance ( Ord y, Show y , ToDoc y, ToDoc [y] , Reader y, Reader [y] , Typeable y ) => UM y class ( UM y, UM z ) => TuringC y z instance ( UM y, UM z ) => TuringC y z data TuringC y z => Turing y z = Turing { eingabealphabet :: Set y , arbeitsalphabet :: Set y , leerzeichen :: y , zustandsmenge :: Set z , tafel :: FiniteMap (y, z) (Set (y, z, Bewegung)) , startzustand :: z , endzustandsmenge :: Set z } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''Turing]) instance TuringC y z => Size (Turing y z) where size = length . unCollect' . tafel instance Container (x, y, z) (x, (y, z)) where label _ = "Triple" pack (x,y,z) = (x,(y,z)) unpack (x,(y,z)) = (x,y,z) -- | specialized instances used for finite automata (testing) instance ( TuringC y z ) => ToDoc (FiniteMap (y,z ) (Set (y,z,Bewegung))) where toDocPrec p fm = docParen (p >= fcp) $ text "collect" <+> toDocPrec fcp (unCollect' fm) instance ( TuringC y z ) => Reader (FiniteMap (y,z ) (Set (y,z,Bewegung))) where atomic_readerPrec p = default_readerPrec p <|> do guard $ p < 9 my_reserved "collect" xys <- reader :: Parser [ (y, z, y, z, Bewegung) ] return $ collect' xys -- | collect transition function from list of quintuples collect' :: ( TuringC y z ) => [ (y, z, y, z, Bewegung) ] -> FiniteMap (y,z ) (Set (y,z,Bewegung)) collect' pxqs = addListToFM_C union emptyFM $ do ( y, z, y', z', b ) <- pxqs return ( (y, z), unitSet (y', z', b) ) -- | represent transition function as list of quintuples unCollect' :: TuringC y z => FiniteMap (y,z ) (Set (y,z,Bewegung)) -> [ (y, z, y, z, Bewegung) ] unCollect' fm = do ((y,z), yzbs ) <- fmToList fm ( y', z', b ) <- setToList yzbs return ( y, z, y', z', b ) -- local variables: -- mode: haskell -- end:
Erdwolf/autotool-bonn
src/Turing/Type.hs
gpl-2.0
2,844
39
10
769
1,063
606
457
-1
-1
module Main where import System.Environment(getArgs) nonRepeatedChar :: [Char] -> Char nonRepeatedChar = nonRepeatedChar' [] where nonRepeatedChar' xs (c:cs) = if c `notElem` cs && c `notElem` xs then c else nonRepeatedChar' (c:xs) cs processLine :: String -> String processLine line = [ nonRepeatedChar line ] main :: IO () main = do [inputFile] <- getArgs input <- readFile inputFile mapM_ putStrLn $ map processLine $ lines input
cryptica/CodeEval
Challenges/12_FirstNonRepeatingCharacter/main.hs
gpl-3.0
478
0
10
112
169
89
80
14
2
module WebParsing.PostParser (addPostToDatabase) where import qualified Data.Text as T import Data.Either (fromRight) import Data.Maybe (maybe) import Data.List (find) import Data.Text (strip) import Control.Monad.Trans (liftIO) import Text.HTML.TagSoup import Text.HTML.TagSoup.Match import Data.List.Split (split, splitWhen, whenElt, keepDelimsL) import Database.Tables import Database.DataType (PostType(..)) import Database.Persist.Sqlite (insert_, SqlPersistM) import Database.Persist (insertUnique) import qualified Text.Parsec as P import Text.Parsec.Text (Parser) import WebParsing.ReqParser (parseReqs) import WebParsing.ParsecCombinators (parseUntil, text) addPostToDatabase :: [Tag T.Text] -> SqlPersistM () addPostToDatabase programElements = do let fullPostName = maybe "" (strip . fromTagText) $ find isTagText programElements requirementLines = reqHtmlToLines $ last $ sections isRequirementSection programElements requirements = concatMap parseRequirement requirementLines liftIO $ print fullPostName case P.parse postInfoParser "POSt information" fullPostName of Left _ -> return () Right post -> do postExists <- insertUnique post case postExists of Just key -> mapM_ (insert_ . PostCategory key) requirements Nothing -> return () where isRequirementSection = tagOpenAttrLit "div" ("class", "field-content") -- | Parse a Post value from its title. -- Titles are usually of the form "Actuarial Science Major (Science Program)". postInfoParser :: Parser Post postInfoParser = do deptName <- parseDepartmentName postType <- parsePostType P.<|> return Other return $ Post postType deptName "" "" where parseDepartmentName :: Parser T.Text parseDepartmentName = parseUntil $ P.choice [ P.lookAhead parsePostType >> return (), P.char '(' >> return () ] parsePostType :: Parser PostType parsePostType = do postTypeName <- P.choice $ map (P.try . text) ["Specialist", "Major", "Minor"] return $ read $ T.unpack postTypeName -- | Split requirements HTML into individual lines. reqHtmlToLines :: [Tag T.Text] -> [[T.Text]] reqHtmlToLines tags = let sects = split (keepDelimsL $ whenElt isSectionSplit) tags sectionsNoNotes = filter (not . isNoteSection) sects paragraphs = concatMap (splitWhen (isTagOpenName "p")) sectionsNoNotes lines' = map (map (T.strip . convertLine) . splitLines) paragraphs in lines' where isSectionSplit :: Tag T.Text -> Bool isSectionSplit tag = isTagText tag && any (flip T.isInfixOf $ fromTagText tag) ["First", "Second", "Third", "Higher", "Notes", "NOTES"] isNoteSection :: [Tag T.Text] -> Bool isNoteSection (sectionTitleTag:_) = isTagText sectionTitleTag && (any (flip T.isInfixOf $ fromTagText $ sectionTitleTag) ["Notes", "NOTES"]) isNoteSection [] = False splitLines :: [Tag T.Text] -> [[Tag T.Text]] splitLines = splitWhen (\tag -> isTagOpenName "br" tag || isTagOpenName "li" tag) convertLine :: [Tag T.Text] -> T.Text convertLine [] = "" convertLine (t:ts) | isTagOpenName "li" t = T.append "0." (innerText ts) | otherwise = innerText (t:ts) parseRequirement :: [T.Text] -> [T.Text] parseRequirement requirement = map parseSingleReq $ filter isReq requirement where isReq t = T.length t >= 7 && not (any (flip T.isInfixOf $ t) ["First", "Second", "Third", "Higher"]) parseSingleReq = T.pack . show . parseReqs . -- Using parser for new Req type T.unpack . fromRight "" . P.parse getLineText "Reading a requirement line" . T.strip -- Strips the optional leading numbering (#.) from a line. getLineText :: Parser T.Text getLineText = do P.optional (P.digit >> P.char '.' >> P.space) parseUntil P.eof
christinem/courseography
app/WebParsing/PostParser.hs
gpl-3.0
4,147
0
18
1,072
1,190
618
572
84
3
{- To ensure GHC evalutes attributes the right number of times we disable the CSE optimisation -} {-# OPTIONS_GHC -fno-cse #-} {-# LANGUAGE DeriveDataTypeable #-} module Data.Config.Args ( Args(..) , defArgs , etcConfig ) where import System.Console.CmdArgs newtype Args = Args { configPath :: Maybe String } deriving (Show, Data, Typeable) defArgs :: Args defArgs = Args { configPath = def } etcConfig :: String etcConfig = "/etc/security-log/config.yaml"
retep007/security-log
src/Data/Config/Args.hs
gpl-3.0
483
0
7
94
90
57
33
13
1
{-# LANGUAGE OverloadedStrings #-} module Response.Loading (loadingResponse) where import Text.Blaze ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Happstack.Server import MasterTemplate loadingResponse :: String -> ServerPart Response loadingResponse size = ok $ toResponse $ masterTemplate "Courseography - Loading..." [] (do header "Loading..." if size == "small" then smallLoadingIcon else largeLoadingIcon ) "" {- Insert a large loading icon into the page -} largeLoadingIcon :: H.Html largeLoadingIcon = H.div ! A.id "loading-icon" $ do H.img ! A.id "c-logo" ! A.src "static/res/img/C-logo.png" H.img ! A.id "compass" ! A.class_ "spinner" ! A.src "static/res/img/compass.png" {- Insert a small loading icon into the page -} smallLoadingIcon :: H.Html smallLoadingIcon = H.div ! A.id "loading-icon" $ do H.img ! A.id "c-logo-small" ! A.src "static/res/img/C-logo-small.png" H.img ! A.id "compass-small" ! A.class_ "spinner" ! A.src "static/res/img/compass-small.png"
Ian-Stewart-Binks/courseography
hs/Response/Loading.hs
gpl-3.0
1,275
0
12
380
280
145
135
27
2
{- ORMOLU_DISABLE -} -- Example 13 - the rounded union of a cube and a sphere. import Control.Applicative (pure) import Graphics.Implicit out = union [ cube False (pure 20) -- same as (V3 20 20 20) , translate (pure 20) $ sphere 15 ] main = writeSTL 1 "example13.stl" out
colah/ImplicitCAD
Examples/example13.hs
agpl-3.0
282
0
10
60
72
38
34
6
1
-- different ways to generate primes ps :: Int -> [Int] ps 2 = [2] ps n = let pn1 = ps (n-1) in if any (==0) $ map (rem n) pn1 then pn1 else pn1 ++ [n] isqrt :: Integral a => a -> a isqrt = ceiling . sqrt . fromIntegral ispm :: Int -> Bool ispm 1 = True ispm 2 = True ispm n = null [q | q <- [x | x <- [2..(isqrt n)], ispm x], rem n q == 0]
ekalosak/haskell-practice
Primes.hs
lgpl-3.0
360
0
14
106
209
108
101
13
2
-- http://stackoverflow.com/questions/20849893/how-to-plot-a-graph-using-haskell-graphviz {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {- Created : 2014 Feb 26 (Wed) 18:54:30 by Harold Carr. Last Modified : 2014 Feb 28 (Fri) 17:10:45 by Harold Carr. This prints the dot versions for the examples in Data.Graph.Inductive.Example. -} module E1 where import Control.Monad (forM_) import Data.Graph.Inductive.Example import Data.Graph.Inductive.Graph (Graph (..)) import Data.GraphViz (graphToDot, nonClusteredParams, toDot) import Data.GraphViz.Printing (renderDot) import Data.Text.Lazy (unpack) showDot :: (Show (gr l el), Graph gr) => (String, gr l el) -> IO () showDot (s,g) = do putStrLn "--------------------------------------------------" putStrLn s putStrLn $ show g putStrLn "" putStrLn $ unpack $ renderDot $ toDot $ graphToDot nonClusteredParams g mapShowDot :: (Show (gr l el), Graph gr) => [(String, gr l el)] -> IO () mapShowDot xs = forM_ xs showDot main :: IO () main = do mapShowDot [("a",a),("b",b),("c",c),("e",e),("loop",loop),("ab",ab),("abb",abb),("dag3",dag3)] mapShowDot [("e3",e3)] mapShowDot [("cyc3",cyc3),("g3",g3),("g3b",g3b)] mapShowDot [("dag4",dag4)] mapShowDot [("d1",d1),("d3",d3)] mapShowDot [("clr479",clr479),("clr489",clr489)] mapShowDot [("clr486",clr486)] mapShowDot [("clr508",clr508),("clr528",clr528)] mapShowDot [("clr595",clr595),("gr1",gr1)] mapShowDot [("kin248",kin248)] mapShowDot [("vor",vor)] -- End of file.
haroldcarr/learn-haskell-coq-ml-etc
haskell/paper/haroldcarr/2014-02-28-using-graphviz-via-haskell/e1.hs
unlicense
1,767
0
10
413
556
316
240
33
1
type CardHolder = String type CardNumber = String type Address = [String] type CustomerID = Int data BillingInfo = CreditCard CardNumber CardHolder Address | CashOnDelivery | Invoice CustomerID deriving (Show)
caiorss/Functional-Programming
haskell/rwh/ch03/BookStore2.hs
unlicense
265
0
6
85
56
34
22
8
0
module Propellor.Property.Tor where import Propellor import qualified Propellor.Property.File as File import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.Service as Service import Utility.FileMode import Utility.DataUnits import System.Posix.Files import Data.Char import Data.List type HiddenServiceName = String type NodeName = String -- | Sets up a tor bridge. (Not a relay or exit node.) -- -- Uses port 443 isBridge :: Property NoInfo isBridge = configured [ ("BridgeRelay", "1") , ("Exitpolicy", "reject *:*") , ("ORPort", "443") ] `describe` "tor bridge" `requires` server -- | Sets up a tor relay. -- -- Uses port 443 isRelay :: Property NoInfo isRelay = configured [ ("BridgeRelay", "0") , ("Exitpolicy", "reject *:*") , ("ORPort", "443") ] `describe` "tor relay" `requires` server -- | Makes the tor node be named, with a known private key. -- -- This can be moved to a different IP without needing to wait to -- accumulate trust. named :: NodeName -> Property HasInfo named n = configured [("Nickname", n')] `describe` ("tor node named " ++ n') `requires` torPrivKey (Context ("tor " ++ n)) where n' = saneNickname n torPrivKey :: Context -> Property HasInfo torPrivKey context = f `File.hasPrivContent` context `onChange` File.ownerGroup f user (userGroup user) -- install tor first, so the directory exists with right perms `requires` Apt.installed ["tor"] where f = "/var/lib/tor/keys/secret_id_key" -- | A tor server (bridge, relay, or exit) -- Don't use if you just want to run tor for personal use. server :: Property NoInfo server = configured [("SocksPort", "0")] `requires` Apt.installed ["tor", "ntp"] `describe` "tor server" -- | Specifies configuration settings. Any lines in the config file -- that set other values for the specified settings will be removed, -- while other settings are left as-is. Tor is restarted when -- configuration is changed. configured :: [(String, String)] -> Property NoInfo configured settings = File.fileProperty "tor configured" go mainConfig `onChange` restarted where ks = map fst settings go ls = sort $ map toconfig $ filter (\(k, _) -> k `notElem` ks) (map fromconfig ls) ++ settings toconfig (k, v) = k ++ " " ++ v fromconfig = separate (== ' ') data BwLimit = PerSecond String | PerDay String | PerMonth String -- | Limit incoming and outgoing traffic to the specified -- amount each. -- -- For example, PerSecond "30 kibibytes" is the minimum limit -- for a useful relay. bandwidthRate :: BwLimit -> Property NoInfo bandwidthRate (PerSecond s) = bandwidthRate' s 1 bandwidthRate (PerDay s) = bandwidthRate' s (24*60*60) bandwidthRate (PerMonth s) = bandwidthRate' s (31*24*60*60) bandwidthRate' :: String -> Integer -> Property NoInfo bandwidthRate' s divby = case readSize dataUnits s of Just sz -> let v = show (sz `div` divby) ++ " bytes" in configured [("BandwidthRate", v)] `describe` ("tor BandwidthRate " ++ v) Nothing -> property ("unable to parse " ++ s) noChange hiddenServiceAvailable :: HiddenServiceName -> Int -> Property NoInfo hiddenServiceAvailable hn port = hiddenServiceHostName prop where prop = configured [ ("HiddenServiceDir", varLib </> hn) , ("HiddenServicePort", unwords [show port, "127.0.0.1:" ++ show port]) ] `describe` "hidden service available" hiddenServiceHostName p = adjustPropertySatisfy p $ \satisfy -> do r <- satisfy h <- liftIO $ readFile (varLib </> hn </> "hostname") warningMessage $ unwords ["hidden service hostname:", h] return r hiddenService :: HiddenServiceName -> Int -> Property NoInfo hiddenService hn port = configured [ ("HiddenServiceDir", varLib </> hn) , ("HiddenServicePort", unwords [show port, "127.0.0.1:" ++ show port]) ] `describe` unwords ["hidden service available:", hn, show port] hiddenServiceData :: IsContext c => HiddenServiceName -> c -> Property HasInfo hiddenServiceData hn context = combineProperties desc [ installonion "hostname" , installonion "private_key" ] where desc = unwords ["hidden service data available in", varLib </> hn] installonion f = withPrivData (PrivFile $ varLib </> hn </> f) context $ \getcontent -> property desc $ getcontent $ install $ varLib </> hn </> f install f content = ifM (liftIO $ doesFileExist f) ( noChange , ensureProperties [ property desc $ makeChange $ do createDirectoryIfMissing True (takeDirectory f) writeFileProtected f content , File.mode (takeDirectory f) $ combineModes [ownerReadMode, ownerWriteMode, ownerExecuteMode] , File.ownerGroup (takeDirectory f) user (userGroup user) , File.ownerGroup f user (userGroup user) ] ) restarted :: Property NoInfo restarted = Service.restarted "tor" mainConfig :: FilePath mainConfig = "/etc/tor/torrc" varLib :: FilePath varLib = "/var/lib/tor" varRun :: FilePath varRun = "/var/run/tor" user :: User user = User "debian-tor" type NickName = String -- | Convert String to a valid tor NickName. saneNickname :: String -> NickName saneNickname s | null n = "unnamed" | otherwise = n where legal c = isNumber c || isAsciiUpper c || isAsciiLower c n = take 19 $ filter legal s
sjfloat/propellor
src/Propellor/Property/Tor.hs
bsd-2-clause
5,177
64
16
908
1,510
818
692
113
2
{-# LANGUAGE TypeFamilies, OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Xournal.Map -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- module Data.Xournal.Map where import Data.IntMap import Data.Xournal.Simple import Data.Xournal.Generic import Data.Xournal.BBox type TPageMap = GPage Background IntMap TLayerSimple type TXournalMap = GXournal [] TPageMap type TPageBBoxMap = GPage Background IntMap TLayerBBox type TXournalBBoxMap = GXournal IntMap TPageBBoxMap type TPageBBoxMapBkg b = GPage b IntMap TLayerBBox type TXournalBBoxMapBkg b = GXournal IntMap (TPageBBoxMapBkg b) emptyGXournalMap :: GXournal IntMap a emptyGXournalMap = GXournal "" empty
wavewave/xournal-types
src/Data/Xournal/Map.hs
bsd-2-clause
875
0
7
133
143
86
57
14
1
module Interface.LpSolve where -- standard modules -- local modules import Helpful.Process --import Data.Time.Clock (diffUTCTime, getCurrentTime) --import Debug.Trace zeroObjective :: String -> Maybe Bool zeroObjective p = case head answer of "This problem is infeasible" -> Nothing "This problem is unbounded" -> Just False otherwise -> do let (chattering, value) = splitAt 29 (answer!!1) if chattering == "Value of objective function: " then if (read value :: Float) == 0.0 then Just True else Just False else error $ "lp_solve answered in an unexpected way.\n" ++ "Expected Answer: \"Value of objective function: " ++ "NUMBER\"\nActual Answer: " ++ lpAnswer where lpAnswer = unsafeReadProcess "lp_solve" [] p answer = lines lpAnswer -- old version --zeroObjective :: String -> Maybe Bool --zeroObjective p = unsafePerformIO $ do ---- start <- getCurrentTime -- (_, clpAnswer, _) <- readProcessWithExitCode "lp_solve" [] p -- let answer = lines clpAnswer ---- end <- getCurrentTime ---- print $ (show (end `diffUTCTime` start) ++ " elapsed. ") ++ clpAnswer -- case head answer of -- "This problem is infeasible" -> return Nothing -- "This problem is unbounded" -> return $ Just False -- otherwise -> do -- let (chattering, value) = splitAt 29 (answer!!1) -- if chattering == "Value of objective function: " then -- if (read value :: Float) == 0.0 then -- return $ Just True -- else -- return $ Just False -- else -- error $ "lp_solve answered in an unexpected way.\n" ++ -- "Expected Answer: \"Value of objective function: " ++ -- "NUMBER\"\nActual Answer: " ++ clpAnswer --{-# NOINLINE zeroObjective #-}
spatial-reasoning/zeno
src/Interface/LpSolve.hs
bsd-2-clause
1,952
0
15
602
196
113
83
17
5
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances #-} module Lambda.DataType.SExpr where import DeepControl.Applicative import DeepControl.Monad import Lambda.DataType.Common import Lambda.DataType.PatternMatch (PM) import qualified Lambda.DataType.PatternMatch as PM import Lambda.DataType.Type (Type((:->))) import qualified Lambda.DataType.Type as Ty import Util.Pseudo import qualified Util.LISP as L import Data.List (unwords, intersperse) import Data.Foldable (fold) -- | sugared expression data SExpr = BOOL Bool MSP | INT Integer MSP | CHAR Char MSP | UNIT MSP | VAR Name MSP        -- variable | OPR String MSP        -- symbolic operator -- tuple | TUPLE [SExpr] MSP | TPLPrj SExpr Index -- tag | TAGPrj SExpr (Name, Index) -- | FIX SExpr MSP -- syntax | IF SExpr SExpr SExpr MSP | CASE SExpr [(PM, SExpr)] MSP -- sentence | TYPESig (Name, Type) MSP | DEF Name [([PM], SExpr, MSP)] | BNF Name [(Name, [Type])] MSP -- quote | QUT SExpr MSP -- quote | QQUT SExpr MSP -- quasi-quote | UNQUT SExpr MSP -- unquote -- syntactic-sugar | APP SExpr [SExpr] MSP -- application | APPSeq [SExpr] MSP -- infix application sequence | LAM [(PM, Type)] SExpr MSP -- lambda | LAMM [(PM, Type)] SExpr MSP -- lambda-macro | AS (SExpr, Type) MSP -- ascription | LET (PM, Type) SExpr SExpr MSP | LETREC (Name, Type) SExpr SExpr MSP -- list | NIL MSP | CONS SExpr SExpr MSP | HEAD SExpr | TAIL SExpr deriving (Eq) unit = UNIT Nothing var name = VAR name Nothing bool b = BOOL b Nothing int n = INT n Nothing char c = CHAR c Nothing nil = NIL Nothing cons a d = CONS a d Nothing tuple xs = TUPLE xs Nothing fix x = FIX x Nothing app x xs = APP x xs Nothing appseq xs = APPSeq xs Nothing lam ps x = LAM ps x Nothing lamm ps x = LAMM ps x Nothing let_ p x1 x2 = LET p x1 x2 Nothing letrec p x1 x2 = LETREC p x1 x2 Nothing instance L.LISP SExpr where car (CONS a _ _) = a car _ = error "car: empty structure" cdr (CONS _ d _) = d cdr _ = error "cdr: empty structure" cons a d = CONS a d Nothing nil = NIL Nothing isCell (CONS _ _ _) = True isCell _ = False instance Show SExpr where -- value show (BOOL bool _) = show bool show (INT n _) = show n show (CHAR c _) = "'"++ [c] ++"'" -- variable show (UNIT _) = "_" show (VAR name _) = if isSymbolic name then "("++ name ++")" else name show (OPR sym _) = sym -- tuple show (TUPLE xs _) = show |$> xs >- (intersperse ", " >-> fold) >- \s -> "("++ s ++ ")" -- apply show (FIX lambda _) = "(fix " ++ show lambda ++")" show (TPLPrj x n) = show x ++"."++ show n show (TAGPrj x (name,n)) = "("++ show x ++")."++ name ++"["++ show n ++"]" -- syntax show (IF e1 e2 e3 _) = "if "++ show e1 ++" then "++ show e2 ++" else "++ show e3 show (CASE e pairs _) = "case "++ show e ++" of "++ (pairs <$| (\(pm,e) -> show pm ++" -> "++ show e) >- (intersperse " | " >-> fold)) -- sentence show (TYPESig (name, ty) _) = if isSymbolic name then "("++ name ++") :: "++ show ty else name ++" :: "++ show ty show (DEF name defs) = fold $ intersperse "\n" $ defs <$| showdef where showdef ([],s,_) = showname ++" = "++ show s showdef (pms,s,_) = showname ++" "++ (unwords $ pms <$| show) ++" = "++ show s showname = if isSymbolic name then "("++ name ++")" else name show (BNF name tags _) = "data "++ name ++" = "++ ((showTag |$> tags) >- (intersperse " | " >-> fold)) where showTag (name, []) = name showTag (name, tys) = name ++" "++ ((show |$> tys) >- (intersperse " " >-> fold)) -- quote show (QUT t _) = "{"++ show t ++ "}" show (QQUT t _) = "`"++ show t show (UNQUT t _) = ","++ show t -- syntactic-sugar show (APP e [] _) = error "APP: empty args" show (APP e args _) = "("++ show e ++" "++ (unwords $ args <$| show) ++")" show (APPSeq [] _) = error "APPSeq: empty seq" show (APPSeq (x:[]) _) = show x show (APPSeq seq _) = "("++ (unwords $ seq <$| show) ++")" show (LAM [] e _) = error "LAM: empty params" show (LAM params e _) = "(\\"++ showParams ++"."++ show e ++")" where showParams = fold $ params <$| (\(pm, ty) -> show pm ++ showType ty) >- intersperse " " where showType ty@(_ :-> _) = "::"++ "("++ show ty ++")" showType Ty.UNIT = "" showType ty = "::"++ show ty show (LAMM [] e _) = error "LAMM: empty params" show (LAMM params e _) = "("++ showParams ++ show e ++")" where showParams = fold $ params <$| (\(pm, ty) -> "#"++ show pm ++ showType ty ++ ".") where showType ty@(_ :-> _) = "::"++ "("++ show ty ++")" showType Ty.UNIT = "" showType ty = "::"++ show ty show (AS (e, ty@(_ :-> _)) _) = show e ++"::("++ show ty ++")" show (AS (e, ty) _) = show e ++"::"++ show ty show (LET (pm,Ty.UNIT) e1 e2 _) = "let "++ show pm ++" = "++ show e1 ++" in "++ show e2 show (LET (pm,ty) e1 e2 _) = "let "++ show pm ++"::"++ show ty ++" = "++ show e1 ++" in "++ show e2 show (LETREC (var,ty) e1 e2 _) = "letrec "++ var ++"::"++ show ty ++" = "++ show e1 ++" in "++ show e2 -- list show (NIL _) = "[]" show x@(CONS a d _) = if L.isList x then case a of CHAR _ _ -> show $ toString $ L.toList x _ -> show $ L.toList x else showParens a ++ ":"++ showParens d where toString [] = [] toString ((CHAR c _):cs) = c : toString cs showParens x@(LAM _ _ _) = "("++ show x ++")" showParens x@(FIX _ _) = "("++ show x ++")" showParens x@(APP _ _ _) = "("++ show x ++")" showParens x@(IF _ _ _ _) = "("++ show x ++")" showParens x@(CASE _ _ _) = "("++ show x ++")" showParens x = show x show (HEAD x) = "(head " ++ show x ++")" show (TAIL x) = "(tail " ++ show x ++")"
ocean0yohsuke/Simply-Typed-Lambda
src/Lambda/DataType/SExpr.hs
bsd-3-clause
6,954
2
14
2,660
2,742
1,427
1,315
140
1
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} -- | Model for wiki. module HL.Model.Wiki where import HL.Controller import Control.Exception.Lifted (catch) import Control.Spoon import Data.Conduit import Data.Maybe import Data.Monoid import Data.Text (unpack) import Network.HTTP.Conduit import Prelude hiding (readFile) import Text.Pandoc.Definition import Text.Pandoc.Options import Text.Pandoc.Readers.MediaWiki import Text.XML import Text.XML.Cursor -- | Get the MediaWiki markup of a wiki page and then convert it to -- HTML. getWikiPage :: Text -> IO (Either Text (Text,Pandoc)) getWikiPage article = do request <- parseUrl ("http://wiki.haskell.org/api.php?action=query&\ \prop=revisions&rvprop=content&format=xml&titles=" <> unpack article) withManager (\manager -> do response <- http request manager doc <- catch (fmap Just (responseBody response $$+- sinkDoc def)) (\(_::UnresolvedEntityException) -> return Nothing) case doc >>= parse of Nothing -> return (Left "Unable to parse XML from wiki.haskell.org.") Just (title,pan) -> return (fromMaybe (Left ("Unable to parse XML from wiki.haskell.org! \ \And the parser gave us an impure exception! \ \Can you believe it?")) (showSpoon (Right (title,pan))))) where parse doc = do let cursor = fromDocument doc title <- listToMaybe (getTitle cursor) text <- listToMaybe (getText cursor) return (title,readMediaWiki def (unpack text)) name n = Name {nameLocalName = n ,nameNamespace = Nothing ,namePrefix = Nothing} getText cursor = element (name "api") cursor >>= descendant >>= element (name "query") >>= descendant >>= element (name "pages") >>= descendant >>= element (name "page") >>= descendant >>= element (name "revisions") >>= descendant >>= element (name "rev") >>= descendant >>= content getTitle cursor = element (name "api") cursor >>= descendant >>= element (name "query") >>= descendant >>= element (name "pages") >>= descendant >>= element (name "page") >>= attribute (name "title") -- | Make a spoon using the Show instance. showSpoon :: Show a => a -> Maybe a showSpoon a = (fmap (const a) (spoon (length (show a))))
erantapaa/hl
src/HL/Model/Wiki.hs
bsd-3-clause
2,701
0
22
816
675
348
327
71
2
{-# LANGUAGE CPP #-} #include "overlapping-compat.h" module Servant.ForeignSpec where import Data.Monoid ((<>)) import Data.Proxy import Servant.Foreign import Test.Hspec spec :: Spec spec = describe "Servant.Foreign" $ do camelCaseSpec listFromAPISpec camelCaseSpec :: Spec camelCaseSpec = describe "camelCase" $ do it "converts FunctionNames to camelCase" $ do camelCase (FunctionName ["post", "counter", "inc"]) `shouldBe` "postCounterInc" camelCase (FunctionName ["get", "hyphen-ated", "counter"]) `shouldBe` "getHyphenatedCounter" ---------------------------------------------------------------------- data LangX instance HasForeignType LangX String NoContent where typeFor _ _ _ = "voidX" instance HasForeignType LangX String Int where typeFor _ _ _ = "intX" instance HasForeignType LangX String Bool where typeFor _ _ _ = "boolX" instance OVERLAPPING_ HasForeignType LangX String String where typeFor _ _ _ = "stringX" instance OVERLAPPABLE_ HasForeignType LangX String a => HasForeignType LangX String [a] where typeFor lang ftype _ = "listX of " <> typeFor lang ftype (Proxy :: Proxy a) type TestApi = "test" :> Header "header" [String] :> QueryFlag "flag" :> Get '[JSON] Int :<|> "test" :> QueryParam "param" Int :> ReqBody '[JSON] [String] :> Post '[JSON] NoContent :<|> "test" :> QueryParams "params" Int :> ReqBody '[JSON] String :> Put '[JSON] NoContent :<|> "test" :> Capture "id" Int :> Delete '[JSON] NoContent :<|> "test" :> CaptureAll "ids" Int :> Get '[JSON] [Int] testApi :: [Req String] testApi = listFromAPI (Proxy :: Proxy LangX) (Proxy :: Proxy String) (Proxy :: Proxy TestApi) listFromAPISpec :: Spec listFromAPISpec = describe "listFromAPI" $ do it "generates 4 endpoints for TestApi" $ do length testApi `shouldBe` 5 let [getReq, postReq, putReq, deleteReq, captureAllReq] = testApi it "collects all info for get request" $ do shouldBe getReq $ defReq { _reqUrl = Url [ Segment $ Static "test" ] [ QueryArg (Arg "flag" "boolX") Flag ] , _reqMethod = "GET" , _reqHeaders = [HeaderArg $ Arg "header" "listX of stringX"] , _reqBody = Nothing , _reqReturnType = Just "intX" , _reqFuncName = FunctionName ["get", "test"] } it "collects all info for post request" $ do shouldBe postReq $ defReq { _reqUrl = Url [ Segment $ Static "test" ] [ QueryArg (Arg "param" "intX") Normal ] , _reqMethod = "POST" , _reqHeaders = [] , _reqBody = Just "listX of stringX" , _reqReturnType = Just "voidX" , _reqFuncName = FunctionName ["post", "test"] } it "collects all info for put request" $ do shouldBe putReq $ defReq { _reqUrl = Url [ Segment $ Static "test" ] -- Shoud this be |intX| or |listX of intX| ? [ QueryArg (Arg "params" "listX of intX") List ] , _reqMethod = "PUT" , _reqHeaders = [] , _reqBody = Just "stringX" , _reqReturnType = Just "voidX" , _reqFuncName = FunctionName ["put", "test"] } it "collects all info for delete request" $ do shouldBe deleteReq $ defReq { _reqUrl = Url [ Segment $ Static "test" , Segment $ Cap (Arg "id" "intX") ] [] , _reqMethod = "DELETE" , _reqHeaders = [] , _reqBody = Nothing , _reqReturnType = Just "voidX" , _reqFuncName = FunctionName ["delete", "test", "by", "id"] } it "collects all info for capture all request" $ do shouldBe captureAllReq $ defReq { _reqUrl = Url [ Segment $ Static "test" , Segment $ Cap (Arg "ids" "listX of intX") ] [] , _reqMethod = "GET" , _reqHeaders = [] , _reqBody = Nothing , _reqReturnType = Just "listX of intX" , _reqFuncName = FunctionName ["get", "test", "by", "ids"] }
zerobuzz/servant
servant-foreign/test/Servant/ForeignSpec.hs
bsd-3-clause
4,035
0
24
1,120
1,148
604
544
-1
-1
{- (c) The University of Glasgow 2011 The deriving code for the Generic class (equivalent to the code in TcGenDeriv, for other classes) -} {-# LANGUAGE CPP, ScopedTypeVariables, TupleSections #-} {-# LANGUAGE FlexibleContexts #-} module TcGenGenerics (canDoGenerics, canDoGenerics1, GenericKind(..), MetaTyCons, genGenericMetaTyCons, gen_Generic_binds, get_gen1_constrained_tys) where import DynFlags import HsSyn import Type import Kind ( isKind ) import TcType import TcGenDeriv import DataCon import TyCon import FamInstEnv ( FamInst, FamFlavor(..), mkSingleCoAxiom ) import FamInst import Module ( Module, moduleName, moduleNameString , modulePackageKey, packageKeyString, getModule ) import IfaceEnv ( newGlobalBinder ) import Name hiding ( varName ) import RdrName import BasicTypes import TysWiredIn import PrelNames import InstEnv import TcEnv import MkId import TcRnMonad import HscTypes import ErrUtils( Validity(..), andValid ) import BuildTyCl import SrcLoc import Bag import VarSet (elemVarSet) import Outputable import FastString import Util import Control.Monad (mplus,forM) #include "HsVersions.h" {- ************************************************************************ * * \subsection{Bindings for the new generic deriving mechanism} * * ************************************************************************ For the generic representation we need to generate: \begin{itemize} \item A Generic instance \item A Rep type instance \item Many auxiliary datatypes and instances for them (for the meta-information) \end{itemize} -} gen_Generic_binds :: GenericKind -> TyCon -> MetaTyCons -> Module -> TcM (LHsBinds RdrName, FamInst) gen_Generic_binds gk tc metaTyCons mod = do repTyInsts <- tc_mkRepFamInsts gk tc metaTyCons mod return (mkBindsRep gk tc, repTyInsts) genGenericMetaTyCons :: TyCon -> TcM (MetaTyCons, BagDerivStuff) genGenericMetaTyCons tc = do let tc_name = tyConName tc mod = nameModule tc_name tc_cons = tyConDataCons tc tc_arits = map dataConSourceArity tc_cons tc_occ = nameOccName tc_name d_occ = mkGenD mod tc_occ c_occ m = mkGenC mod tc_occ m s_occ m n = mkGenS mod tc_occ m n mkTyCon name = ASSERT( isExternalName name ) buildAlgTyCon name [] [] Nothing [] distinctAbstractTyConRhs NonRecursive False -- Not promotable False -- Not GADT syntax NoParentTyCon loc <- getSrcSpanM -- we generate new names in current module currentMod <- getModule d_name <- newGlobalBinder currentMod d_occ loc c_names <- forM (zip [0..] tc_cons) $ \(m,_) -> newGlobalBinder currentMod (c_occ m) loc s_names <- forM (zip [0..] tc_arits) $ \(m,a) -> forM [0..a-1] $ \n -> newGlobalBinder currentMod (s_occ m n) loc let metaDTyCon = mkTyCon d_name metaCTyCons = map mkTyCon c_names metaSTyCons = map (map mkTyCon) s_names metaDts = MetaTyCons metaDTyCon metaCTyCons metaSTyCons (,) metaDts `fmap` metaTyConsToDerivStuff tc metaDts -- both the tycon declarations and related instances metaTyConsToDerivStuff :: TyCon -> MetaTyCons -> TcM BagDerivStuff metaTyConsToDerivStuff tc metaDts = do dflags <- getDynFlags dClas <- tcLookupClass datatypeClassName d_dfun_name <- newDFunName' dClas tc cClas <- tcLookupClass constructorClassName c_dfun_names <- sequence [ (conTy,) <$> newDFunName' cClas tc | conTy <- metaC metaDts ] sClas <- tcLookupClass selectorClassName s_dfun_names <- sequence (map sequence [ [ (selector,) <$> newDFunName' sClas tc | selector <- selectors ] | selectors <- metaS metaDts ]) fix_env <- getFixityEnv let (dBinds,cBinds,sBinds) = mkBindsMetaD fix_env tc mk_inst clas tc dfun_name = mkLocalInstance (mkDictFunId dfun_name [] [] clas tys) OverlapFlag { overlapMode = (NoOverlap "") , isSafeOverlap = safeLanguageOn dflags } [] clas tys where tys = [mkTyConTy tc] -- Datatype d_metaTycon = metaD metaDts d_inst = mk_inst dClas d_metaTycon d_dfun_name d_binds = InstBindings { ib_binds = dBinds , ib_tyvars = [] , ib_pragmas = [] , ib_extensions = [] , ib_derived = True } d_mkInst = DerivInst (InstInfo { iSpec = d_inst, iBinds = d_binds }) -- Constructor c_insts = [ mk_inst cClas c ds | (c, ds) <- c_dfun_names ] c_binds = [ InstBindings { ib_binds = c , ib_tyvars = [] , ib_pragmas = [] , ib_extensions = [] , ib_derived = True } | c <- cBinds ] c_mkInst = [ DerivInst (InstInfo { iSpec = is, iBinds = bs }) | (is,bs) <- myZip1 c_insts c_binds ] -- Selector s_insts = map (map (\(s,ds) -> mk_inst sClas s ds)) s_dfun_names s_binds = [ [ InstBindings { ib_binds = s , ib_tyvars = [] , ib_pragmas = [] , ib_extensions = [] , ib_derived = True } | s <- ss ] | ss <- sBinds ] s_mkInst = map (map (\(is,bs) -> DerivInst (InstInfo { iSpec = is , iBinds = bs}))) (myZip2 s_insts s_binds) myZip1 :: [a] -> [b] -> [(a,b)] myZip1 l1 l2 = ASSERT(length l1 == length l2) zip l1 l2 myZip2 :: [[a]] -> [[b]] -> [[(a,b)]] myZip2 l1 l2 = ASSERT(and (zipWith (>=) (map length l1) (map length l2))) [ zip x1 x2 | (x1,x2) <- zip l1 l2 ] return $ mapBag DerivTyCon (metaTyCons2TyCons metaDts) `unionBags` listToBag (d_mkInst : c_mkInst ++ concat s_mkInst) {- ************************************************************************ * * \subsection{Generating representation types} * * ************************************************************************ -} get_gen1_constrained_tys :: TyVar -> Type -> [Type] -- called by TcDeriv.inferConstraints; generates a list of types, each of which -- must be a Functor in order for the Generic1 instance to work. get_gen1_constrained_tys argVar = argTyFold argVar $ ArgTyAlg { ata_rec0 = const [] , ata_par1 = [], ata_rec1 = const [] , ata_comp = (:) } {- Note [Requirements for deriving Generic and Rep] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the following, T, Tfun, and Targ are "meta-variables" ranging over type expressions. (Generic T) and (Rep T) are derivable for some type expression T if the following constraints are satisfied. (a) T = (D v1 ... vn) with free variables v1, v2, ..., vn where n >= 0 v1 ... vn are distinct type variables. Cf #5939. (b) D is a type constructor *value*. In other words, D is either a type constructor or it is equivalent to the head of a data family instance (up to alpha-renaming). (c) D cannot have a "stupid context". (d) The right-hand side of D cannot include unboxed types, existential types, or universally quantified types. (e) T :: *. (Generic1 T) and (Rep1 T) are derivable for some type expression T if the following constraints are satisfied. (a),(b),(c),(d) As above. (f) T must expect arguments, and its last parameter must have kind *. We use `a' to denote the parameter of D that corresponds to the last parameter of T. (g) For any type-level application (Tfun Targ) in the right-hand side of D where the head of Tfun is not a tuple constructor: (b1) `a' must not occur in Tfun. (b2) If `a' occurs in Targ, then Tfun :: * -> *. -} canDoGenerics :: TyCon -> [Type] -> Validity -- canDoGenerics rep_tc tc_args determines if Generic/Rep can be derived for a -- type expression (rep_tc tc_arg0 tc_arg1 ... tc_argn). -- -- Check (b) from Note [Requirements for deriving Generic and Rep] is taken -- care of because canDoGenerics is applied to rep tycons. -- -- It returns Nothing if deriving is possible. It returns (Just reason) if not. canDoGenerics tc tc_args = mergeErrors ( -- Check (c) from Note [Requirements for deriving Generic and Rep]. (if (not (null (tyConStupidTheta tc))) then (NotValid (tc_name <+> text "must not have a datatype context")) else IsValid) : -- Check (a) from Note [Requirements for deriving Generic and Rep]. -- -- Data family indices can be instantiated; the `tc_args` here are -- the representation tycon args (if (all isTyVarTy (filterOut isKind tc_args)) then IsValid else NotValid (tc_name <+> text "must not be instantiated;" <+> text "try deriving `" <> tc_name <+> tc_tys <> text "' instead")) -- See comment below : (map bad_con (tyConDataCons tc))) where -- The tc can be a representation tycon. When we want to display it to the -- user (in an error message) we should print its parent (tc_name, tc_tys) = case tyConParent tc of FamInstTyCon _ ptc tys -> (ppr ptc, hsep (map ppr (tys ++ drop (length tys) tc_args))) _ -> (ppr tc, hsep (map ppr (tyConTyVars tc))) -- Check (d) from Note [Requirements for deriving Generic and Rep]. -- -- If any of the constructors has an unboxed type as argument, -- then we can't build the embedding-projection pair, because -- it relies on instantiating *polymorphic* sum and product types -- at the argument types of the constructors bad_con dc = if (any bad_arg_type (dataConOrigArgTys dc)) then (NotValid (ppr dc <+> text "must not have unlifted or polymorphic arguments")) else (if (not (isVanillaDataCon dc)) then (NotValid (ppr dc <+> text "must be a vanilla data constructor")) else IsValid) -- Nor can we do the job if it's an existential data constructor, -- Nor if the args are polymorphic types (I don't think) bad_arg_type ty = isUnLiftedType ty || not (isTauTy ty) mergeErrors :: [Validity] -> Validity mergeErrors [] = IsValid mergeErrors (NotValid s:t) = case mergeErrors t of IsValid -> NotValid s NotValid s' -> NotValid (s <> text ", and" $$ s') mergeErrors (IsValid : t) = mergeErrors t -- A datatype used only inside of canDoGenerics1. It's the result of analysing -- a type term. data Check_for_CanDoGenerics1 = CCDG1 { _ccdg1_hasParam :: Bool -- does the parameter of interest occurs in -- this type? , _ccdg1_errors :: Validity -- errors generated by this type } {- Note [degenerate use of FFoldType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use foldDataConArgs here only for its ability to treat tuples specially. foldDataConArgs also tracks covariance (though it assumes all higher-order type parameters are covariant) and has hooks for special handling of functions and polytypes, but we do *not* use those. The key issue is that Generic1 deriving currently offers no sophisticated support for functions. For example, we cannot handle data F a = F ((a -> Int) -> Int) even though a is occurring covariantly. In fact, our rule is harsh: a is simply not allowed to occur within the first argument of (->). We treat (->) the same as any other non-tuple tycon. Unfortunately, this means we have to track "the parameter occurs in this type" explicitly, even though foldDataConArgs is also doing this internally. -} -- canDoGenerics1 rep_tc tc_args determines if a Generic1/Rep1 can be derived -- for a type expression (rep_tc tc_arg0 tc_arg1 ... tc_argn). -- -- Checks (a) through (d) from Note [Requirements for deriving Generic and Rep] -- are taken care of by the call to canDoGenerics. -- -- It returns Nothing if deriving is possible. It returns (Just reason) if not. canDoGenerics1 :: TyCon -> [Type] -> Validity canDoGenerics1 rep_tc tc_args = canDoGenerics rep_tc tc_args `andValid` additionalChecks where additionalChecks -- check (f) from Note [Requirements for deriving Generic and Rep] | null (tyConTyVars rep_tc) = NotValid $ ptext (sLit "Data type") <+> quotes (ppr rep_tc) <+> ptext (sLit "must have some type parameters") | otherwise = mergeErrors $ concatMap check_con data_cons data_cons = tyConDataCons rep_tc check_con con = case check_vanilla con of j@(NotValid {}) -> [j] IsValid -> _ccdg1_errors `map` foldDataConArgs (ft_check con) con bad :: DataCon -> SDoc -> SDoc bad con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg check_vanilla :: DataCon -> Validity check_vanilla con | isVanillaDataCon con = IsValid | otherwise = NotValid (bad con existential) bmzero = CCDG1 False IsValid bmbad con s = CCDG1 True $ NotValid $ bad con s bmplus (CCDG1 b1 m1) (CCDG1 b2 m2) = CCDG1 (b1 || b2) (m1 `andValid` m2) -- check (g) from Note [degenerate use of FFoldType] ft_check :: DataCon -> FFoldType Check_for_CanDoGenerics1 ft_check con = FT { ft_triv = bmzero , ft_var = caseVar, ft_co_var = caseVar -- (component_0,component_1,...,component_n) , ft_tup = \_ components -> if any _ccdg1_hasParam (init components) then bmbad con wrong_arg else foldr bmplus bmzero components -- (dom -> rng), where the head of ty is not a tuple tycon , ft_fun = \dom rng -> -- cf #8516 if _ccdg1_hasParam dom then bmbad con wrong_arg else bmplus dom rng -- (ty arg), where head of ty is neither (->) nor a tuple constructor and -- the parameter of interest does not occur in ty , ft_ty_app = \_ arg -> arg , ft_bad_app = bmbad con wrong_arg , ft_forall = \_ body -> body -- polytypes are handled elsewhere } where caseVar = CCDG1 True IsValid existential = text "must not have existential arguments" wrong_arg = text "applies a type to an argument involving the last parameter" $$ text "but the applied type is not of kind * -> *" {- ************************************************************************ * * \subsection{Generating the RHS of a generic default method} * * ************************************************************************ -} type US = Int -- Local unique supply, just a plain Int type Alt = (LPat RdrName, LHsExpr RdrName) -- GenericKind serves to mark if a datatype derives Generic (Gen0) or -- Generic1 (Gen1). data GenericKind = Gen0 | Gen1 -- as above, but with a payload of the TyCon's name for "the" parameter data GenericKind_ = Gen0_ | Gen1_ TyVar -- as above, but using a single datacon's name for "the" parameter data GenericKind_DC = Gen0_DC | Gen1_DC TyVar forgetArgVar :: GenericKind_DC -> GenericKind forgetArgVar Gen0_DC = Gen0 forgetArgVar Gen1_DC{} = Gen1 -- When working only within a single datacon, "the" parameter's name should -- match that datacon's name for it. gk2gkDC :: GenericKind_ -> DataCon -> GenericKind_DC gk2gkDC Gen0_ _ = Gen0_DC gk2gkDC Gen1_{} d = Gen1_DC $ last $ dataConUnivTyVars d -- Bindings for the Generic instance mkBindsRep :: GenericKind -> TyCon -> LHsBinds RdrName mkBindsRep gk tycon = unitBag (mkRdrFunBind (L loc from01_RDR) from_matches) `unionBags` unitBag (mkRdrFunBind (L loc to01_RDR) to_matches) where from_matches = [mkSimpleHsAlt pat rhs | (pat,rhs) <- from_alts] to_matches = [mkSimpleHsAlt pat rhs | (pat,rhs) <- to_alts ] loc = srcLocSpan (getSrcLoc tycon) datacons = tyConDataCons tycon (from01_RDR, to01_RDR) = case gk of Gen0 -> (from_RDR, to_RDR) Gen1 -> (from1_RDR, to1_RDR) -- Recurse over the sum first from_alts, to_alts :: [Alt] (from_alts, to_alts) = mkSum gk_ (1 :: US) tycon datacons where gk_ = case gk of Gen0 -> Gen0_ Gen1 -> ASSERT(length tyvars >= 1) Gen1_ (last tyvars) where tyvars = tyConTyVars tycon -------------------------------------------------------------------------------- -- The type synonym instance and synonym -- type instance Rep (D a b) = Rep_D a b -- type Rep_D a b = ...representation type for D ... -------------------------------------------------------------------------------- tc_mkRepFamInsts :: GenericKind -- Gen0 or Gen1 -> TyCon -- The type to generate representation for -> MetaTyCons -- Metadata datatypes to refer to -> Module -- Used as the location of the new RepTy -> TcM (FamInst) -- Generated representation0 coercion tc_mkRepFamInsts gk tycon metaDts mod = -- Consider the example input tycon `D`, where data D a b = D_ a -- Also consider `R:DInt`, where { data family D x y :: * -> * -- ; data instance D Int a b = D_ a } do { -- `rep` = GHC.Generics.Rep or GHC.Generics.Rep1 (type family) fam_tc <- case gk of Gen0 -> tcLookupTyCon repTyConName Gen1 -> tcLookupTyCon rep1TyConName ; let -- `tyvars` = [a,b] (tyvars, gk_) = case gk of Gen0 -> (all_tyvars, Gen0_) Gen1 -> ASSERT(not $ null all_tyvars) (init all_tyvars, Gen1_ $ last all_tyvars) where all_tyvars = tyConTyVars tycon tyvar_args = mkTyVarTys tyvars appT :: [Type] appT = case tyConFamInst_maybe tycon of -- `appT` = D Int a b (data families case) Just (famtycon, apps) -> -- `fam` = D -- `apps` = [Int, a, b] let allApps = case gk of Gen0 -> apps Gen1 -> ASSERT(not $ null apps) init apps in [mkTyConApp famtycon allApps] -- `appT` = D a b (normal case) Nothing -> [mkTyConApp tycon tyvar_args] -- `repTy` = D1 ... (C1 ... (S1 ... (Rec0 a))) :: * -> * ; repTy <- tc_mkRepTy gk_ tycon metaDts -- `rep_name` is a name we generate for the synonym ; rep_name <- let mkGen = case gk of Gen0 -> mkGenR; Gen1 -> mkGen1R in newGlobalBinder mod (mkGen (nameOccName (tyConName tycon))) (nameSrcSpan (tyConName tycon)) ; let axiom = mkSingleCoAxiom Nominal rep_name tyvars fam_tc appT repTy ; newFamInst SynFamilyInst axiom } -------------------------------------------------------------------------------- -- Type representation -------------------------------------------------------------------------------- -- | See documentation of 'argTyFold'; that function uses the fields of this -- type to interpret the structure of a type when that type is considered as an -- argument to a constructor that is being represented with 'Rep1'. data ArgTyAlg a = ArgTyAlg { ata_rec0 :: (Type -> a) , ata_par1 :: a, ata_rec1 :: (Type -> a) , ata_comp :: (Type -> a -> a) } -- | @argTyFold@ implements a generalised and safer variant of the @arg@ -- function from Figure 3 in <http://dreixel.net/research/pdf/gdmh.pdf>. @arg@ -- is conceptually equivalent to: -- -- > arg t = case t of -- > _ | isTyVar t -> if (t == argVar) then Par1 else Par0 t -- > App f [t'] | -- > representable1 f && -- > t' == argVar -> Rec1 f -- > App f [t'] | -- > representable1 f && -- > t' has tyvars -> f :.: (arg t') -- > _ -> Rec0 t -- -- where @argVar@ is the last type variable in the data type declaration we are -- finding the representation for. -- -- @argTyFold@ is more general than @arg@ because it uses 'ArgTyAlg' to -- abstract out the concrete invocations of @Par0@, @Rec0@, @Par1@, @Rec1@, and -- @:.:@. -- -- @argTyFold@ is safer than @arg@ because @arg@ would lead to a GHC panic for -- some data types. The problematic case is when @t@ is an application of a -- non-representable type @f@ to @argVar@: @App f [argVar]@ is caught by the -- @_@ pattern, and ends up represented as @Rec0 t@. This type occurs /free/ in -- the RHS of the eventual @Rep1@ instance, which is therefore ill-formed. Some -- representable1 checks have been relaxed, and others were moved to -- @canDoGenerics1@. argTyFold :: forall a. TyVar -> ArgTyAlg a -> Type -> a argTyFold argVar (ArgTyAlg {ata_rec0 = mkRec0, ata_par1 = mkPar1, ata_rec1 = mkRec1, ata_comp = mkComp}) = -- mkRec0 is the default; use it if there is no interesting structure -- (e.g. occurrences of parameters or recursive occurrences) \t -> maybe (mkRec0 t) id $ go t where go :: Type -> -- type to fold through Maybe a -- the result (e.g. representation type), unless it's trivial go t = isParam `mplus` isApp where isParam = do -- handles parameters t' <- getTyVar_maybe t Just $ if t' == argVar then mkPar1 -- moreover, it is "the" parameter else mkRec0 t -- NB mkRec0 instead of the conventional mkPar0 isApp = do -- handles applications (phi, beta) <- tcSplitAppTy_maybe t let interesting = argVar `elemVarSet` exactTyVarsOfType beta -- Does it have no interesting structure to represent? if not interesting then Nothing else -- Is the argument the parameter? Special case for mkRec1. if Just argVar == getTyVar_maybe beta then Just $ mkRec1 phi else mkComp phi `fmap` go beta -- It must be a composition. tc_mkRepTy :: -- Gen0_ or Gen1_, for Rep or Rep1 GenericKind_ -- The type to generate representation for -> TyCon -- Metadata datatypes to refer to -> MetaTyCons -- Generated representation0 type -> TcM Type tc_mkRepTy gk_ tycon metaDts = do d1 <- tcLookupTyCon d1TyConName c1 <- tcLookupTyCon c1TyConName s1 <- tcLookupTyCon s1TyConName nS1 <- tcLookupTyCon noSelTyConName rec0 <- tcLookupTyCon rec0TyConName rec1 <- tcLookupTyCon rec1TyConName par1 <- tcLookupTyCon par1TyConName u1 <- tcLookupTyCon u1TyConName v1 <- tcLookupTyCon v1TyConName plus <- tcLookupTyCon sumTyConName times <- tcLookupTyCon prodTyConName comp <- tcLookupTyCon compTyConName let mkSum' a b = mkTyConApp plus [a,b] mkProd a b = mkTyConApp times [a,b] mkComp a b = mkTyConApp comp [a,b] mkRec0 a = mkTyConApp rec0 [a] mkRec1 a = mkTyConApp rec1 [a] mkPar1 = mkTyConTy par1 mkD a = mkTyConApp d1 [metaDTyCon, sumP (tyConDataCons a)] mkC i d a = mkTyConApp c1 [d, prod i (dataConInstOrigArgTys a $ mkTyVarTys $ tyConTyVars tycon) (null (dataConFieldLabels a))] -- This field has no label mkS True _ a = mkTyConApp s1 [mkTyConTy nS1, a] -- This field has a label mkS False d a = mkTyConApp s1 [d, a] -- Sums and products are done in the same way for both Rep and Rep1 sumP [] = mkTyConTy v1 sumP l = ASSERT(length metaCTyCons == length l) foldBal mkSum' [ mkC i d a | (d,(a,i)) <- zip metaCTyCons (zip l [0..])] -- The Bool is True if this constructor has labelled fields prod :: Int -> [Type] -> Bool -> Type prod i [] _ = ASSERT(length metaSTyCons > i) ASSERT(length (metaSTyCons !! i) == 0) mkTyConTy u1 prod i l b = ASSERT(length metaSTyCons > i) ASSERT(length l == length (metaSTyCons !! i)) foldBal mkProd [ arg d t b | (d,t) <- zip (metaSTyCons !! i) l ] arg :: Type -> Type -> Bool -> Type arg d t b = mkS b d $ case gk_ of -- Here we previously used Par0 if t was a type variable, but we -- realized that we can't always guarantee that we are wrapping-up -- all type variables in Par0. So we decided to stop using Par0 -- altogether, and use Rec0 all the time. Gen0_ -> mkRec0 t Gen1_ argVar -> argPar argVar t where -- Builds argument represention for Rep1 (more complicated due to -- the presence of composition). argPar argVar = argTyFold argVar $ ArgTyAlg {ata_rec0 = mkRec0, ata_par1 = mkPar1, ata_rec1 = mkRec1, ata_comp = mkComp} metaDTyCon = mkTyConTy (metaD metaDts) metaCTyCons = map mkTyConTy (metaC metaDts) metaSTyCons = map (map mkTyConTy) (metaS metaDts) return (mkD tycon) -------------------------------------------------------------------------------- -- Meta-information -------------------------------------------------------------------------------- data MetaTyCons = MetaTyCons { -- One meta datatype per datatype metaD :: TyCon -- One meta datatype per constructor , metaC :: [TyCon] -- One meta datatype per selector per constructor , metaS :: [[TyCon]] } instance Outputable MetaTyCons where ppr (MetaTyCons d c s) = ppr d $$ vcat (map ppr c) $$ vcat (map ppr (concat s)) metaTyCons2TyCons :: MetaTyCons -> Bag TyCon metaTyCons2TyCons (MetaTyCons d c s) = listToBag (d : c ++ concat s) -- Bindings for Datatype, Constructor, and Selector instances mkBindsMetaD :: FixityEnv -> TyCon -> ( LHsBinds RdrName -- Datatype instance , [LHsBinds RdrName] -- Constructor instances , [[LHsBinds RdrName]]) -- Selector instances mkBindsMetaD fix_env tycon = (dtBinds, allConBinds, allSelBinds) where mkBag l = foldr1 unionBags [ unitBag (mkRdrFunBind (L loc name) matches) | (name, matches) <- l ] dtBinds = mkBag ( [ (datatypeName_RDR, dtName_matches) , (moduleName_RDR, moduleName_matches) , (packageName_RDR, pkgName_matches)] ++ ifElseEmpty (isNewTyCon tycon) [ (isNewtypeName_RDR, isNewtype_matches) ] ) allConBinds = map conBinds datacons conBinds c = mkBag ( [ (conName_RDR, conName_matches c)] ++ ifElseEmpty (dataConIsInfix c) [ (conFixity_RDR, conFixity_matches c) ] ++ ifElseEmpty (length (dataConFieldLabels c) > 0) [ (conIsRecord_RDR, conIsRecord_matches c) ] ) ifElseEmpty p x = if p then x else [] fixity c = case lookupFixity fix_env (dataConName c) of Fixity n InfixL -> buildFix n leftAssocDataCon_RDR Fixity n InfixR -> buildFix n rightAssocDataCon_RDR Fixity n InfixN -> buildFix n notAssocDataCon_RDR buildFix n assoc = nlHsApps infixDataCon_RDR [nlHsVar assoc , nlHsIntLit (toInteger n)] allSelBinds = map (map selBinds) datasels selBinds s = mkBag [(selName_RDR, selName_matches s)] loc = srcLocSpan (getSrcLoc tycon) mkStringLHS s = [mkSimpleHsAlt nlWildPat (nlHsLit (mkHsString s))] datacons = tyConDataCons tycon datasels = map dataConFieldLabels datacons tyConName_user = case tyConFamInst_maybe tycon of Just (ptycon, _) -> tyConName ptycon Nothing -> tyConName tycon dtName_matches = mkStringLHS . occNameString . nameOccName $ tyConName_user moduleName_matches = mkStringLHS . moduleNameString . moduleName . nameModule . tyConName $ tycon pkgName_matches = mkStringLHS . packageKeyString . modulePackageKey . nameModule . tyConName $ tycon isNewtype_matches = [mkSimpleHsAlt nlWildPat (nlHsVar true_RDR)] conName_matches c = mkStringLHS . occNameString . nameOccName . dataConName $ c conFixity_matches c = [mkSimpleHsAlt nlWildPat (fixity c)] conIsRecord_matches _ = [mkSimpleHsAlt nlWildPat (nlHsVar true_RDR)] selName_matches s = mkStringLHS (occNameString (nameOccName s)) -------------------------------------------------------------------------------- -- Dealing with sums -------------------------------------------------------------------------------- mkSum :: GenericKind_ -- Generic or Generic1? -> US -- Base for generating unique names -> TyCon -- The type constructor -> [DataCon] -- The data constructors -> ([Alt], -- Alternatives for the T->Trep "from" function [Alt]) -- Alternatives for the Trep->T "to" function -- Datatype without any constructors mkSum _ _ tycon [] = ([from_alt], [to_alt]) where from_alt = (nlWildPat, mkM1_E (makeError errMsgFrom)) to_alt = (mkM1_P nlWildPat, makeError errMsgTo) -- These M1s are meta-information for the datatype makeError s = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString s)) tyConStr = occNameString (nameOccName (tyConName tycon)) errMsgFrom = "No generic representation for empty datatype " ++ tyConStr errMsgTo = "No values for empty datatype " ++ tyConStr -- Datatype with at least one constructor mkSum gk_ us _ datacons = -- switch the payload of gk_ to be datacon-centric instead of tycon-centric unzip [ mk1Sum (gk2gkDC gk_ d) us i (length datacons) d | (d,i) <- zip datacons [1..] ] -- Build the sum for a particular constructor mk1Sum :: GenericKind_DC -- Generic or Generic1? -> US -- Base for generating unique names -> Int -- The index of this constructor -> Int -- Total number of constructors -> DataCon -- The data constructor -> (Alt, -- Alternative for the T->Trep "from" function Alt) -- Alternative for the Trep->T "to" function mk1Sum gk_ us i n datacon = (from_alt, to_alt) where gk = forgetArgVar gk_ -- Existentials already excluded argTys = dataConOrigArgTys datacon n_args = dataConSourceArity datacon datacon_varTys = zip (map mkGenericLocal [us .. us+n_args-1]) argTys datacon_vars = map fst datacon_varTys us' = us + n_args datacon_rdr = getRdrName datacon from_alt = (nlConVarPat datacon_rdr datacon_vars, from_alt_rhs) from_alt_rhs = mkM1_E (genLR_E i n (mkProd_E gk_ us' datacon_varTys)) to_alt = (mkM1_P (genLR_P i n (mkProd_P gk us' datacon_vars)), to_alt_rhs) -- These M1s are meta-information for the datatype to_alt_rhs = case gk_ of Gen0_DC -> nlHsVarApps datacon_rdr datacon_vars Gen1_DC argVar -> nlHsApps datacon_rdr $ map argTo datacon_varTys where argTo (var, ty) = converter ty `nlHsApp` nlHsVar var where converter = argTyFold argVar $ ArgTyAlg {ata_rec0 = const $ nlHsVar unK1_RDR, ata_par1 = nlHsVar unPar1_RDR, ata_rec1 = const $ nlHsVar unRec1_RDR, ata_comp = \_ cnv -> (nlHsVar fmap_RDR `nlHsApp` cnv) `nlHsCompose` nlHsVar unComp1_RDR} -- Generates the L1/R1 sum pattern genLR_P :: Int -> Int -> LPat RdrName -> LPat RdrName genLR_P i n p | n == 0 = error "impossible" | n == 1 = p | i <= div n 2 = nlConPat l1DataCon_RDR [genLR_P i (div n 2) p] | otherwise = nlConPat r1DataCon_RDR [genLR_P (i-m) (n-m) p] where m = div n 2 -- Generates the L1/R1 sum expression genLR_E :: Int -> Int -> LHsExpr RdrName -> LHsExpr RdrName genLR_E i n e | n == 0 = error "impossible" | n == 1 = e | i <= div n 2 = nlHsVar l1DataCon_RDR `nlHsApp` genLR_E i (div n 2) e | otherwise = nlHsVar r1DataCon_RDR `nlHsApp` genLR_E (i-m) (n-m) e where m = div n 2 -------------------------------------------------------------------------------- -- Dealing with products -------------------------------------------------------------------------------- -- Build a product expression mkProd_E :: GenericKind_DC -- Generic or Generic1? -> US -- Base for unique names -> [(RdrName, Type)] -- List of variables matched on the lhs and their types -> LHsExpr RdrName -- Resulting product expression mkProd_E _ _ [] = mkM1_E (nlHsVar u1DataCon_RDR) mkProd_E gk_ _ varTys = mkM1_E (foldBal prod appVars) -- These M1s are meta-information for the constructor where appVars = map (wrapArg_E gk_) varTys prod a b = prodDataCon_RDR `nlHsApps` [a,b] wrapArg_E :: GenericKind_DC -> (RdrName, Type) -> LHsExpr RdrName wrapArg_E Gen0_DC (var, _) = mkM1_E (k1DataCon_RDR `nlHsVarApps` [var]) -- This M1 is meta-information for the selector wrapArg_E (Gen1_DC argVar) (var, ty) = mkM1_E $ converter ty `nlHsApp` nlHsVar var -- This M1 is meta-information for the selector where converter = argTyFold argVar $ ArgTyAlg {ata_rec0 = const $ nlHsVar k1DataCon_RDR, ata_par1 = nlHsVar par1DataCon_RDR, ata_rec1 = const $ nlHsVar rec1DataCon_RDR, ata_comp = \_ cnv -> nlHsVar comp1DataCon_RDR `nlHsCompose` (nlHsVar fmap_RDR `nlHsApp` cnv)} -- Build a product pattern mkProd_P :: GenericKind -- Gen0 or Gen1 -> US -- Base for unique names -> [RdrName] -- List of variables to match -> LPat RdrName -- Resulting product pattern mkProd_P _ _ [] = mkM1_P (nlNullaryConPat u1DataCon_RDR) mkProd_P gk _ vars = mkM1_P (foldBal prod appVars) -- These M1s are meta-information for the constructor where appVars = map (wrapArg_P gk) vars prod a b = prodDataCon_RDR `nlConPat` [a,b] wrapArg_P :: GenericKind -> RdrName -> LPat RdrName wrapArg_P Gen0 v = mkM1_P (k1DataCon_RDR `nlConVarPat` [v]) -- This M1 is meta-information for the selector wrapArg_P Gen1 v = m1DataCon_RDR `nlConVarPat` [v] mkGenericLocal :: US -> RdrName mkGenericLocal u = mkVarUnqual (mkFastString ("g" ++ show u)) mkM1_E :: LHsExpr RdrName -> LHsExpr RdrName mkM1_E e = nlHsVar m1DataCon_RDR `nlHsApp` e mkM1_P :: LPat RdrName -> LPat RdrName mkM1_P p = m1DataCon_RDR `nlConPat` [p] nlHsCompose :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName nlHsCompose x y = compose_RDR `nlHsApps` [x, y] -- | Variant of foldr1 for producing balanced lists foldBal :: (a -> a -> a) -> [a] -> a foldBal op = foldBal' op (error "foldBal: empty list") foldBal' :: (a -> a -> a) -> a -> [a] -> a foldBal' _ x [] = x foldBal' _ _ [y] = y foldBal' op x l = let (a,b) = splitAt (length l `div` 2) l in foldBal' op x a `op` foldBal' op x b
ghc-android/ghc
compiler/typecheck/TcGenGenerics.hs
bsd-3-clause
37,323
0
23
11,947
7,328
3,905
3,423
496
6
-- 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. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE OverloadedStrings #-} module Duckling.Email.EN.Corpus ( corpus ) where import Data.String import Prelude import Duckling.Email.Types import Duckling.Testing.Types corpus :: Corpus corpus = (testContext, allExamples) allExamples :: [Example] allExamples = concat [ examples (EmailData "alice@exAmple.io") [ "alice at exAmple.io" ] , examples (EmailData "yo+yo@blah.org") [ "yo+yo at blah.org" ] , examples (EmailData "1234+abc@x.net") [ "1234+abc at x.net" ] , examples (EmailData "jean-jacques@stuff.co.uk") [ "jean-jacques at stuff.co.uk" ] ]
rfranek/duckling
Duckling/Email/EN/Corpus.hs
bsd-3-clause
983
0
9
246
140
84
56
19
1
module SimpleLang.Syntax where import Data.Functor.Identity import Data.Maybe (fromMaybe) import qualified SimpleLang.Parser as P import Text.Parsec import qualified Text.Parsec.Expr as Ex import qualified Text.Parsec.Token as Tok data Expr = Tr | Fl | Zero | IsZero Expr | Succ Expr | Pred Expr | If Expr Expr Expr deriving (Eq, Show) ----------------- -- Parsing -- ----------------- prefixOp :: String -> (a -> a) -> Ex.Operator String () Identity a prefixOp s f = Ex.Prefix (P.reservedOp s >> return f) -- table of operations for our language table :: Ex.OperatorTable String () Identity Expr table = [ [ prefixOp "succ" Succ , prefixOp "pred" Pred , prefixOp "iszero" IsZero ] ] -- Constants : true, false, zero :: P.Parser Expr true = P.reserved "true" >> return Tr false = P.reserved "false" >> return Fl zero = P.reserved "0" >> return Zero ifthen :: P.Parser Expr ifthen = do P.reserved "if" cond <- expr P.reservedOp "then" tr <- expr P.reserved "else" fl <- expr return (If cond tr fl) factor :: P.Parser Expr factor = true <|> false <|> zero <|> ifthen <|> P.parens expr expr :: P.Parser Expr expr = Ex.buildExpressionParser table factor contents :: P.Parser a -> P.Parser a contents p = do Tok.whiteSpace P.lexer r <- p eof return r -- The toplevel function we'll expose from our Parse module is parseExpr -- which will be called as the entry point in our REPL. parseExpr :: String -> Either ParseError Expr parseExpr = parse (contents expr) "<stdin>" ----------------- -- Evaluation -- ----------------- isNum :: Expr -> Bool isNum Zero = True isNum (Succ t) = isNum t isNum _ = False isVal :: Expr -> Bool isVal Tr = True isVal Fl = True isVal t | isNum t = True isVal _ = False eval' :: Expr -> Maybe Expr eval' x = case x of IsZero Zero -> Just Tr IsZero (Succ t) | isNum t -> Just Fl IsZero t -> IsZero <$> eval' t Succ t -> Succ <$> eval' t Pred Zero -> Just Zero Pred (Succ t) | isNum t -> Just t Pred t -> Pred <$> eval' t If Tr c _ -> Just c If Fl _ a -> Just a If t c a -> (\t' -> If t' c a) <$> eval' t _ -> Nothing -- we need that function to be able to evaluate multiple times nf :: Expr -> Expr nf x = fromMaybe x (nf <$> eval' x) eval :: Expr -> Maybe Expr eval t = case nf t of nft | isVal nft -> Just nft | otherwise -> Nothing -- term is "stuck"
AlphaMarc/WYAH
src/SimpleLang/Syntax.hs
bsd-3-clause
2,692
0
11
856
909
451
458
82
11
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module Config where import Control.Applicative import Control.Exception import Data.ByteString (ByteString) import Data.Configurator as C import HFlags import System.Directory import System.FilePath import System.IO import Paths_sproxy_web defineFlag "c:config" ("sproxy-web.config" :: String) "config file" data Config = Config { dbConnectionString :: ByteString, port :: Int, staticDir :: FilePath } deriving (Show, Eq) -- | Get the connection string and the port -- from the config file getConfig :: FilePath -> IO Config getConfig configFile = do conf <- C.load [C.Required configFile] Config <$> C.require conf "db_connection_string" <*> C.require conf "port" <*> getStaticDir getStaticDir :: IO FilePath getStaticDir = do currentDir <- getCurrentDirectory staticExists <- doesDirectoryExist (currentDir </> "static") if staticExists then do hPutStrLn stderr ("Serving static files from " ++ currentDir ++ " -- This is bad since it probably allows to publicly access source code files.") return currentDir else do cabalDataDir <- getDataDir cabalDataDirExists <- doesDirectoryExist cabalDataDir if cabalDataDirExists then return cabalDataDir else throwIO (ErrorCall "directory for static files not found.")
alpmestan/spw
src/Config.hs
bsd-3-clause
1,432
0
13
332
291
152
139
38
3
module Module1.Task10 where fibonacci :: Integer -> Integer fibonacci n | n == 0 = 0 | n == 1 = 1 | n < 0 = -(-1) ^ (-n) * fibonacci (-n) | n > 0 = fibonacciIter 0 1 (n - 2) fibonacciIter acc1 acc2 0 = acc1 + acc2 fibonacciIter acc1 acc2 n = fibonacciIter (acc2) (acc1 + acc2) (n - 1)
dstarcev/stepic-haskell
src/Module1/Task10.hs
bsd-3-clause
309
0
10
89
166
84
82
10
1
{-# LANGUAGE BangPatterns #-} module Network.HPACK.Table.DoubleHashMap ( DoubleHashMap , empty , insert , delete , fromList , deleteList , Res(..) , search ) where import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as H import Data.List (foldl') import Network.HPACK.Types newtype DoubleHashMap a = DoubleHashMap (HashMap HeaderName (HashMap HeaderValue a)) deriving Show empty :: DoubleHashMap a empty = DoubleHashMap H.empty insert :: Ord a => Header -> a -> DoubleHashMap a -> DoubleHashMap a insert (k,v) p (DoubleHashMap m) = case H.lookup k m of Nothing -> let inner = H.singleton v p in DoubleHashMap $ H.insert k inner m Just inner -> let inner' = H.insert v p inner in DoubleHashMap $ H.adjust (const inner') k m delete :: Ord a => Header -> DoubleHashMap a -> DoubleHashMap a delete (k,v) dhm@(DoubleHashMap outer) = case H.lookup k outer of Nothing -> dhm -- Non-smart implementation makes duplicate keys. -- It is likely to happen to delete the same key -- in multiple times. Just inner -> case H.lookup v inner of Nothing -> dhm -- see above _ -> delete' inner where delete' inner | H.null inner' = DoubleHashMap $ H.delete k outer | otherwise = DoubleHashMap $ H.adjust (const inner') k outer where inner' = H.delete v inner fromList :: Ord a => [(a,Header)] -> DoubleHashMap a fromList alist = hashinner where ins !hp (!a,!dhm) = insert dhm a hp !hashinner = foldl' ins empty alist deleteList :: Ord a => [Header] -> DoubleHashMap a -> DoubleHashMap a deleteList hs hp = foldl' (flip delete) hp hs data Res a = N | K a | KV a search :: Ord a => Header -> DoubleHashMap a -> Res a search (k,v) (DoubleHashMap outer) = case H.lookup k outer of Nothing -> N Just inner -> case H.lookup v inner of Nothing -> case top inner of Nothing -> error "DoubleHashMap.search" Just a -> K a Just a -> KV a -- | Take an arbitrary entry. O(1) thanks to lazy evaluation. top :: HashMap k v -> Maybe v top = H.foldr (\v _ -> Just v) Nothing
bergmark/http2
Network/HPACK/Table/DoubleHashMap.hs
bsd-3-clause
2,210
0
14
597
774
392
382
51
4
{-# LANGUAGE OverloadedStrings #-} module Network.IRC.Bot.Part.Channels where import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (TVar, newTVar, readTVar, writeTVar) import Control.Monad.Trans (MonadIO(liftIO)) import Data.Monoid ((<>)) import Data.Set (Set, insert, toList) import Data.ByteString (ByteString) import Data.ByteString.Char8(unpack) import Network.IRC (Message(..), joinChan) import Network.IRC.Bot.BotMonad (BotMonad(..)) import Network.IRC.Bot.Log (LogLevel(..)) initChannelsPart :: (BotMonad m) => Set ByteString -> IO (TVar (Set ByteString), m ()) initChannelsPart chans = do channels <- atomically $ newTVar chans return (channels, channelsPart channels) channelsPart :: (BotMonad m) => TVar (Set ByteString) -> m () channelsPart channels = do msg <- askMessage let cmd = msg_command msg case cmd of "005" -> do chans <- liftIO $ atomically $ readTVar channels mapM_ doJoin (toList chans) _ -> return () where doJoin :: (BotMonad m) => ByteString -> m () doJoin chan = do sendMessage (joinChan chan) logM Normal $ "Joining room " <> chan joinChannel :: (BotMonad m) => ByteString -> TVar (Set ByteString) -> m () joinChannel chan channels = do liftIO $ atomically $ do cs <- readTVar channels writeTVar channels (insert chan cs) sendMessage (joinChan chan)
eigengrau/haskell-ircbot
Network/IRC/Bot/Part/Channels.hs
bsd-3-clause
1,451
0
14
322
505
267
238
34
2
{-# LANGUAGE MultiParamTypeClasses #-} -- | -- Module: $HEADER$ -- Description: Command line tool that generates random passwords. -- Copyright: (c) 2013 Peter Trsko -- License: BSD3 -- -- Maintainer: peter.trsko@gmail.com -- Stability: experimental -- Portability: non-portable (FlexibleContexts, depends on non-portable -- module) -- -- Command line tool that generates random passwords. module Main.Application (runApp, processOptions) where import Control.Applicative ((<$>)) import Control.Monad (replicateM) import Data.Char (isDigit) import Data.Maybe (fromMaybe) import Data.Version (Version) import Data.Word (Word32) import System.Console.GetOpt ( OptDescr(Option) , ArgDescr(NoArg) , ArgOrder(Permute) , getOpt ) import System.Exit (exitFailure) import System.IO (Handle, stderr, stdout) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS (hPutStrLn, unwords) import Data.Default.Class (Default(def)) import Data.Monoid.Endo hiding ((<>)) import Data.Semigroup (Semigroup((<>))) import System.Console.Terminal.Size as Terminal (Window(..), size) import System.Console.GetOpt.UsageInfo ( UsageInfoConfig(outputHandle) , renderUsageInfo ) import Main.ApplicationMode ( ApplicationMode(..) , SimpleMode(..) , changeAction , updateConfiguration ) import Main.ApplicationMode.SimpleAction (SimpleAction(..)) import qualified Main.ApplicationMode.SimpleAction as SimpleAction (optErrors) import Main.Common (Parameters(..), printHelp, printVersion, printOptErrors) import Main.MiniLens (E, L, get, mkL, set) import Main.Random (withGenRand) import qualified Text.Pwgen.Pronounceable as Pronounceable (genPwConfigBS) import Text.Pwgen (genPassword) import Paths_hpwgen (version) -- | Default length of password. defaultPwlen :: Word32 defaultPwlen = 8 -- | Default number of lines, this is used when printing passwords in columns, -- but number of passwords wasn't specified. defaultNumberOfLines :: Int defaultNumberOfLines = 20 -- | Line length used when printing in columns, but to a handle that isn't a -- terminal. defaultLineLength :: Int defaultLineLength = 80 type HpwgenMode = SimpleMode SimpleAction Config instance ApplicationMode SimpleMode SimpleAction Config where optErrors msgs = case SimpleAction.optErrors msgs of Nothing -> mempty Just a -> changeAction a `mappend` updateConfiguration (set outHandleL stderr) data Config = Config { cfgProgName :: String , cfgVersion :: Version , cfgPasswordLength :: Word32 , cfgNumberOfPasswords :: Maybe Int , cfgPrintInColumns :: Maybe Bool -- ^ If 'Nothing' then it's determined depending on the fact if output is -- a terminal. When 'True' and output is not a terminal 80 character width -- is assumed. And when 'False' then only one password is printed per line. , cfgGeneratePronounceable :: Bool , cfgIncludeNumbers :: Bool , cfgIncludeSymbols :: Bool , cfgIncludeUppers :: Bool , cfgOutHandle :: Handle } instance Default Config where def = Config { cfgProgName = "" , cfgVersion = version , cfgPasswordLength = defaultPwlen , cfgNumberOfPasswords = Nothing , cfgPrintInColumns = Nothing , cfgGeneratePronounceable = True , cfgIncludeNumbers = True , cfgIncludeSymbols = True , cfgIncludeUppers = True , cfgOutHandle = stdout } outHandleL :: L Config Handle outHandleL = mkL cfgOutHandle $ \ h c -> c{cfgOutHandle = h} progNameL :: L Config String progNameL = mkL cfgProgName $ \ pn c -> c{cfgProgName = pn} generatePronounceableL :: L Config Bool generatePronounceableL = mkL cfgGeneratePronounceable $ \ b c -> c{cfgGeneratePronounceable = b} passwordLengthL :: L Config Word32 passwordLengthL = mkL cfgPasswordLength $ \ n c -> c{cfgPasswordLength = n} numberOfPasswordsL :: L Config (Maybe Int) numberOfPasswordsL = mkL cfgNumberOfPasswords $ \ n c -> c{cfgNumberOfPasswords = n} includeNumbersL :: L Config Bool includeNumbersL = mkL cfgIncludeNumbers $ \ b c -> c{cfgIncludeNumbers = b} includeSymbolsL :: L Config Bool includeSymbolsL = mkL cfgIncludeSymbols $ \ b c -> c{cfgIncludeSymbols = b} includeUppersL :: L Config Bool includeUppersL = mkL cfgIncludeUppers $ \ b c -> c{cfgIncludeUppers = b} printInColumnsL :: L Config (Maybe Bool) printInColumnsL = mkL cfgPrintInColumns $ \ b c -> c{cfgPrintInColumns = b} params :: Parameters Config params = def { paramOutputHandle = get outHandleL , paramProgName = get progNameL , paramCommand = get progNameL , paramVersion = cfgVersion , paramUsage = const [ "[OPTIONS] [PASSWORD_LENGTH [NUMBER_OF_PASSWORDS]]" , "{-h|--help|-V|--version|--numeric-version}" ] } options :: [OptDescr (Endo HpwgenMode)] options = {- TODO [ Option "s" ["secure"] (NoArg . updateConfiguration $ set generatePronounceableL False) "Generate completely random passwords." -} [ Option "cu" ["capitalize", "upper"] (NoArg . updateConfiguration $ set includeUppersL True) $ defaultMark (get includeUppersL) "Upper case letters will be included in passwords." , Option "CU" ["no-capitalize", "no-upper"] (NoArg . updateConfiguration $ set includeUppersL False) $ defaultMark (not . get includeUppersL) "Upper case letters won't be included in passwords." , Option "n" ["numerals", "numbers"] (NoArg . updateConfiguration $ set includeNumbersL True) $ defaultMark (get includeNumbersL) "Numbers will be included in passwords." , Option "N0" [ "no-numerals", "no-numbers"] (NoArg . updateConfiguration $ set includeNumbersL False) $ defaultMark (not . get includeNumbersL) "Numbers won't be included in passwords." , Option "y" [ "symbols"] (NoArg . updateConfiguration $ set includeSymbolsL True) $ defaultMark (get includeSymbolsL) "Special symbols will be included in passwords." , Option "Y" [ "no-symbols"] (NoArg . updateConfiguration $ set includeSymbolsL False) $ defaultMark (not . get includeSymbolsL) "Special symbols won't be included in passwords." , Option "1" ["one-column"] (NoArg . updateConfiguration . set printInColumnsL $ Just False) "Passwords will be printed in only one column. If number of passwords\ \ is not specified, then only one password will be printed." , Option "h" ["help"] (NoArg $ changeAction PrintHelp) "Print this help and exit." , Option "V" ["version"] (NoArg . changeAction $ PrintVersion False) "Print version number and exit." , Option "" ["numeric-version"] (NoArg . changeAction $ PrintVersion True) "Print version number (numeric form only) and exit. Useful for batch\ \ processing." ] where defaultMark :: (Config -> Bool) -> String -> String defaultMark p | p def = (++ " (default)") | otherwise = id processOptions :: String -> [String] -> Endo HpwgenMode processOptions progName = mconcat . processOptions' . getOpt Permute options where processOptions' (endos, nonOpts, errs) = optErrors errs : processNonOpts nonOpts : updateConfiguration (set progNameL progName) : reverse endos setNum :: Read a => (a -> E Config) -> String -> String -> Endo HpwgenMode setNum setter what s | all isDigit s = updateConfiguration . setter $ read s | otherwise = optError $ "Incorrect " ++ what ++ ": Expecting number, but got: " ++ show s setPwNum, setPwLen :: String -> Endo HpwgenMode setPwNum = setNum (set numberOfPasswordsL . Just) "number of passwords" setPwLen = setNum (set passwordLengthL) "password length" processNonOpts opts = case opts of [] -> mempty [n] -> setPwLen n [n, m] -> setPwLen n <> setPwNum m _ -> optError . ("Too many options: " ++) . unwords $ drop 2 opts -- | Print passwords in columns. printPasswords :: Handle -> Int -- ^ Number of columns to print passwords in. -> [ByteString] -- ^ List of generated passwords. -> IO () printPasswords _ _ [] = return () printPasswords h n pws = do BS.hPutStrLn h $ BS.unwords x printPasswords h n xs where (x, xs) = splitAt n pws -- | Calculate number of columns to print passwords in and number of passwords -- that should be generated. numberOfColumnsAndPasswords :: Config -> Maybe Int -- ^ Terminal width or 'Nothing' if not a terminal. -> (Int, Int) -- ^ Number of columns to print passwords in and number of passowrds that -- will be generated. numberOfColumnsAndPasswords cfg s = case (get printInColumnsL cfg, s) of (Nothing, Nothing) -> (1, fromMaybe 1 pwNum) -- In auto mode and output is not a terminal. (Just False, _) -> (1, fromMaybe 1 pwNum) -- Forcing one column mode, then by default just one password shouls be -- printed. (Just True, Nothing) -> let cols = numberOfColumns defaultLineLength in (cols, fromMaybe (cols * defaultNumberOfLines) pwNum) -- Forced to print in columns, but output is not a terminal, assuming -- defaultLineLength character width. (_, Just n) -> let cols = numberOfColumns n in (cols, fromMaybe (cols * defaultNumberOfLines) pwNum) -- Either in auto mode or forced to print in columns, output is a -- terminal. where pwNum = fromIntegral <$> get numberOfPasswordsL cfg -- n * pwlen + n - 1 <= terminalWidth -- n * (pwlen + 1) - 1 <= terminalWidth -- -- terminalWidth + 1 -- n <= ------------------- -- pwlen + 1 numberOfColumns n | n <= pwlen = 1 | otherwise = case (n + 1) `div` (pwlen + 1) of d | d <= 1 -> 1 | otherwise -> d where pwlen = fromIntegral $ get passwordLengthL cfg runApp :: SimpleAction -> Config -> IO () runApp a cfg = case a of PrintVersion numericOnly -> printVersion' numericOnly PrintHelp -> printHelp' OptErrors errs -> printOptErrors' errs >> printHelp' >> exitFailure Action -> generatePasswords cfg where withParams f = f params cfg printVersion' = withParams printVersion printOptErrors' = withParams printOptErrors printHelp' = do str <- renderUsageInfo usageInfoCfg "" options withParams printHelp (\ _ _ -> unlines [str]) where usageInfoCfg = def{outputHandle = get outHandleL cfg} generatePasswords :: Config -> IO () generatePasswords cfg = do (cols, pwNum) <- numberOfColumnsAndPasswords cfg . fmap width <$> Terminal.size printPasswords handle cols =<< withGenRand (\ genRandom -> replicateM pwNum $ genPassword genPwCfg genRandom pwLen) where pwLen = get passwordLengthL cfg handle = get outHandleL cfg genPwCfg = (if get generatePronounceableL cfg then Pronounceable.genPwConfigBS else Pronounceable.genPwConfigBS) (get includeUppersL cfg) (get includeNumbersL cfg) (get includeSymbolsL cfg) -- secureCfg cfg =
trskop/hpwgen
src/Main/Application.hs
bsd-3-clause
11,354
0
14
2,715
2,637
1,443
1,194
218
4
{-# LANGUAGE ViewPatterns #-} module Plunge.Analytics.C2CPP ( lineAssociations ) where import Data.List import Plunge.Types.PreprocessorOutput -- Fill in any gaps left by making associations out of CPP spans. lineAssociations :: [Section] -> [LineAssociation] lineAssociations ss = concat $ snd $ mapAccumL fillGap 1 assocs where fillGap :: LineNumber -> LineAssociation -> (LineNumber, [LineAssociation]) fillGap n (LineAssociation Nothing Nothing) = (n, []) fillGap n a@(LineAssociation Nothing (Just _)) = (n, [a]) fillGap _ a@(LineAssociation (Just clr) Nothing) = (toLine clr, [a]) fillGap n a@(LineAssociation (Just clr) (Just _)) | n < cFrom = (cTo, [gap, a]) | n == cFrom = (cTo, [a]) | otherwise = (n, []) -- n > cFrom where cTo = toLine clr cFrom = fromLine clr gap = LineAssociation (Just $ LineRange n cFrom) Nothing assocs = sectionLineAssociations ss sectionLineAssociations :: [Section] -> [LineAssociation] sectionLineAssociations ss = map lineAssoc ss where lineAssoc (Block bls sl lr) = LineAssociation { cppRange = Just lr , cRange = Just $ LineRange sl (sl + (length bls)) } lineAssoc (MiscDirective _ lr) = LineAssociation { cppRange = Just lr , cRange = Nothing } lineAssoc (Expansion _ (CppDirective stop _ _) n _ lr) = LineAssociation { cppRange = Just lr , cRange = Just $ LineRange n stop }
sw17ch/plunge
src/Plunge/Analytics/C2CPP.hs
bsd-3-clause
1,653
0
14
546
509
275
234
29
4
{-# LANGUAGE GADTs, TypeOperators #-} module Compiler.InstantiateLambdas (instantiate, dump) where import Compiler.Generics import Compiler.Expression import Control.Applicative import Control.Arrow hiding (app) import Control.Monad.Reader import Data.List (intercalate) import qualified Lang.Value as V instantiate :: Arrow (~>) => V.Val l i ~> Expression instantiate = arr (flip runReader 0 . tr) where tr :: V.Val l i -> Reader Integer Expression tr (V.App f a ) = app <$> tr f <*> tr a tr (V.Con c ) = pure (con c) tr (V.Lam f ) = local (+1) (ask >>= \r -> let v = 'v':show r in lam [v] <$> tr (f (V.Var v))) tr (V.Name n e ) = name n <$> tr e tr (V.Prim s vs) = pure (prim s vs) tr (V.Var v ) = pure (var v) dump :: Arrow (~>) => Expression ~> String dump = arr rec where tr (App f e ) = rec f ++ "(\n" ++ indent (rec e) ++ ")" tr (Con c ) = c tr (Lam as e) = "(function (" ++ intercalate ", " as ++ ")" ++ "\n{\n" ++ indent ("return " ++ rec e ++ ";") ++ "\n})" tr (Name n e ) = "/* " ++ n ++ "*/ " ++ rec e tr (Prim s vs) = s vs ++ " /* free: " ++ intercalate ", " vs ++ " */" tr (Var v ) = v rec = tr . unId . out indent = unlines . map (" "++) . lines
tomlokhorst/AwesomePrelude
src/Compiler/InstantiateLambdas.hs
bsd-3-clause
1,251
0
19
341
608
309
299
-1
-1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} import Db import Parser import Trains import Result import Data.List import System.IO import System.Directory import Control.Arrow import Control.Applicative import Control.Monad import Control.Monad.Writer import Data.Monoid import Data.Maybe import Debug.Trace todo = error "TODO" {- a action parsed from user input, - takes a Db, produces a new Db and some output to print - and a flag telling us if we are done -} type Command = (Db -> (Db, String)) commands = Commands { show_all_trains = todo, show_all_routes = todo, show_train = \id -> executeQuery (find_train_by_id id) (tell . show), show_traincar = \id -> executeQuery (find_traincar_by_id id) (tell . show), show_route = \id -> executeQuery (find_route_by_id id) (tell . show), show_city = todo, show_reservation = \id -> executeQuery (find_reservation_by_id id) (tell . show), cmd_query2 = \start stop -> executeQuery (query2_query start stop) query2_printer, cmd_query3 = \train car seat -> executeQuery (query3_query train car seat) query3_printer, cmd_query4 = \trains -> executeQuery (query4_query trains) query4_printer, unknown_command = \cmd db -> (db, "Unknown command: '" ++ cmd ++ "'") } -- | Get train car from train by index. -- | Start counting at 1. -- | So a train has cars [1 .. num-cars] get_nth_car_of_train :: Train -> Int -> Maybe TrainCar get_nth_car_of_train train n = do guard (n >= 1) guard (length (train_cars train) >= n) return (train_cars train !! (n - 1)) -- | Compute all trains that pass a given station transfers :: City -> Db -> [Train] transfers city = db_trains -- get all trains >>> filter (elem city . route_cities . train_route) -- filter out trains for city executeQuery :: (Db -> Result a) -> (a -> Writer String b) -> Db -> (Db, String) executeQuery query printer db = case query db of (Ok a) -> (db, snd (runWriter (printer a))) (Err msg) -> (db, "Error: " ++ msg) train_printer train = tell (show train) -- Mindestanzahl der freien und maximale Anzahl der durch Reservierung belegten Plätze pro Zug -- und Waggon zwischen je zwei Stationen (wobei sich Minimum und Maximum darauf beziehen, -- dass Reservierungen möglicherweise nur auf Teilen der abgefragten Strecke existieren); -- Input: Eine List von Stationen -- Output: Für jeden Wagon jeden Zuges, Anzahl der freien und reservierten Plätze zwischen den Stationen. query2_query :: City -> City -> Db -> Result [(TrainId, [(TrainCarId, Int, Int)])] query2_query start stop db = do route <- route_from_endpoints start stop db -- actual query runs in list monad return $ do train <- db_trains db let cars = do traincar <- train_cars train -- filter out reservations for this train, car and route let rs = do r <- db_reservations db guard (reservation_train r == train_id train) -- filter for this train guard (reservation_traincar r == traincar_id traincar) -- filter for this traincar guard (routes_overlap route (reservation_route r)) -- filter for this route return r let free = num_free_seats_for_car traincar (map reservation_slot rs) let reserved = num_reserved_seats_for_car traincar (map reservation_slot rs) return (traincar_id traincar, free, reserved) return (train_id train, cars) query2_printer :: [(TrainId, [(TrainCarId, Int, Int)])] -> Writer String () query2_printer trains = do tell ("QUERY 2 FOUND " ++ show (length trains) ++ " RECORD(S)") forM trains $ \(train, cars) -> do tell ("TRAIN: " ++ tId train ++ "\n") forM cars $ \(traincar, free_seats, reserved_seats) -> do tell ("\tTRAIN CAR: " ++ tcId traincar ++ "\n") tell ("\t\tFREE SEATS: " ++ show free_seats ++ "\n") tell ("\t\tRESERVED SEATS: " ++ show reserved_seats ++ "\n") return () -- Reservierungen für einen bestimmten Platz in einem Zug, wobei das Ergebnis die Stationen angibt, -- zwischen denen Reservierungen bestehen; -- Input: Ein Zug, ein Wagon, eine Sitznummer -- Output: Alle Routen für die diser Sitz reserviert wurde. --query3_query :: Train -> TrainCar -> Int -> Db -> Result [[City]] query3_query train_id traincar_id seat db = do train <- find_train_by_id train_id db -- validate train traincar <- find_traincar_by_id traincar_id db -- validate traincar return $ db_reservations -- get reservations from db >>> filter ((train_id ==) . reservation_train) -- filter for this train >>> filter ((traincar_id ==) . reservation_traincar) -- filter for this train >>> filter ((slot_contains_seat seat) . reservation_slot) -- filter for `seat' >>> map reservation_route -- get cities of reservation $ db query3_printer routes = do tell ("QUERY 3 FOUND " ++ show (length routes) ++ " RECORD(S)") forM routes $ \route -> do tell (concat (intersperse ", " (map city_name route))) tell "\n" return () -- Mindestanzahl der zwischen zwei Stationen freien und der noch reservierbaren Plätze sowie die maximale Gruppengröße -- (= maximale Zahl der Personen pro Reservierung) für einen Zug oder mehrere gegebene Züge (wenn Umsteigen nötig ist). -- Input: Eine Liste von (Zug, Startstation, Endstation) Tupeln -- Output: Für jeden Tupel, Anzahl der freien und reservierbaren Plätze, sowie Länge des größten freien Bereichs in einem Wagon, -- zwischen den Stationen. query4_query :: [(TrainId, City, City)] -> Db -> Result [(TrainId, Int, Int, Int)] query4_query trains db = do forM trains $ \(train_id, start, stop) -> do train <- find_train_by_id train_id db route <- route_from_endpoints start stop db let cars = do traincar <- train_cars train -- filter out reservations for this train, car and route let rs = do r <- db_reservations db guard (reservation_train r == train_id) -- filter for this train guard (reservation_traincar r == traincar_id traincar) -- filter for this traincar guard (routes_overlap route (reservation_route r)) -- filter for this route return r let free = num_free_seats_for_car traincar (map reservation_slot rs) let max_group_size = max_group_size_for_car traincar (map reservation_slot rs) return (free, max_group_size) let free = sum (map fst cars) -- add up free seats from all cars let reservable = free - (train_res_free_seats train) -- cannot reserve seats in free quota let max_group_size = maximum (map snd cars) -- get biggest free slot return (train_id, free, reservable, max_group_size) query4_printer trains = do tell ("QUERY 4 FOUND " ++ show (length trains) ++ " RECORD(S)") forM trains $ \(train, free, reservable, max_group_size) -> do tell ("\tTRAIN " ++ show (tId train) ++ "\n") tell ("\t\tFREE SEATS: " ++ show free ++ "\n") tell ("\t\tRESERVABLE SEATS: " ++ show reservable ++ "\n") tell ("\t\tMAXIMUM GROUP SIZE: " ++ show max_group_size ++ "\n") return () num_free_seats_for_train train db = do let rs = db_reservations db let free = do car <- train_cars train let rs' = filter (\r -> reservation_traincar r == traincar_id car) rs let slots = map reservation_slot rs' return (num_free_seats_for_car car slots) return (sum free) -- | Computes the number of free seats for a traincar num_free_seats_for_car :: TrainCar -> [Slot] -> Int num_free_seats_for_car traincar = traincar_status traincar -- compute free/reserved bitmap >>> filter (==Free) -- filter for `free' bits >>> length -- count `free' bits -- | Computes the number of reserved seats for a traincar num_reserved_seats_for_car :: TrainCar -> [Slot] -> Int num_reserved_seats_for_car traincar = traincar_status traincar -- compute free/reserved bitmap >>> filter (==Reserved) -- folter for `reserved' bits >>> length -- count `reserved' bits -- | Computes the size of the biggest free slot in a train car max_group_size_for_car :: TrainCar -> [Slot] -> Int max_group_size_for_car traincar = traincar_status traincar -- create free/reserved bitmap >>> run_length_encode -- run length encode >>> filter (\(a,_) -> a==Free) -- discard reserved slots >>> map snd -- discard Free tags >>> maximum -- get maximum where run_length_encode :: Eq a => [a] -> [(a, Int)] run_length_encode [] = [] run_length_encode (l:ls) = encode l 0 (l:ls) where encode a n [] = [(a,n)] encode a n (l:ls) | a == l = encode a (n+1) ls | otherwise = (a,n) : encode l 0 (l:ls) -- | A bitmap that shows which seats of a TrainCar are reserved or free type TrainCarStatus = [SeatStatus] data SeatStatus = Free | Reserved deriving (Show, Eq) -- | Computes a bitmap telling us which seats are free or reserved from a list of reservations -- | Works by computing a bitmap for each slot and just `or'ing together the bitmaps traincar_status :: TrainCar -> [Slot] -> TrainCarStatus traincar_status traincar reservations = foldl (zipWith or) initial_status (map slot_to_status reservations) where -- initially all seats are free initial_status = times Free (traincar_num_seats traincar) -- create bitmaps from reservation slot_to_status s = times Free (slot_first_seat s - 1) ++ times Reserved (slot_num_seats s) ++ repeat Free or Free Free = Free or _ _ = Reserved -- | Create a list that contains element `a' `n' times. times :: a -> Int -> [a] times a n = take n (repeat a) -- | Given a route try to get the subroute starting at station `start' and ending at station `stop' try_find_subroute :: City -> City -> [City] -> Maybe [City] try_find_subroute start stop cities = do a <- findIndex (start==) cities b <- findIndex (stop ==) cities guard (a < b) return (drop a (take b cities)) main :: IO () main = do let db_path = "zug.db" putStrLn ">> STARTING APP" db_exists <- doesFileExist db_path when (not db_exists) $ do putStrLn ">> CREATING DATABASE" writeDb db_path db putStrLn ">> READING DATABASE" db' <- readDb db_path putStrLn ">> READ DATABASE" db'' <- mainLoop db' putStrLn ">> WRITING DATABASE" writeDb db_path db'' -- process changes in DB putStrLn ">> WROTE DATABASE" putStrLn ">> DONE" _PROMPT = "$ " mainLoop :: Db -> IO Db mainLoop db = do eof <- isEOF if eof then return db else do input <- getLine cmd <- return (parse_command commands (id $! input)) (db', output) <- return (cmd db) putStrLn output mainLoop db' readDb :: FilePath -> IO Db readDb path = do text <- readFile path return $! read $! text -- $! makes sure file is fully read writeDb :: FilePath -> Db -> IO () writeDb file db = writeFile file (show db)
fadeopolis/prog-spr-ue3
ue3.hs
bsd-3-clause
11,533
26
25
2,963
2,914
1,473
1,441
193
3
a :: Int a = 123 unittest "quote" [ (show {a}, "a"), (show {,a}, ",a"), (show {pred ,a}, "pred ,a"), ] unittest "quasiquote" [ (`a, a), (`(,a), 123), (`(pred ,a), pred 123), (let x = `(pred ,a) in x , 122), ] -- quine x = "x" q = \x. `(,x {,x}) -- godel isunprovable = "isunprovable" valueof = "valueof" g = \x -> `(isunprovable (valueof (,x {,x}))) unittest "quine & godel" [ (q {x}, x {x}), (q {q}, q {q}), (g {x}, isunprovable (valueof (x {x}))), (g {g}, isunprovable (valueof (g {g}))), ] {--}
ocean0yohsuke/Simply-Typed-Lambda
Start/UnitTest/Quote.hs
bsd-3-clause
650
23
11
247
320
195
125
-1
-1
module Test.Pos.Crypto.Gen ( -- Protocol Magic Generator genProtocolMagic , genProtocolMagicId , genRequiresNetworkMagic -- Sign Tag Generator , genSignTag -- Key Generators , genKeypair , genPublicKey , genSecretKey , genEncryptedSecretKey -- Redeem Key Generators , genRedeemKeypair , genRedeemPublicKey , genRedeemSecretKey , genUnitRedeemSignature -- VSS Key Generators , genVssKeyPair , genVssPublicKey -- Proxy Cert and Key Generators , genProxyCert , genProxySecretKey , genProxySignature , genUnitProxyCert , genUnitProxySecretKey , genUnitProxySignature -- Signature Generators , genSignature , genSignatureEncoded , genSigned , genRedeemSignature , genUnitSignature -- Secret Generators , genDecShare , genEncShare , genSharedSecretData , genSecret , genSecretProof -- Hash Generators , genAbstractHash , genWithHash , genUnitAbstractHash -- SafeSigner Generators , genSafeSigner -- PassPhrase Generators , genPassPhrase -- HD Generators , genHDPassphrase , genHDAddressPayload ) where import Universum import qualified Data.ByteArray as ByteArray import Data.List.NonEmpty (fromList) import Hedgehog import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Crypto.Hash (Blake2b_256) import Pos.Binary.Class (Bi) import Pos.Crypto (PassPhrase) import Pos.Crypto.Configuration (ProtocolMagic (..), ProtocolMagicId (..), RequiresNetworkMagic (..)) import Pos.Crypto.Hashing (AbstractHash (..), HashAlgorithm, WithHash, abstractHash, withHash) import Pos.Crypto.HD (HDAddressPayload (..), HDPassphrase (..)) import Pos.Crypto.Random (deterministic) import Pos.Crypto.SecretSharing (DecShare, EncShare, Secret, SecretProof, VssKeyPair, VssPublicKey, decryptShare, deterministicVssKeyGen, genSharedSecret, toVssPublicKey) import Pos.Crypto.Signing (EncryptedSecretKey, ProxyCert, ProxySecretKey, ProxySignature, PublicKey, SafeSigner (..), SecretKey, SignTag (..), Signature, Signed, createPsk, deterministicKeyGen, mkSigned, noPassEncrypt, proxySign, safeCreateProxyCert, safeCreatePsk, sign, signEncoded, toPublic) import Pos.Crypto.Signing.Redeem (RedeemPublicKey, RedeemSecretKey, RedeemSignature, redeemDeterministicKeyGen, redeemSign) ---------------------------------------------------------------------------- -- Protocol Magic Generator ---------------------------------------------------------------------------- genProtocolMagic :: Gen ProtocolMagic genProtocolMagic = ProtocolMagic <$> genProtocolMagicId <*> genRequiresNetworkMagic genProtocolMagicId :: Gen ProtocolMagicId genProtocolMagicId = ProtocolMagicId <$> Gen.int32 Range.constantBounded genRequiresNetworkMagic :: Gen RequiresNetworkMagic genRequiresNetworkMagic = Gen.element [RequiresNoMagic, RequiresMagic] ---------------------------------------------------------------------------- -- Sign Tag Generator ---------------------------------------------------------------------------- genSignTag :: Gen SignTag genSignTag = Gen.element [ SignForTestingOnly , SignTx , SignRedeemTx , SignVssCert , SignUSProposal , SignCommitment , SignUSVote , SignMainBlock , SignMainBlockLight , SignMainBlockHeavy , SignProxySK ] ---------------------------------------------------------------------------- -- Key Generators ---------------------------------------------------------------------------- genKeypair :: Gen (PublicKey, SecretKey) genKeypair = deterministicKeyGen <$> gen32Bytes genPublicKey :: Gen PublicKey genPublicKey = fst <$> genKeypair genSecretKey :: Gen SecretKey genSecretKey = snd <$> genKeypair genEncryptedSecretKey :: Gen EncryptedSecretKey genEncryptedSecretKey = noPassEncrypt <$> genSecretKey ---------------------------------------------------------------------------- -- Redeem Key Generators ---------------------------------------------------------------------------- genRedeemKeypair :: Gen (Maybe (RedeemPublicKey, RedeemSecretKey)) genRedeemKeypair = redeemDeterministicKeyGen <$> gen32Bytes genRedeemPublicKey :: Gen (RedeemPublicKey) genRedeemPublicKey = do rkp <- genRedeemKeypair case rkp of Nothing -> error "Error generating a RedeemPublicKey." Just (pk, _) -> return pk genRedeemSecretKey :: Gen (RedeemSecretKey) genRedeemSecretKey = do rkp <- genRedeemKeypair case rkp of Nothing -> error "Error generating a RedeemSecretKey." Just (_, sk) -> return sk genUnitRedeemSignature :: Gen (RedeemSignature ()) genUnitRedeemSignature = do pm <- genProtocolMagic genRedeemSignature pm (pure ()) ---------------------------------------------------------------------------- -- VSS Key Generators ---------------------------------------------------------------------------- genVssKeyPair :: Gen VssKeyPair genVssKeyPair = deterministicVssKeyGen <$> gen32Bytes genVssPublicKey :: Gen VssPublicKey genVssPublicKey = toVssPublicKey <$> genVssKeyPair ---------------------------------------------------------------------------- -- Proxy Cert and Key Generators ---------------------------------------------------------------------------- genProxyCert :: Bi w => ProtocolMagic -> Gen w -> Gen (ProxyCert w) genProxyCert pm genW = safeCreateProxyCert pm <$> genSafeSigner <*> genPublicKey <*> genW genProxySecretKey :: Bi w => ProtocolMagic -> Gen w -> Gen (ProxySecretKey w) genProxySecretKey pm genW = safeCreatePsk pm <$> genSafeSigner <*> genPublicKey <*> genW genProxySignature :: (Bi w, Bi a) => ProtocolMagic -> Gen a -> Gen w -> Gen (ProxySignature w a) genProxySignature pm genA genW = do delegateSk <- genSecretKey issuerSk <- genSecretKey w <- genW a <- genA let psk = createPsk pm issuerSk (toPublic delegateSk) w return $ proxySign pm SignProxySK delegateSk psk a genUnitProxyCert :: Gen (ProxyCert ()) genUnitProxyCert = do pm <- genProtocolMagic genProxyCert pm $ pure () genUnitProxySecretKey :: Gen (ProxySecretKey ()) genUnitProxySecretKey = do pm <- genProtocolMagic genProxySecretKey pm $ pure () genUnitProxySignature :: Gen (ProxySignature () ()) genUnitProxySignature = do pm <- genProtocolMagic genProxySignature pm (pure ()) (pure ()) ---------------------------------------------------------------------------- -- Signature Generators ---------------------------------------------------------------------------- genSignature :: Bi a => ProtocolMagic -> Gen a -> Gen (Signature a) genSignature pm genA = sign pm <$> genSignTag <*> genSecretKey <*> genA genSignatureEncoded :: Gen ByteString -> Gen (Signature a) genSignatureEncoded genB = signEncoded <$> genProtocolMagic <*> genSignTag <*> genSecretKey <*> genB genSigned :: Bi a => Gen a -> Gen (Signed a) genSigned genA = mkSigned <$> genProtocolMagic <*> genSignTag <*> genSecretKey <*> genA genRedeemSignature :: Bi a => ProtocolMagic -> Gen a -> Gen (RedeemSignature a) genRedeemSignature pm genA = redeemSign pm <$> gst <*> grsk <*> genA where gst = genSignTag grsk = genRedeemSecretKey genUnitSignature :: Gen (Signature ()) genUnitSignature = do pm <- genProtocolMagic genSignature pm (pure ()) ---------------------------------------------------------------------------- -- Secret Generators ---------------------------------------------------------------------------- genDecShare :: Gen DecShare genDecShare = do (_, _, xs) <- genSharedSecretData case fmap fst (uncons xs) of Just (vkp, es) -> return $ deterministic "ds" $ decryptShare vkp es Nothing -> error "Error generating a DecShare." genEncShare :: Gen EncShare genEncShare = do (_, _, xs) <- genSharedSecretData case fmap fst (uncons xs) of Just (_, es) -> return es Nothing -> error "Error generating an EncShare." genSharedSecretData :: Gen (Secret, SecretProof, [(VssKeyPair, EncShare)]) genSharedSecretData = do let numKeys = 128 :: Int parties <- Gen.integral (Range.constant 4 (fromIntegral numKeys)) :: Gen Integer threshold <- Gen.integral (Range.constant 2 (parties - 2)) :: Gen Integer vssKeyPairs <- replicateM numKeys genVssKeyPair let vssPublicKeys = map toVssPublicKey vssKeyPairs (s, sp, xs) = deterministic "ss" $ genSharedSecret threshold (fromList vssPublicKeys) ys = zipWith (\(_, y) x -> (x, y)) xs vssKeyPairs return (s, sp, ys) genSecret :: Gen Secret genSecret = do (s, _, _) <- genSharedSecretData return s genSecretProof :: Gen SecretProof genSecretProof = do (_, sp, _) <- genSharedSecretData return sp ---------------------------------------------------------------------------- -- Hash Generators ---------------------------------------------------------------------------- genAbstractHash :: (Bi a, HashAlgorithm algo) => Gen a -> Gen (AbstractHash algo a) genAbstractHash genA = abstractHash <$> genA genUnitAbstractHash :: Gen (AbstractHash Blake2b_256 ()) genUnitAbstractHash = genAbstractHash $ pure () genWithHash :: Bi a => Gen a -> Gen (WithHash a) genWithHash genA = withHash <$> genA ---------------------------------------------------------------------------- -- PassPhrase Generators ---------------------------------------------------------------------------- genPassPhrase :: Gen PassPhrase genPassPhrase = ByteArray.pack <$> genWord8List where genWord8List :: Gen [Word8] genWord8List = Gen.list (Range.singleton 32) (Gen.word8 Range.constantBounded) ---------------------------------------------------------------------------- -- SafeSigner Generators ---------------------------------------------------------------------------- genSafeSigner :: Gen SafeSigner genSafeSigner = Gen.choice gens where gens = [ SafeSigner <$> genEncryptedSecretKey <*> genPassPhrase , FakeSigner <$> genSecretKey ] ---------------------------------------------------------------------------- -- HD Generators ---------------------------------------------------------------------------- genHDPassphrase :: Gen HDPassphrase genHDPassphrase = HDPassphrase <$> gen32Bytes genHDAddressPayload :: Gen HDAddressPayload genHDAddressPayload = HDAddressPayload <$> gen32Bytes ---------------------------------------------------------------------------- -- Helper Generators ---------------------------------------------------------------------------- genBytes :: Int -> Gen ByteString genBytes n = Gen.bytes (Range.singleton n) gen32Bytes :: Gen ByteString gen32Bytes = genBytes 32
input-output-hk/pos-haskell-prototype
crypto/test/Test/Pos/Crypto/Gen.hs
mit
11,486
0
13
2,478
2,303
1,249
1,054
220
2
{- --Task 4 --power x*y = --if x*y==0 --then 0 --else if (x*y) != 0 --then x+(x*(y-1)) --These are home tasks --bb bmi --| bmi <= 10 ="a" --| bmi <= 5 = "b" --| otherwise = bmi slope (x1,y1) (x2,y2) = dy / dx where dy = y2-y1 dx = x2 - x1 --Task 2 reci x = 1/x; --Task 3 --abst x --Task 4 sign x | x<0 = -1 | x>0 = 1 | x==0 = 0 |otherwise = 0 signNum x = if x>0 then 1 else if x<0 then -1 else 0 --Task 5 threeDifferent x y z | x==y && y==z && x==z = True | otherwise = False --Task 6 maxofThree x y z | x>y && x>z = x | y>x && y>z = y | otherwise = z --Task 7 numString x | x==1 ="One" | x==2 ="Two" | x==3 ="Three" | x==4 ="Four" | x==5 ="Five" | otherwise = "Your input in not less than 6 " (!) _ True = True (!) True _ = True --This is fibnanci funciton fib:: Int -> Int fib 0 = 1 fib 1 = 1 fib x = fib(x-1) + fib(x-2) charName ::Char -> String charName 'a' = "Albert" charName 'b' = "Broseph" cahrName 'c' = "Cecil" -}
badarshahzad/Learn-Haskell
week 2 & 3/function.hs
mit
974
0
2
266
3
2
1
1
0
{- | Module : ./HasCASL/Builtin.hs Description : builtin types and functions Copyright : (c) Christian Maeder and Uni Bremen 2003 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : experimental Portability : portable HasCASL's builtin types and functions -} module HasCASL.Builtin ( cpoMap , bList , bTypes , bOps , preEnv , addBuiltins , aTypeArg , bTypeArg , cTypeArg , aType , bType , cType , botId , whenElse , ifThenElse , defId , eqId , exEq , falseId , trueId , notId , negId , andId , orId , logId , predTypeId , implId , infixIf , eqvId , resId , resType , botType , whenType , defType , eqType , notType , logType , mkQualOp , mkEqTerm , mkLogTerm , toBinJunctor , mkTerm , mkTermInst , unitTerm , unitTypeScheme ) where import Common.Id import Common.Keywords import Common.GlobalAnnotations import Common.AS_Annotation import Common.AnnoParser import Common.AnalyseAnnos import Common.Result import qualified Data.Map as Map import qualified Data.Set as Set import qualified Common.Lib.Rel as Rel import HasCASL.As import HasCASL.AsUtils import HasCASL.Le import Text.ParserCombinators.Parsec -- * buitln identifiers trueId :: Id trueId = mkId [mkSimpleId trueS] falseId :: Id falseId = mkId [mkSimpleId falseS] ifThenElse :: Id ifThenElse = mkId (map mkSimpleId [ifS, place, thenS, place, elseS, place]) whenElse :: Id whenElse = mkId (map mkSimpleId [place, whenS, place, elseS, place]) infixIf :: Id infixIf = mkInfix ifS andId :: Id andId = mkInfix lAnd orId :: Id orId = mkInfix lOr implId :: Id implId = mkInfix implS eqvId :: Id eqvId = mkInfix equivS resId :: Id resId = mkInfix "res" {- make these prefix identifier to allow "not def x" to be recognized as "not (def x)" by giving def__ higher precedence then not__. Simple identifiers usually have higher precedence then ____, otherwise "def x" would be rejected. But with simple identifiers "not def x" would be parsed as "(not def) x" because ____ is left associative. -} defId :: Id defId = mkId [mkSimpleId defS, placeTok] notId :: Id notId = mkId [mkSimpleId notS, placeTok] negId :: Id negId = mkId [mkSimpleId negS, placeTok] builtinRelIds :: Set.Set Id builtinRelIds = Set.fromList [typeId, eqId, exEq, defId] builtinLogIds :: Set.Set Id builtinLogIds = Set.fromList [andId, eqvId, implId, orId, infixIf, notId] -- | add builtin identifiers addBuiltins :: GlobalAnnos -> GlobalAnnos addBuiltins ga = let ass = assoc_annos ga newAss = Map.union ass $ Map.fromList [(applId, ALeft), (andId, ALeft), (orId, ALeft), (implId, ARight), (infixIf, ALeft), (whenElse, ARight)] precs = prec_annos ga pMap = Rel.toMap precs opIds = Set.unions (Map.keysSet pMap : Map.elems pMap) opIs = Set.toList (((Set.filter (\ i -> begPlace i || endPlace i) opIds Set.\\ builtinRelIds) Set.\\ builtinLogIds) Set.\\ Set.fromList [applId, whenElse]) logs = [(eqvId, implId), (implId, andId), (implId, orId), (eqvId, infixIf), (infixIf, andId), (infixIf, orId), (andId, notId), (orId, notId), (andId, negId), (orId, negId)] rels1 = map ( \ i -> (notId, i)) $ Set.toList builtinRelIds rels1b = map ( \ i -> (negId, i)) $ Set.toList builtinRelIds rels2 = map ( \ i -> (i, whenElse)) $ Set.toList builtinRelIds ops1 = map ( \ i -> (whenElse, i)) (applId : opIs) ops2 = map ( \ i -> (i, applId)) opIs newPrecs = foldl (\ p (a, b) -> if Rel.path b a p then p else Rel.insertDiffPair a b p) precs $ concat [logs, rels1, rels1b, rels2, ops1, ops2] in case addGlobalAnnos ga { assoc_annos = newAss , prec_annos = Rel.transClosure newPrecs } $ map parseDAnno displayStrings of Result _ (Just newGa) -> newGa _ -> error "addBuiltins" displayStrings :: [String] displayStrings = [ "%display __\\/__ %LATEX __\\vee__" , "%display __/\\__ %LATEX __\\wedge__" , "%display __=>__ %LATEX __\\Rightarrow__" , "%display __<=>__ %LATEX __\\Leftrightarrow__" , "%display not__ %LATEX \\neg__" ] parseDAnno :: String -> Annotation parseDAnno str = case parse annotationL "" str of Left _ -> error "parseDAnno" Right a -> a aVar :: Id aVar = stringToId "a" bVar :: Id bVar = stringToId "b" cVar :: Id cVar = stringToId "c" aType :: Type aType = typeArgToType aTypeArg bType :: Type bType = typeArgToType bTypeArg cType :: Type cType = typeArgToType cTypeArg lazyAType :: Type lazyAType = mkLazyType aType varToTypeArgK :: Id -> Int -> Variance -> Kind -> TypeArg varToTypeArgK i n v k = TypeArg i v (VarKind k) (toRaw k) n Other nullRange varToTypeArg :: Id -> Int -> Variance -> TypeArg varToTypeArg i n v = varToTypeArgK i n v universe mkATypeArg :: Variance -> TypeArg mkATypeArg = varToTypeArg aVar (-1) aTypeArg :: TypeArg aTypeArg = mkATypeArg NonVar aTypeArgK :: Kind -> TypeArg aTypeArgK = varToTypeArgK aVar (-1) NonVar bTypeArg :: TypeArg bTypeArg = varToTypeArg bVar (-2) NonVar cTypeArg :: TypeArg cTypeArg = varToTypeArg cVar (-3) NonVar bindVarA :: TypeArg -> Type -> TypeScheme bindVarA a t = TypeScheme [a] t nullRange bindA :: Type -> TypeScheme bindA = bindVarA aTypeArg resType :: TypeScheme resType = TypeScheme [aTypeArg, bTypeArg] (mkFunArrType (mkProductType [lazyAType, mkLazyType bType]) FunArr aType) nullRange lazyLog :: Type lazyLog = mkLazyType unitType aPredType :: Type aPredType = TypeAbs (mkATypeArg ContraVar) (mkFunArrType aType PFunArr unitType) nullRange eqType :: TypeScheme eqType = bindA $ mkFunArrType (mkProductType [lazyAType, lazyAType]) PFunArr unitType logType :: TypeScheme logType = simpleTypeScheme $ mkFunArrType (mkProductType [lazyLog, lazyLog]) PFunArr unitType notType :: TypeScheme notType = simpleTypeScheme $ mkFunArrType lazyLog PFunArr unitType whenType :: TypeScheme whenType = bindA $ mkFunArrType (mkProductType [lazyAType, lazyLog, lazyAType]) PFunArr aType unitTypeScheme :: TypeScheme unitTypeScheme = simpleTypeScheme lazyLog botId :: Id botId = mkId [mkSimpleId "bottom"] predTypeId :: Id predTypeId = mkId [mkSimpleId "Pred"] logId :: Id logId = mkId [mkSimpleId "Logical"] botType :: TypeScheme botType = let a = aTypeArgK cppoCl in bindVarA a $ mkLazyType $ typeArgToType a defType :: TypeScheme defType = bindA $ mkFunArrType lazyAType PFunArr unitType -- | builtin functions bList :: [(Id, TypeScheme)] bList = (botId, botType) : (defId, defType) : (notId, notType) : (negId, notType) : (whenElse, whenType) : (trueId, unitTypeScheme) : (falseId, unitTypeScheme) : (eqId, eqType) : (exEq, eqType) : (resId, resType) : map ( \ o -> (o, logType)) [andId, orId, eqvId, implId, infixIf] mkTypesEntry :: Id -> Kind -> [Kind] -> [Id] -> TypeDefn -> (Id, TypeInfo) mkTypesEntry i k cs s d = (i, TypeInfo (toRaw k) (Set.fromList cs) (Set.fromList s) d) funEntry :: Arrow -> [Arrow] -> [Kind] -> (Id, TypeInfo) funEntry a s cs = mkTypesEntry (arrowId a) funKind (funKind : cs) (map arrowId s) NoTypeDefn mkEntry :: Id -> Kind -> [Kind] -> TypeDefn -> (Id, TypeInfo) mkEntry i k cs = mkTypesEntry i k cs [] pEntry :: Id -> Kind -> TypeDefn -> (Id, TypeInfo) pEntry i k = mkEntry i k [k] -- | builtin data type map bTypes :: TypeMap bTypes = Map.fromList $ funEntry PFunArr [] [] : funEntry FunArr [PFunArr] [] : funEntry PContFunArr [PFunArr] [funKind3 cpoCl cpoCl cppoCl] : funEntry ContFunArr [PContFunArr, FunArr] [funKind3 cpoCl cpoCl cpoCl, funKind3 cpoCl cppoCl cppoCl] : pEntry unitTypeId cppoCl NoTypeDefn : pEntry predTypeId (FunKind ContraVar universe universe nullRange) (AliasTypeDefn aPredType) : pEntry lazyTypeId coKind NoTypeDefn : pEntry logId universe (AliasTypeDefn $ mkLazyType unitType) : map (\ n -> let k = prodKind n nullRange in mkEntry (productId n nullRange) k (k : map (prodKind1 n nullRange) [cpoCl, cppoCl]) NoTypeDefn) [2 .. 5] cpoId :: Id cpoId = stringToId "Cpo" cpoCl :: Kind cpoCl = ClassKind cpoId cppoId :: Id cppoId = stringToId "Cppo" cppoCl :: Kind cppoCl = ClassKind cppoId -- | builtin class map cpoMap :: ClassMap cpoMap = Map.fromList [ (cpoId, ClassInfo rStar $ Set.singleton universe) , (cppoId, ClassInfo rStar $ Set.singleton cpoCl)] -- | builtin function map bOps :: Assumps bOps = Map.fromList $ map ( \ (i, sc) -> (i, Set.singleton $ OpInfo sc Set.empty $ NoOpDefn Fun)) bList -- | environment with predefined names preEnv :: Env preEnv = initialEnv { classMap = cpoMap, typeMap = bTypes, assumps = bOps } mkQualOpInst :: InstKind -> Id -> TypeScheme -> [Type] -> Range -> Term mkQualOpInst k i sc tys ps = QualOp Fun (PolyId i [] ps) sc tys k ps mkQualOp :: Id -> TypeScheme -> [Type] -> Range -> Term mkQualOp = mkQualOpInst Infer mkTermInst :: InstKind -> Id -> TypeScheme -> [Type] -> Range -> Term -> Term mkTermInst k i sc tys ps t = ApplTerm (mkQualOpInst k i sc tys ps) t ps mkTerm :: Id -> TypeScheme -> [Type] -> Range -> Term -> Term mkTerm = mkTermInst Infer mkBinTerm :: Id -> TypeScheme -> [Type] -> Range -> Term -> Term -> Term mkBinTerm i sc tys ps t1 t2 = mkTerm i sc tys ps $ TupleTerm [t1, t2] ps mkLogTerm :: Id -> Range -> Term -> Term -> Term mkLogTerm i = mkBinTerm i logType [] mkEqTerm :: Id -> Type -> Range -> Term -> Term -> Term mkEqTerm i ty = mkBinTerm i eqType [ty] unitTerm :: Id -> Range -> Term unitTerm i = mkQualOp i unitTypeScheme [] toBinJunctor :: Id -> [Term] -> Range -> Term toBinJunctor i ts ps = case ts of [] -> error "toBinJunctor" [t] -> t t : rs -> mkLogTerm i ps t (toBinJunctor i rs ps)
spechub/Hets
HasCASL/Builtin.hs
gpl-2.0
10,052
0
20
2,343
3,284
1,800
1,484
265
3
{- | Module : ./CASL_DL/Parse_AS.hs Description : Parser for CASL_DL Copyright : (c) Klaus Luettich, Uni Bremen 2004 License : similar to LGPL, see HetCATS/LICENSE.txt or LIZENZ.txt Maintainer : luecke@informatik.uni-bremen.de Stability : provisional Portability : portable Parser for CASL_DL logic -} module CASL_DL.Parse_AS where import Common.AnnoState import Common.Id import Common.Lexer import Common.Parsec import Common.Token import CASL_DL.AS_CASL_DL import CASL.Formula import CASL.AS_Basic_CASL import Text.ParserCombinators.Parsec dlFormula :: AParser st DL_FORMULA dlFormula = do (ct, ctp) <- cardKeyword o <- oBracketT p <- parsePredSymb c <- cBracketT op <- oParenT t1 <- term casl_DL_reserved_words co <- anComma t2 <- term casl_DL_reserved_words t3 <- optionMaybe $ anComma >> formula casl_DL_reserved_words cp <- cParenT return $ Cardinality ct p t1 t2 t3 $ appRange ctp $ concatMapRange tokPos [o, c, op, co, cp] parsePredSymb :: AParser st PRED_SYMB parsePredSymb = fmap Pred_name (parseId casl_DL_reserved_words) <|> do o <- oParenT << addAnnos Mixfix_qual_pred qpred <- qualPredName casl_DL_reserved_words o return qpred <?> "a PRED_SYMB" cardKeyword :: AParser st (CardType, Range) cardKeyword = choice $ map ( \ v -> do kw <- asKey $ show v return (v, tokPos kw)) caslDLCardTypes instance TermParser DL_FORMULA where termParser = aToTermParser dlFormula
spechub/Hets
CASL_DL/Parse_AS.hs
gpl-2.0
1,535
0
13
348
359
179
180
37
1
-- grid is a game written in Haskell -- Copyright (C) 2018 karamellpelle@hotmail.com -- -- This file is part of grid. -- -- grid 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. -- -- grid 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 grid. If not, see <http://www.gnu.org/licenses/>. -- module MEnv.System ( #ifdef GRID_PLATFORM_IOS module MEnv.System.IOS, #endif #ifdef GRID_PLATFORM_GLFW module MEnv.System.GLFW, #endif ) where #ifdef GRID_PLATFORM_IOS import MEnv.System.IOS #endif #ifdef GRID_PLATFORM_GLFW import MEnv.System.GLFW #endif
karamellpelle/grid
source/MEnv/System.hs
gpl-3.0
1,023
0
5
180
61
50
11
2
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.WorkSpaces.CreateWorkspaces -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Creates one or more WorkSpaces. -- -- This operation is asynchronous and returns before the WorkSpaces are -- created. -- -- -- -- <http://docs.aws.amazon.com/workspaces/latest/devguide/API_CreateWorkspaces.html> module Network.AWS.WorkSpaces.CreateWorkspaces ( -- * Request CreateWorkspaces -- ** Request constructor , createWorkspaces -- ** Request lenses , cwWorkspaces -- * Response , CreateWorkspacesResponse -- ** Response constructor , createWorkspacesResponse -- ** Response lenses , cwrFailedRequests , cwrPendingRequests ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.WorkSpaces.Types import qualified GHC.Exts newtype CreateWorkspaces = CreateWorkspaces { _cwWorkspaces :: List1 "Workspaces" WorkspaceRequest } deriving (Eq, Read, Show, Semigroup) -- | 'CreateWorkspaces' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cwWorkspaces' @::@ 'NonEmpty' 'WorkspaceRequest' -- createWorkspaces :: NonEmpty WorkspaceRequest -- ^ 'cwWorkspaces' -> CreateWorkspaces createWorkspaces p1 = CreateWorkspaces { _cwWorkspaces = withIso _List1 (const id) p1 } -- | An array of structures that specify the WorkSpaces to create. cwWorkspaces :: Lens' CreateWorkspaces (NonEmpty WorkspaceRequest) cwWorkspaces = lens _cwWorkspaces (\s a -> s { _cwWorkspaces = a }) . _List1 data CreateWorkspacesResponse = CreateWorkspacesResponse { _cwrFailedRequests :: List "FailedRequests" FailedCreateWorkspaceRequest , _cwrPendingRequests :: List "PendingRequests" Workspace } deriving (Eq, Read, Show) -- | 'CreateWorkspacesResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cwrFailedRequests' @::@ ['FailedCreateWorkspaceRequest'] -- -- * 'cwrPendingRequests' @::@ ['Workspace'] -- createWorkspacesResponse :: CreateWorkspacesResponse createWorkspacesResponse = CreateWorkspacesResponse { _cwrFailedRequests = mempty , _cwrPendingRequests = mempty } -- | An array of structures that represent the WorkSpaces that could not be -- created. cwrFailedRequests :: Lens' CreateWorkspacesResponse [FailedCreateWorkspaceRequest] cwrFailedRequests = lens _cwrFailedRequests (\s a -> s { _cwrFailedRequests = a }) . _List -- | An array of structures that represent the WorkSpaces that were created. -- -- Because this operation is asynchronous, the identifier in 'WorkspaceId' is not -- immediately available. If you immediately call 'DescribeWorkspaces' with this -- identifier, no information will be returned. cwrPendingRequests :: Lens' CreateWorkspacesResponse [Workspace] cwrPendingRequests = lens _cwrPendingRequests (\s a -> s { _cwrPendingRequests = a }) . _List instance ToPath CreateWorkspaces where toPath = const "/" instance ToQuery CreateWorkspaces where toQuery = const mempty instance ToHeaders CreateWorkspaces instance ToJSON CreateWorkspaces where toJSON CreateWorkspaces{..} = object [ "Workspaces" .= _cwWorkspaces ] instance AWSRequest CreateWorkspaces where type Sv CreateWorkspaces = WorkSpaces type Rs CreateWorkspaces = CreateWorkspacesResponse request = post "CreateWorkspaces" response = jsonResponse instance FromJSON CreateWorkspacesResponse where parseJSON = withObject "CreateWorkspacesResponse" $ \o -> CreateWorkspacesResponse <$> o .:? "FailedRequests" .!= mempty <*> o .:? "PendingRequests" .!= mempty
kim/amazonka
amazonka-workspaces/gen/Network/AWS/WorkSpaces/CreateWorkspaces.hs
mpl-2.0
4,636
0
13
920
571
343
228
66
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.SNS.ListTopics -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of the requester\'s topics. Each call returns a limited -- list of topics, up to 100. If there are more topics, a 'NextToken' is -- also returned. Use the 'NextToken' parameter in a new 'ListTopics' call -- to get further results. -- -- /See:/ <http://docs.aws.amazon.com/sns/latest/api/API_ListTopics.html AWS API Reference> for ListTopics. -- -- This operation returns paginated results. module Network.AWS.SNS.ListTopics ( -- * Creating a Request listTopics , ListTopics -- * Request Lenses , ltNextToken -- * Destructuring the Response , listTopicsResponse , ListTopicsResponse -- * Response Lenses , ltrsTopics , ltrsNextToken , ltrsResponseStatus ) where import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.SNS.Types import Network.AWS.SNS.Types.Product -- | /See:/ 'listTopics' smart constructor. newtype ListTopics = ListTopics' { _ltNextToken :: Maybe Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListTopics' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ltNextToken' listTopics :: ListTopics listTopics = ListTopics' { _ltNextToken = Nothing } -- | Token returned by the previous 'ListTopics' request. ltNextToken :: Lens' ListTopics (Maybe Text) ltNextToken = lens _ltNextToken (\ s a -> s{_ltNextToken = a}); instance AWSPager ListTopics where page rq rs | stop (rs ^. ltrsNextToken) = Nothing | stop (rs ^. ltrsTopics) = Nothing | otherwise = Just $ rq & ltNextToken .~ rs ^. ltrsNextToken instance AWSRequest ListTopics where type Rs ListTopics = ListTopicsResponse request = postQuery sNS response = receiveXMLWrapper "ListTopicsResult" (\ s h x -> ListTopicsResponse' <$> (x .@? "Topics" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "NextToken") <*> (pure (fromEnum s))) instance ToHeaders ListTopics where toHeaders = const mempty instance ToPath ListTopics where toPath = const "/" instance ToQuery ListTopics where toQuery ListTopics'{..} = mconcat ["Action" =: ("ListTopics" :: ByteString), "Version" =: ("2010-03-31" :: ByteString), "NextToken" =: _ltNextToken] -- | Response for ListTopics action. -- -- /See:/ 'listTopicsResponse' smart constructor. data ListTopicsResponse = ListTopicsResponse' { _ltrsTopics :: !(Maybe [Topic]) , _ltrsNextToken :: !(Maybe Text) , _ltrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListTopicsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ltrsTopics' -- -- * 'ltrsNextToken' -- -- * 'ltrsResponseStatus' listTopicsResponse :: Int -- ^ 'ltrsResponseStatus' -> ListTopicsResponse listTopicsResponse pResponseStatus_ = ListTopicsResponse' { _ltrsTopics = Nothing , _ltrsNextToken = Nothing , _ltrsResponseStatus = pResponseStatus_ } -- | A list of topic ARNs. ltrsTopics :: Lens' ListTopicsResponse [Topic] ltrsTopics = lens _ltrsTopics (\ s a -> s{_ltrsTopics = a}) . _Default . _Coerce; -- | Token to pass along to the next 'ListTopics' request. This element is -- returned if there are additional topics to retrieve. ltrsNextToken :: Lens' ListTopicsResponse (Maybe Text) ltrsNextToken = lens _ltrsNextToken (\ s a -> s{_ltrsNextToken = a}); -- | The response status code. ltrsResponseStatus :: Lens' ListTopicsResponse Int ltrsResponseStatus = lens _ltrsResponseStatus (\ s a -> s{_ltrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-sns/gen/Network/AWS/SNS/ListTopics.hs
mpl-2.0
4,692
0
16
1,104
745
437
308
86
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ECS.ListServices -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Lists the services that are running in a specified cluster. -- -- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListServices.html> module Network.AWS.ECS.ListServices ( -- * Request ListServices -- ** Request constructor , listServices -- ** Request lenses , lsCluster , lsMaxResults , lsNextToken -- * Response , ListServicesResponse -- ** Response constructor , listServicesResponse -- ** Response lenses , lsrNextToken , lsrServiceArns ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.ECS.Types import qualified GHC.Exts data ListServices = ListServices { _lsCluster :: Maybe Text , _lsMaxResults :: Maybe Int , _lsNextToken :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ListServices' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lsCluster' @::@ 'Maybe' 'Text' -- -- * 'lsMaxResults' @::@ 'Maybe' 'Int' -- -- * 'lsNextToken' @::@ 'Maybe' 'Text' -- listServices :: ListServices listServices = ListServices { _lsCluster = Nothing , _lsNextToken = Nothing , _lsMaxResults = Nothing } -- | The short name or full Amazon Resource Name (ARN) of the cluster that hosts -- the services you want to list. If you do not specify a cluster, the default -- cluster is assumed.. lsCluster :: Lens' ListServices (Maybe Text) lsCluster = lens _lsCluster (\s a -> s { _lsCluster = a }) -- | The maximum number of container instance results returned by 'ListServices' in -- paginated output. When this parameter is used, 'ListServices' only returns 'maxResults' results in a single page along with a 'nextToken' response element. The -- remaining results of the initial request can be seen by sending another 'ListServices' request with the returned 'nextToken' value. This value can be between 1 and -- 100. If this parameter is not used, then 'ListServices' returns up to 100 -- results and a 'nextToken' value if applicable. lsMaxResults :: Lens' ListServices (Maybe Int) lsMaxResults = lens _lsMaxResults (\s a -> s { _lsMaxResults = a }) -- | The 'nextToken' value returned from a previous paginated 'ListServices' request -- where 'maxResults' was used and the results exceeded the value of that -- parameter. Pagination continues from the end of the previous results that -- returned the 'nextToken' value. This value is 'null' when there are no more -- results to return. lsNextToken :: Lens' ListServices (Maybe Text) lsNextToken = lens _lsNextToken (\s a -> s { _lsNextToken = a }) data ListServicesResponse = ListServicesResponse { _lsrNextToken :: Maybe Text , _lsrServiceArns :: List "serviceArns" Text } deriving (Eq, Ord, Read, Show) -- | 'ListServicesResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lsrNextToken' @::@ 'Maybe' 'Text' -- -- * 'lsrServiceArns' @::@ ['Text'] -- listServicesResponse :: ListServicesResponse listServicesResponse = ListServicesResponse { _lsrServiceArns = mempty , _lsrNextToken = Nothing } -- | The 'nextToken' value to include in a future 'ListServices' request. When the -- results of a 'ListServices' request exceed 'maxResults', this value can be used -- to retrieve the next page of results. This value is 'null' when there are no -- more results to return. lsrNextToken :: Lens' ListServicesResponse (Maybe Text) lsrNextToken = lens _lsrNextToken (\s a -> s { _lsrNextToken = a }) -- | The list of full Amazon Resource Name (ARN) entries for each service -- associated with the specified cluster. lsrServiceArns :: Lens' ListServicesResponse [Text] lsrServiceArns = lens _lsrServiceArns (\s a -> s { _lsrServiceArns = a }) . _List instance ToPath ListServices where toPath = const "/" instance ToQuery ListServices where toQuery = const mempty instance ToHeaders ListServices instance ToJSON ListServices where toJSON ListServices{..} = object [ "cluster" .= _lsCluster , "nextToken" .= _lsNextToken , "maxResults" .= _lsMaxResults ] instance AWSRequest ListServices where type Sv ListServices = ECS type Rs ListServices = ListServicesResponse request = post "ListServices" response = jsonResponse instance FromJSON ListServicesResponse where parseJSON = withObject "ListServicesResponse" $ \o -> ListServicesResponse <$> o .:? "nextToken" <*> o .:? "serviceArns" .!= mempty
romanb/amazonka
amazonka-ecs/gen/Network/AWS/ECS/ListServices.hs
mpl-2.0
5,564
0
12
1,164
688
415
273
73
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE TupleSections #-} #if MIN_VERSION_base(4,8,0) {-# LANGUAGE PatternSynonyms #-} #endif module Succinct.Sequence ( -- $intro WaveletTree(..), Encoding(..), buildOptimizedAlphabeticalSearchTree, huTucker, validHuTuckerTree, ) where import Control.Applicative import Control.Monad import Data.Profunctor import Data.Bifunctor import Data.Bits import qualified Data.Foldable as F import qualified Data.Traversable as T import Data.Ord import Data.List import Data.Function import Succinct.Tree.Types import Succinct.Dictionary.Builder import Succinct.Internal.Building import Succinct.Dictionary.Class import Succinct.Dictionary.Rank9 import Data.Bitraversable import qualified Data.PriorityQueue.FingerTree as PQ import qualified Data.Map as M import qualified Data.Sequence as S import qualified Data.IntSet as IS import qualified Data.Vector.Unboxed as V import qualified Data.Vector.Unboxed.Mutable as MV import Data.Maybe import Control.Monad.ST (runST) import Control.Monad.ST.Unsafe import Data.Monoid import Debug.Trace -- $setup -- >>> :set -XFlexibleContexts -- The members of the alphabet need an encoding newtype Encoding a = Encoding { runEncoding :: Labelled () a } deriving Show directionToBool :: Direction -> Bool #if MIN_VERSION_base(4,8,0) -- We have pattern synonyms newtype Direction = Direction Bool instance Show Direction where show (Direction False) = show "L" show (Direction True) = show "R" pattern L = Direction False pattern R = Direction True directionToBool (Direction x) = x #else data Direction = L | R deriving Show directionToBool L = False directionToBool R = True #endif -- endif MIN_VERSION_base(4,8,0) {-# INLINE directionToBool #-} -- | O(nlog(n)). Given elements in a dictionary and their probability of occuring, -- produce a huffman encoding. huffmanEncoding :: (Num n, Ord n, Functor m, Monad m) => [(a, n)] -> m (Encoding a) huffmanEncoding input = let initial = PQ.fromList $ fmap (\(a, b) -> (b, LabelledTip a)) input in Encoding <$> huffmanHeapToTree initial huffmanHeapToTree :: (Ord n, Num n, Monad m) => PQ.PQueue n (Labelled () a) -> m (Labelled () a) huffmanHeapToTree pq = case PQ.minViewWithKey pq of Just ((k, v), rest) -> case PQ.minViewWithKey rest of Just ((k2, v2), rest2) -> huffmanHeapToTree $ PQ.insert (k+k2) (LabelledBin () v v2) rest2 Nothing -> return v Nothing -> fail "huffmanEncoding: No elements received" buildHistogram :: (Ord a, Num n) => Builder a (M.Map a n) buildHistogram = Builder $ Building stop step start where stop = pure step x c = pure $ M.insertWith (+) c 1 x start = pure M.empty buildHuffmanEncoding :: forall a. (Ord a) => Builder a (Encoding a) buildHuffmanEncoding = fmap (fromJust . huffmanEncoding . M.toList) (buildHistogram :: Builder a (M.Map a Int)) -- | O(n^2). Given a list of characters of an alphabet with a -- frequency, produce an encoding that respects the order provided. -- TODO: this is an implementation of Knuth's O(n^2) dynamic -- programming solution. Hu-Tucker can solve this in O(nlogn) in -- general. buildOptimalAlphabeticSearchTree :: [(a, n)] -> Builder a (Encoding a) buildOptimalAlphabeticSearchTree = undefined diagonalIndex n i j | trace ("(i, j) = " <> show (i,j)) False = undefined diagonalIndex n i j = n * i - i * (i + 1) `div` 2 + j -- data KnuthBuilder s a = KnuthBuilder { weight :: V.STVector s a -- , root :: V.STVector s a -- , path :: V.STVector s a -- } foldableLength :: F.Foldable f => f a -> Int #if MIN_VERSION_base(4,8,0) foldableLength = F.length #else foldableLength = length . F.toList #endif -- --buildOptimalSearchTree :: (Functor f, F.Foldable f, n ~ Int) => f (a, n) -> Labelled () a -- buildOptimalSearchTree input = runST $ do -- let n = foldableLength input -- space = (n+1) * (n+2) `div` 2 -- index = diagonalIndex (n+1) -- get v (i, j) = if j < i then error (show (i, j)) else MV.read v (index i j) -- -- no checks -- grab v (i, j) = MV.read v (index i j) -- weight <- MV.new space -- root <- MV.replicate space (-1) -- path <- MV.new space -- forM_ (zip [1..n] $ F.toList $ fmap snd input) $ \(k, p) -> do -- let i = index k k -- MV.write weight i p -- MV.write root i k -- MV.write path i p -- MV.write path (index k (k-1)) 0 -- MV.write path (index (n+1) n) 0 -- forM_ [1..n-1] $ \diagonal -> do -- forM_ [1..n-diagonal] $ \j -> do -- let k = j + diagonal -- MV.write weight (index j k) =<< ((+) <$> (weight `get` (j, k-1)) <*> (weight `get` (k, k))) -- root1 <- root `get` (j, k-1) -- root2 <- root `get` (j+1, k) -- (p, _) <- F.minimumBy (comparing snd) <$> ( -- forM [root1..root2] $ \p -> do -- a <- path `grab` (j, p-1) -- b <- path `grab` (p+1, k) -- return (p, a + b)) -- unsafeIOToST $ putStrLn $ "p: " <> show p -- unsafeIOToST $ putStrLn $ "root" <> show (j,k) <> ": " <> show p -- MV.write root (index j k) p -- MV.write path (index j k) =<< liftA3 (\a b c -> a + b + c) (path `grab` (j, p-1)) (path `grab` (p+1, k)) (weight `get` (j, k)) -- let go (i, j) | i > j = error $ "creating tree found i > j: " <> show (i, j) -- go (i, j) | i == j = pure $ LabelledTip $ i-1 -- go (i, j) = do -- split <- root `grab` (i, j) -- LabelledBin (split - 1) <$> go (i, split-1) <*> go (split+1, j) -- let depth _ (i, j) | i > j = error $ "creating tree found i > j: " <> show (i, j) -- depth !d (i, j) | i == j = pure $ [(d, i-1)] -- depth !d (i, j) = do -- split <- root `grab` (i, j) -- lefties <- depth (d+1) (i, split-1) -- righties <- depth (d+1) (split+1, j) -- return $ [(d, split - 1)] ++ lefties ++ righties -- depth 0 (1, n) data Attraction = PreviousPrevious | Previous | Self | Next | NextNext deriving (Show, Eq, Ord) data Elem heap b a = Elem (Either a (heap b)) [Attraction] | LeftBoundary | RightBoundary deriving (Eq) instance (Show a, Show b, F.Foldable heap) => Show (Elem heap b a) where show (Elem (Left x) a) = "Elem " <> show x <> " " <> show a show (Elem (Right h) a) = "Elem " <> show (F.toList h) <> " " <> show a show LeftBoundary = "LeftBoundary" show RightBoundary = "RightBoundary" attraction (Elem _ a) = a attraction LeftBoundary = [Previous] attraction RightBoundary = [Next] isBoundary LeftBoundary = True isBoundary RightBoundary = True isBoundary _ = False decideAttraction xs = map f $ filter ok $ tails $ Nothing : fmap Just xs ++ [Nothing] where f (Nothing:_:_:_) = Next f (_:_:Nothing:_) = Previous f (Just a:Just _:Just c:_) = case compare a c of LT -> Previous _ -> Next ok (_:_:_:_) = True ok _ = False --huTucker :: huTucker = constructTree . breadthFirstSearch . buildOptimizedAlphabeticalSearchTree -- return tree in increasing depth breadthFirstSearch :: Labelled () a -> [(a, Int)] breadthFirstSearch t = go $ S.singleton (t, 0) where go to_visit = case S.viewl to_visit of S.EmptyL -> [] (LabelledTip a, !l) S.:< rest -> (a, l) : go rest (LabelledBin _ left right, !l) S.:< rest -> go (rest S.|> (left, l+1) S.|> (right, l+1)) pair :: [a] -> [(a, a)] pair [] = [] pair [x] = error "pair: odd man out" pair (a:b:rest) = (a, b) : pair rest iterateN :: Int -> (a -> a) -> (a -> a) iterateN n f = foldl (.) id $ replicate n f constructTree :: [((Int, a), Int)] -> Labelled () a constructTree = snd . pairUp . snd . foldl1 (\(old_level, acc) (new_level, new) -> (new_level, merge new $ iterateN (old_level - new_level) bin acc)) . map (\l -> (snd $ head l, map fst l)) . map (sortBy (comparing (fst.fst))) . reverse . groupBy ((==) `on` snd) . map (\((index, value), height) -> ((index, LabelledTip value), height)) where bin x = map (\((i,a), (_,b)) -> (i, LabelledBin () a b)) . pair $ x pairUp [] = error "nothing to pair" pairUp [x] = x pairUp xs = pairUp (bin xs) merge a b = sortBy (comparing fst) $ a <> b codewords :: Labelled () a -> [(a, [Bool])] codewords t = fmap (\(a, code) -> (a, reverse code)) $ go $ S.singleton (t, []) where go to_visit = case S.viewl to_visit of S.EmptyL -> [] (LabelledTip a, code) S.:< rest -> (a, code) : go rest (LabelledBin _ left right, code) S.:< rest -> go (rest S.|> (left, False:code) S.|> (right, True:code)) buildOptimizedAlphabeticalSearchTree :: forall a n. (Show a, Eq a, Show n, Ord n, Num n, Bounded n) => [(a, n)] -> Labelled () a buildOptimizedAlphabeticalSearchTree [] = error "Cannot build with empty list of elements" buildOptimizedAlphabeticalSearchTree input = go (repeat LeftBoundary) $ (<> repeat RightBoundary) $ fmap (\((a, freq), attract) -> Elem (Left (freq, LabelledTip a)) [attract]) $ zip input $ decideAttraction $ fmap snd $ input where go past [] = error $ "Internal error: empty future. Past: " <> show (takeWhile (not . isBoundary) past) go past (RightBoundary:_) = error $ "Internal error: no current. Past: " <> show (takeWhile (not . isBoundary) past) go (LeftBoundary:_) (Elem (Left (_, x)) _:RightBoundary:_) = x go (LeftBoundary:_) (Elem (Right h) _:RightBoundary:_) = fromJust $ huffmanHeapToTree h -- If the person I like likes me back, then we deal with it now. go past@(p:past1@(p2:ps)) (x:future@(next:future1@(next2:xs))) = case head $ attraction x of PreviousPrevious | NextNext `elem` attraction p2 -> combine ps (merge (contents p) (fix (contents p2) (contents x))) future Previous | Next `elem` attraction p -> combine past1 (fix (contents p) (contents x)) future Self | Elem (Right heap) _ <- x -> let heap' = case PQ.minViewWithKey heap of Just ((k, v), rest) -> case PQ.minViewWithKey rest of Just ((k2, v2), rest2) -> PQ.insert (k+k2) (LabelledBin () v v2) rest2 Nothing -> error "You shouldn't self attract if you only have one element in the heap" Nothing -> error "heap cannot be empty" in adjust past (Right heap') future Next | Previous `elem` attraction next -> combine past (fix (contents x) (contents next)) future1 NextNext | PreviousPrevious `elem` attraction next2 -> let c = merge (fix (contents x) (contents next2)) (contents next) in combine past c xs -- She loves me not _ -> go (x:past) future value (Elem (Left (freq, _)) _) = freq value (Elem (Right h) _) = heapValue h value RightBoundary = maxBound value LeftBoundary = maxBound contents (Elem x _) = x -- Guaranteed that heap is non-empty heapValue h = case PQ.minViewWithKey h of Just ((k, v), rest) -> k secondSmallestElement h = fst <$> (PQ.minViewWithKey =<< snd <$> PQ.minView h) combine past@(p:past2) x future@(f:future2) = case (isBlocked p, isBlocked f) of (False, False) -> adjust past2 (merge (contents p) $ merge x (contents f)) future2 (False, True) -> adjust past2 (merge (contents p) x) future (True, False) -> adjust past (merge x (contents f)) future2 (True, True) -> adjust past x future adjust past x future = let e = calculate past x future (a:past') = fixPast past (e:future) future' = e : fixFuture (e:past) future in go past' (a:future') fixPast rest@(LeftBoundary:_) _ = rest fixPast (Elem heap _:rest@(LeftBoundary:_)) future = calculate rest heap future : rest fixPast (e1@(Elem heap1 _):rest@(Elem heap2 _:rest2)) future = calculate rest heap1 future : calculate rest2 heap2 (e1 : future) : rest2 fixFuture _ rest@(RightBoundary:_) = rest fixFuture past (Elem heap _:rest@(RightBoundary:_)) = calculate past heap rest : rest fixFuture past (e1@(Elem heap1 _):rest@(Elem heap2 _:rest2)) = calculate past heap1 rest : calculate (e1 : past) heap2 rest2 : rest2 ff (Left x) = "Left " <> show x ff (Right x) = "Right " <> show (F.toList x) calculate (p:p2:_) heap (f:f2:_) = Elem heap $ if can_skip then best $ [(value p, Previous), (value f, Next)] ++ (if not $ isBlocked p then [(value p2, PreviousPrevious)] else []) ++ (if not $ isBlocked f then [(value f2, NextNext)] else []) else case secondSmallestValue of Just (k, _) -> best [(value p, Previous), (k, Self), (value f, Next)] Nothing -> best [(value p, Previous), (value f, Next)] where secondSmallestValue = case heap of Left _ -> Nothing Right h -> secondSmallestElement h can_skip = case heap of Left _ -> True Right _ -> False best = map snd . head . groupBy ((==) `on` fst) . sortBy (comparing fst) fix a = Right . fix' a fix' (Left (k1, v1)) (Left (k2, v2)) = PQ.singleton (k1 + k2) $ LabelledBin () v1 v2 fix' (Left (k1, v1)) (Right h) = case PQ.minViewWithKey h of Just ((k2, v2), rest) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) rest fix' (Right h) (Left (k2, v2)) = case PQ.minViewWithKey h of Just ((k1, v1), rest) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) rest fix' (Right h1) (Right h2) = case PQ.minViewWithKey h1 of Just ((k1, v1), rest) -> case PQ.minViewWithKey h2 of Just ((k2, v2), rest2) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) $ rest <> rest2 merge a b = Right $ f a <> f b where f = either (uncurry PQ.singleton) id isBlocked (Elem (Right _) _) = False isBlocked _ = True validHuTuckerTree :: (Eq a, Ord a) => Labelled () a -> Bool validHuTuckerTree t = let nodes = inOrderTraversal t in nodes == sort nodes inOrderTraversal :: Labelled () a -> [a] inOrderTraversal (LabelledTip a) = [a] inOrderTraversal (LabelledBin () l r) = inOrderTraversal l ++ inOrderTraversal r data WaveletTree f a = WaveletTree { bits :: Labelled f a , alphabet :: a -> Int -> Direction -- ^ For a given level, is the element to the right or to the left? } instance (Access Bool f, Ranked f) => F.Foldable (WaveletTree f) where foldMap f t = F.foldMap f $ map (t !) [0 .. size t - 1] -- mapBits f (WaveletTree bits alphabet) = WaveletTree (first f bits) alphabet instance (Access Bool f, Ranked f) => Access a (WaveletTree f a) where size (WaveletTree t _) = case t of LabelledTip _ -> 0 LabelledBin x _ _ -> size x (!) (WaveletTree t0 _) index0 = go t0 index0 where go t index = case t of LabelledTip a -> a LabelledBin x left right -> if x ! index then go right (rank1 x index) else go left (rank0 x index) instance (Access Bool f, Select0 f, Select1 f, Ranked f) => Dictionary a (WaveletTree f a) where rank a (WaveletTree t0 find) i0 = go 0 t0 i0 where finda = find a go level t i = case t of LabelledTip _ -> i LabelledBin x left right -> case finda level of L -> go (level+1) left (rank0 x i) R -> go (level+1) right (rank1 x i) select a (WaveletTree t0 find) i0 = findPath 0 t0 i0 where finda = find a findPath level t = case t of LabelledTip _ -> id LabelledBin x left right -> case finda level of L -> (select0 x) . findPath (level+1) left R -> (select1 x) . findPath (level+1) right -- $intro -- >>> :{ -- let abracadabraFind 'a' = const False -- abracadabraFind 'b' = odd -- abracadabraFind 'c' = (> 0) -- abracadabraFind 'd' = even -- abracadabraFind 'r' = const True -- :} -- -- >>> :{ -- let bin = LabelledBin () -- tip = LabelledTip -- abracadabraEncoding = -- bin (bin (tip 'a') (bin (tip 'b') (tip 'c'))) (bin (tip 'd') (tip 'r')) -- :} -- -- >>> :{ -- let (t, f) = (True, False) -- tree = LabelledBin (build [f, f, t, f, f, f, t, f, f, t, f]) -- -- a & (b & c) -- (LabelledBin (build [f, t, f, t, f, f, t, f]) (LabelledTip 'a') -- -- b & c -- (LabelledBin (build [f, t, f]) (LabelledTip 'b') (LabelledTip 'c'))) -- -- d & r -- (LabelledBin (build [t, f, t]) (LabelledTip 'd') (LabelledTip 'r')) -- exampleWaveletTree :: WaveletTree Rank9 Char -- exampleWaveletTree = WaveletTree tree abracadabraFind -- :} -- -- Inefficient foldable -- -- >>> F.toList exampleWaveletTree -- "abracadabra" -- -- >>> [(c, map (select c exampleWaveletTree) [1.. rank c exampleWaveletTree (size exampleWaveletTree)]) | c <- "abcdr"] -- [('a',[1,4,6,8,11]),('b',[2,9]),('c',[5]),('d',[7]),('r',[3,10])] -- -- >>> [(c, map (rank c exampleWaveletTree) [0.. size exampleWaveletTree]) | c <- "abcdr"] -- [('a',[0,1,1,1,2,2,3,3,4,4,4,5]),('b',[0,0,1,1,1,1,1,1,1,2,2,2]),('c',[0,0,0,0,0,1,1,1,1,1,1,1]),('d',[0,0,0,0,0,0,0,1,1,1,1,1]),('r',[0,0,0,1,1,1,1,1,1,1,2,2])] asListOfNumbers :: Access Bool t => t -> [Int] asListOfNumbers t = concat [ [x | t ! x] | x <- [0 .. size t - 1] ] buildWithEncoding :: forall a f. Buildable Bool f => Encoding a -> (a -> Int -> Direction) -> Builder a (Labelled f a) buildWithEncoding (Encoding e) f = Builder $ case builder :: Builder Bool f of Builder (Building stop' step' start') -> Building stop step start where start = bifor e (const start') pure stop x = bifor x stop' pure step x0 c0 = walk c0 0 x0 where walk _ _ a@(LabelledTip{}) = pure a walk c !l (LabelledBin v a b) = let dir = f c l q = LabelledBin <$> step' v (directionToBool dir) in case dir of L -> q <*> walk c (l+1) a <*> pure b R -> q <*> pure a <*> walk c (l+1) b decidingFunction :: Eq a => Encoding a -> (a -> Int -> Direction) decidingFunction (Encoding enc0) = \c -> let Just t = fmap reverse $ go enc0 c [] in (t !!) where go (LabelledTip c') c visited = do guard $ c == c' return $ visited go (LabelledBin _ l _) c visited | Just x <- go l c (L:visited ) = Just x go (LabelledBin _ _ r) c visited | Just x <- go r c (R:visited ) = Just x go _ _ _ = Nothing instance (Ord a, Buildable Bool f) => Buildable a (WaveletTree f a) where builder = runNonStreaming $ do enc <- NonStreaming $ buildHuffmanEncoding let fun = decidingFunction enc NonStreaming $ WaveletTree <$> buildWithEncoding enc fun <*> pure fun
Gabriel439/succinct
src/Succinct/Sequence.hs
bsd-2-clause
19,162
0
24
5,073
6,196
3,268
2,928
274
33
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} -- | Run sub-processes. module System.Process.Run (runCmd ,runCmd' ,callProcess ,callProcess' ,callProcessInheritStderrStdout ,createProcess' ,ProcessExitedUnsuccessfully ,Cmd(..) ) where import Control.Exception.Lifted import Control.Monad (liftM) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger (MonadLogger, logError) import Control.Monad.Trans.Control (MonadBaseControl) import Data.Conduit.Process hiding (callProcess) import Data.Foldable (forM_) import Data.Text (Text) import qualified Data.Text as T import Path (Dir, Abs, Path) import Path (toFilePath) import Prelude -- Fix AMP warning import System.Exit (exitWith, ExitCode (..)) import System.IO import qualified System.Process import System.Process.Log import System.Process.Read -- | Cmd holds common infos needed to running a process in most cases data Cmd = Cmd { cmdDirectoryToRunIn :: Maybe (Path Abs Dir) -- ^ directory to run in , cmdCommandToRun :: FilePath -- ^ command to run , cmdEnvOverride :: EnvOverride , cmdCommandLineArguments :: [String] -- ^ command line arguments } -- | Run the given command in the given directory, inheriting stdout and stderr. -- -- If it exits with anything but success, prints an error -- and then calls 'exitWith' to exit the program. runCmd :: forall (m :: * -> *). (MonadLogger m,MonadIO m,MonadBaseControl IO m) => Cmd -> Maybe Text -- ^ optional additional error message -> m () runCmd = runCmd' id runCmd' :: forall (m :: * -> *). (MonadLogger m,MonadIO m,MonadBaseControl IO m) => (CreateProcess -> CreateProcess) -> Cmd -> Maybe Text -- ^ optional additional error message -> m () runCmd' modCP cmd@(Cmd{..}) mbErrMsg = do result <- try (callProcess' modCP cmd) case result of Left (ProcessExitedUnsuccessfully _ ec) -> do $logError $ T.pack $ concat $ [ "Exit code " , show ec , " while running " , show (cmdCommandToRun : cmdCommandLineArguments) ] ++ (case cmdDirectoryToRunIn of Nothing -> [] Just mbDir -> [" in ", toFilePath mbDir] ) forM_ mbErrMsg $logError liftIO (exitWith ec) Right () -> return () -- | Like 'System.Process.callProcess', but takes an optional working directory and -- environment override, and throws 'ProcessExitedUnsuccessfully' if the -- process exits unsuccessfully. -- -- Inherits stdout and stderr. callProcess :: (MonadIO m, MonadLogger m) => Cmd -> m () callProcess = callProcess' id -- | Like 'System.Process.callProcess', but takes an optional working directory and -- environment override, and throws 'ProcessExitedUnsuccessfully' if the -- process exits unsuccessfully. -- -- Inherits stdout and stderr. callProcess' :: (MonadIO m, MonadLogger m) => (CreateProcess -> CreateProcess) -> Cmd -> m () callProcess' modCP cmd = do c <- liftM modCP (cmdToCreateProcess cmd) $logCreateProcess c liftIO $ do (_, _, _, p) <- System.Process.createProcess c exit_code <- waitForProcess p case exit_code of ExitSuccess -> return () ExitFailure _ -> throwIO (ProcessExitedUnsuccessfully c exit_code) callProcessInheritStderrStdout :: (MonadIO m, MonadLogger m) => Cmd -> m () callProcessInheritStderrStdout cmd = do let inheritOutput cp = cp { std_in = CreatePipe, std_out = Inherit, std_err = Inherit } callProcess' inheritOutput cmd -- | Like 'System.Process.Internal.createProcess_', but taking a 'Cmd'. -- Note that the 'Handle's provided by 'UseHandle' are not closed -- automatically. createProcess' :: (MonadIO m, MonadLogger m) => String -> (CreateProcess -> CreateProcess) -> Cmd -> m (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) createProcess' tag modCP cmd = do c <- liftM modCP (cmdToCreateProcess cmd) $logCreateProcess c liftIO $ System.Process.createProcess_ tag c cmdToCreateProcess :: MonadIO m => Cmd -> m CreateProcess cmdToCreateProcess (Cmd wd cmd0 menv args) = do cmd <- preProcess wd menv cmd0 return $ (proc cmd args) { delegate_ctlc = True , cwd = fmap toFilePath wd , env = envHelper menv }
Heather/stack
src/System/Process/Run.hs
bsd-3-clause
4,928
0
18
1,369
1,079
588
491
100
3
{-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Choose.ST -- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu> -- License : BSD3 -- Maintainer : Patrick Perry <patperry@stanford.edu> -- Stability : experimental -- -- Mutable combinations in the 'ST' monad. module Data.Choose.ST ( -- * Combinations STChoose, runSTChoose, -- * Overloaded mutable combination interface module Data.Choose.MChoose ) where import Control.Monad.ST import Data.Choose.Base( Choose, STChoose, unsafeFreezeSTChoose ) import Data.Choose.MChoose -- | A safe way to create and work with a mutable combination before returning -- an immutable one for later perusal. This function avoids copying the -- combination before returning it - it uses unsafeFreeze internally, but this -- wrapper is a safe interface to that function. runSTChoose :: (forall s. ST s (STChoose s)) -> Choose runSTChoose c = runST (c >>= unsafeFreezeSTChoose) {-# INLINE runSTChoose #-}
patperry/permutation
lib/Data/Choose/ST.hs
bsd-3-clause
1,074
0
10
185
114
75
39
11
1
{-# LANGUAGE CPP #-} module Main where import Prelude hiding ( catch ) import Test.HUnit import System.Exit import System.Process ( system ) import System.IO ( stderr ) import qualified DependencyTest import qualified MigrationsTest import qualified FilesystemSerializeTest import qualified FilesystemParseTest import qualified FilesystemTest import qualified CycleDetectionTest import qualified StoreTest import Control.Monad ( forM ) import Control.Exception ( finally, catch, SomeException ) import Database.HDBC ( IConnection(disconnect) ) #ifndef WithoutBackendDependencies import qualified BackendTest import Database.HDBC.Sqlite3 ( connectSqlite3 ) import qualified Database.HDBC.PostgreSQL as PostgreSQL doBackendTests :: IO [Test] doBackendTests = do sqliteConn <- connectSqlite3 ":memory:" pgConn <- setupPostgresDb let backends = [ ("Sqlite", (BackendTest.tests sqliteConn) `finally` (disconnect sqliteConn)) , ("PostgreSQL", (BackendTest.tests pgConn) `finally` (disconnect pgConn >> teardownPostgresDb)) ] backendTests <- forM backends $ \(name, testAct) -> do return $ (name ++ " backend tests") ~: test testAct setupPostgresDb :: IO PostgreSQL.Connection setupPostgresDb = do teardownPostgresDb `catch` ignoreException -- create database status <- system $ "createdb " ++ tempPgDatabase case status of ExitSuccess -> return () ExitFailure _ -> error $ "Failed to create PostgreSQL database " ++ (show tempPgDatabase) -- return test db connection PostgreSQL.connectPostgreSQL $ "dbname=" ++ tempPgDatabase teardownPostgresDb :: IO () teardownPostgresDb = do -- create database status <- system $ "dropdb " ++ tempPgDatabase ++ " 2>/dev/null" case status of ExitSuccess -> return () ExitFailure _ -> error $ "Failed to drop PostgreSQL database " ++ (show tempPgDatabase) #else doBackendTests :: IO [Test] doBackendTests = return [] #endif loadTests :: IO [Test] loadTests = do backendTests <- doBackendTests ioTests <- sequence [ do fspTests <- FilesystemParseTest.tests return $ "Filesystem Parsing" ~: test fspTests , do fsTests <- FilesystemTest.tests return $ "Filesystem general" ~: test fsTests ] return $ concat [ backendTests , ioTests , DependencyTest.tests , FilesystemSerializeTest.tests , MigrationsTest.tests , CycleDetectionTest.tests , StoreTest.tests ] tempPgDatabase :: String tempPgDatabase = "dbmigrations_test" ignoreException :: SomeException -> IO () ignoreException _ = return () main :: IO () main = do tests <- loadTests (testResults, _) <- runTestText (putTextToHandle stderr False) $ test tests if errors testResults + failures testResults > 0 then exitFailure else exitSuccess
nick0x01/dbmigrations
test/TestDriver.hs
bsd-3-clause
3,047
0
15
771
701
377
324
-1
-1
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Graph.MST.Config where import Autolib.ToDoc import Autolib.Reader import Data.Typeable data Config = Config { nodes :: Int , edges :: Int , weight_bounds :: (Int,Int) } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''Config]) rc :: Config rc = Config { nodes = 15 , edges = 30 , weight_bounds = ( 1, 100 ) }
Erdwolf/autotool-bonn
src/Graph/MST/Config.hs
gpl-2.0
450
12
14
132
121
74
47
15
1
module Graphics.UI.Gtk.Layout.EitherWidget where import Control.Monad import Data.IORef import Graphics.UI.Gtk import System.Glib.Types data EitherWidget a b = EitherWidget Notebook (IORef EitherWidgetParams) type EitherWidgetParams = Bool instance WidgetClass (EitherWidget a b) instance ObjectClass (EitherWidget a b) instance GObjectClass (EitherWidget a b) where toGObject (EitherWidget nb _) = toGObject nb unsafeCastGObject o = EitherWidget (unsafeCastGObject o) undefined eitherWidgetNew :: (WidgetClass a, WidgetClass b) => a -> b -> IO (EitherWidget a b) eitherWidgetNew wL wR = do nb <- notebookNew _ <- notebookAppendPage nb wL "" _ <- notebookAppendPage nb wR "" notebookSetShowTabs nb False params <- newIORef True return $ EitherWidget nb params eitherWidgetLeftActivated :: Attr (EitherWidget a b) Bool eitherWidgetLeftActivated = newAttr getter setter where getter (EitherWidget _ paramsR) = readIORef paramsR setter (EitherWidget nb paramsR) v = do params <- readIORef paramsR when (v /= params) $ do let upd = if v then 0 else 1 notebookSetCurrentPage nb upd writeIORef paramsR v eitherWidgetRightActivated :: Attr (EitherWidget a b) Bool eitherWidgetRightActivated = newAttr getter setter where getter w = fmap not $ get w eitherWidgetLeftActivated setter w v = set w [ eitherWidgetLeftActivated := not v ] eitherWidgetToggle :: EitherWidget a b -> IO() eitherWidgetToggle w = set w [ eitherWidgetLeftActivated :~ not ]
keera-studios/gtk-helpers
gtk3/src/Graphics/UI/Gtk/Layout/EitherWidget.hs
bsd-3-clause
1,612
0
15
377
495
243
252
34
2
module E.Binary() where import Data.Binary import E.Type import FrontEnd.HsSyn() import Name.Binary() import Support.MapBinaryInstance import {-# SOURCE #-} Info.Binary(putInfo,getInfo) instance Binary TVr where put TVr { tvrIdent = eid, tvrType = e, tvrInfo = nf} = do put eid put e putInfo nf get = do x <- get e <- get nf <- getInfo return $ TVr x e nf instance Data.Binary.Binary RuleType where put RuleSpecialization = do Data.Binary.putWord8 0 put RuleUser = do Data.Binary.putWord8 1 put RuleCatalyst = do Data.Binary.putWord8 2 get = do h <- Data.Binary.getWord8 case h of 0 -> do return RuleSpecialization 1 -> do return RuleUser 2 -> do return RuleCatalyst _ -> fail "invalid binary data found" instance Data.Binary.Binary Rule where put (Rule aa ab ac ad ae af ag ah) = do Data.Binary.put aa putList ab putList ac putLEB128 $ fromIntegral ad Data.Binary.put ae Data.Binary.put af Data.Binary.put ag Data.Binary.put ah get = do aa <- get ab <- getList ac <- getList ad <- fromIntegral `fmap` getLEB128 ae <- get af <- get ag <- get ah <- get return (Rule aa ab ac ad ae af ag ah) instance Data.Binary.Binary ARules where put (ARules aa ab) = do Data.Binary.put aa putList ab get = do aa <- get ab <- getList return (ARules aa ab) instance (Data.Binary.Binary e, Data.Binary.Binary t) => Data.Binary.Binary (Lit e t) where put (LitInt aa ab) = do Data.Binary.putWord8 0 Data.Binary.put aa Data.Binary.put ab put (LitCons ac ad ae af) = do Data.Binary.putWord8 1 Data.Binary.put ac putList ad Data.Binary.put ae Data.Binary.put af get = do h <- Data.Binary.getWord8 case h of 0 -> do aa <- Data.Binary.get ab <- Data.Binary.get return (LitInt aa ab) 1 -> do ac <- Data.Binary.get ad <- getList ae <- Data.Binary.get af <- Data.Binary.get return (LitCons ac ad ae af) _ -> fail "invalid binary data found" instance Data.Binary.Binary ESort where put EStar = do Data.Binary.putWord8 0 put EBang = do Data.Binary.putWord8 1 put EHash = do Data.Binary.putWord8 2 put ETuple = do Data.Binary.putWord8 3 put EHashHash = do Data.Binary.putWord8 4 put EStarStar = do Data.Binary.putWord8 5 put (ESortNamed aa) = do Data.Binary.putWord8 6 Data.Binary.put aa get = do h <- Data.Binary.getWord8 case h of 0 -> do return EStar 1 -> do return EBang 2 -> do return EHash 3 -> do return ETuple 4 -> do return EHashHash 5 -> do return EStarStar 6 -> do aa <- Data.Binary.get return (ESortNamed aa) _ -> fail "invalid binary data found" instance Data.Binary.Binary E where put (EAp aa ab) = do Data.Binary.putWord8 0 Data.Binary.put aa Data.Binary.put ab put (ELam ac ad) = do Data.Binary.putWord8 1 Data.Binary.put ac Data.Binary.put ad put (EPi ae af) = do Data.Binary.putWord8 2 Data.Binary.put ae Data.Binary.put af put (EVar ag) = do Data.Binary.putWord8 3 Data.Binary.put ag put Unknown = do Data.Binary.putWord8 4 put (ESort ah) = do Data.Binary.putWord8 5 Data.Binary.put ah put (ELit ai) = do Data.Binary.putWord8 6 Data.Binary.put ai put (ELetRec aj ak) = do Data.Binary.putWord8 7 putList aj Data.Binary.put ak put (EPrim al am an) = do Data.Binary.putWord8 8 Data.Binary.put al Data.Binary.put am Data.Binary.put an put (EError ao ap) = do Data.Binary.putWord8 9 Data.Binary.put ao Data.Binary.put ap put (ECase aq ar as at au av) = do Data.Binary.putWord8 10 Data.Binary.put aq Data.Binary.put ar Data.Binary.put as putList at Data.Binary.put au Data.Binary.put av get = do h <- Data.Binary.getWord8 case h of 0 -> do aa <- Data.Binary.get ab <- Data.Binary.get return (EAp aa ab) 1 -> do ac <- Data.Binary.get ad <- Data.Binary.get return (ELam ac ad) 2 -> do ae <- Data.Binary.get af <- Data.Binary.get return (EPi ae af) 3 -> do ag <- Data.Binary.get return (EVar ag) 4 -> do return Unknown 5 -> do ah <- Data.Binary.get return (ESort ah) 6 -> do ai <- Data.Binary.get return (ELit ai) 7 -> do aj <- getList ak <- Data.Binary.get return (ELetRec aj ak) 8 -> do al <- Data.Binary.get am <- Data.Binary.get an <- Data.Binary.get return (EPrim al am an) 9 -> do ao <- Data.Binary.get ap <- Data.Binary.get return (EError ao ap) 10 -> do aq <- Data.Binary.get ar <- Data.Binary.get as <- Data.Binary.get at <- getList au <- Data.Binary.get av <- Data.Binary.get return (ECase aq ar as at au av) _ -> fail "invalid binary data found" instance (Data.Binary.Binary e) => Data.Binary.Binary (Alt e) where put (Alt aa ab) = do Data.Binary.put aa Data.Binary.put ab get = do aa <- get ab <- get return (Alt aa ab)
m-alvarez/jhc
src/E/Binary.hs
mit
5,542
58
44
1,865
2,102
1,018
1,084
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hu-HU"> <title>Directory List v2.3</title> <maps> <homeID>directorylistv2_3</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/directorylistv2_3/src/main/javahelp/help_hu_HU/helpset_hu_HU.hs
apache-2.0
978
78
66
157
412
209
203
-1
-1
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} ---------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.NoFrillsDecoration -- Copyright : (c) Jan Vornberger 2009 -- License : BSD3-style (see LICENSE) -- -- Maintainer : jan.vornberger@informatik.uni-oldenburg.de -- Stability : unstable -- Portability : not portable -- -- Most basic version of decoration for windows without any additional -- modifications. In contrast to "XMonad.Layout.SimpleDecoration" this will -- result in title bars that span the entire window instead of being only the -- length of the window title. -- ----------------------------------------------------------------------------- module XMonad.Layout.NoFrillsDecoration ( -- * Usage: -- $usage noFrillsDeco , module XMonad.Layout.SimpleDecoration , NoFrillsDecoration ) where import XMonad.Layout.Decoration import XMonad.Layout.SimpleDecoration -- $usage -- You can use this module with the following in your -- @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.NoFrillsDecoration -- -- Then edit your @layoutHook@ by adding the NoFrillsDecoration to -- your layout: -- -- > myL = noFrillsDeco shrinkText def (layoutHook def) -- > main = xmonad def { layoutHook = myL } -- -- | Add very simple decorations to windows of a layout. noFrillsDeco :: (Eq a, Shrinker s) => s -> Theme -> l a -> ModifiedLayout (Decoration NoFrillsDecoration s) l a noFrillsDeco s c = decoration s c $ NFD True data NoFrillsDecoration a = NFD Bool deriving (Show, Read) instance Eq a => DecorationStyle NoFrillsDecoration a where describeDeco _ = "NoFrillsDeco"
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Layout/NoFrillsDecoration.hs
bsd-2-clause
1,703
0
11
292
184
114
70
14
1
{-# LANGUAGE TypeFamilies, TypeSynonymInstances, FlexibleContexts, FlexibleInstances, ScopedTypeVariables, Arrows, GeneralizedNewtypeDeriving, PatternSynonyms #-} module Graphics.GPipe.Internal.PrimitiveStream where import Control.Monad.Trans.Class import Control.Monad.Trans.Writer.Lazy import Control.Monad.Trans.State.Lazy import Prelude hiding (length, id, (.)) import Graphics.GPipe.Internal.Buffer import Graphics.GPipe.Internal.Expr import Graphics.GPipe.Internal.Shader import Graphics.GPipe.Internal.Compiler import Graphics.GPipe.Internal.PrimitiveArray import Graphics.GPipe.Internal.Context import Control.Category import Control.Arrow import Data.Monoid (Monoid(..)) import Data.IntMap.Lazy (insert) import Data.Word import Data.Int import Graphics.GL.Core33 import Foreign.Marshal.Utils import Foreign.Ptr (intPtrToPtr) import Data.IORef import Linear.V4 import Linear.V3 import Linear.V2 import Linear.V1 import Linear.V0 import Linear.Plucker (Plucker(..)) import Linear.Quaternion (Quaternion(..)) import Linear.Affine (Point(..)) import Data.Maybe (fromMaybe) type DrawCallName = Int data PrimitiveStreamData = PrimitiveStreamData DrawCallName -- | A @'PrimitiveStream' t a @ is a stream of primitives of type @t@ where the vertices are values of type @a@. You -- can operate a stream's vertex values using the 'Functor' instance (this will result in a shader running on the GPU). -- You may also append 'PrimitiveStream's using the 'Monoid' instance, but if possible append the origin 'PrimitiveArray's instead, as this will create more optimized -- draw calls. newtype PrimitiveStream t a = PrimitiveStream [(a, (Maybe PointSize, PrimitiveStreamData))] deriving Monoid instance Functor (PrimitiveStream t) where fmap f (PrimitiveStream xs) = PrimitiveStream $ map (first f) xs -- | This class constraints which buffer types can be turned into vertex values, and what type those values have. class BufferFormat a => VertexInput a where -- | The type the buffer value will be turned into once it becomes a vertex value. type VertexFormat a -- | An arrow action that turns a value from it's buffer representation to it's vertex representation. Use 'toVertex' from -- the GPipe provided instances to operate in this arrow. Also note that this arrow needs to be able to return a value -- lazily, so ensure you use -- -- @proc ~pattern -> do ...@. toVertex :: ToVertex a (VertexFormat a) -- | The arrow type for 'toVertex'. newtype ToVertex a b = ToVertex (Kleisli (StateT Int (Writer [Binding -> (IO VAOKey, IO ())])) a b) deriving (Category, Arrow) -- | Create a primitive stream from a primitive array provided from the shader environment. toPrimitiveStream :: forall os f s a p. VertexInput a => (s -> PrimitiveArray p a) -> Shader os f s (PrimitiveStream p (VertexFormat a)) toPrimitiveStream sf = Shader $ do n <- getName uniAl <- askUniformAlignment let sampleBuffer = makeBuffer undefined undefined uniAl :: Buffer os a x = fst $ runWriter (evalStateT (mf $ bufBElement sampleBuffer $ BInput 0 0) 0) doForInputArray n (map drawcall . getPrimitiveArray . sf) return $ PrimitiveStream [(x, (Nothing, PrimitiveStreamData n))] where ToVertex (Kleisli mf) = toVertex :: ToVertex a (VertexFormat a) drawcall (PrimitiveArraySimple p l a) binds = (attribs a binds, glDrawArrays (toGLtopology p) 0 (fromIntegral l)) drawcall (PrimitiveArrayIndexed p i a) binds = (attribs a binds, do bindIndexBuffer i glDrawElements (toGLtopology p) (fromIntegral $ indexArrayLength i) (indexType i) (intPtrToPtr $ fromIntegral $ offset i * glSizeOf (indexType i))) drawcall (PrimitiveArrayInstanced p il l a) binds = (attribs a binds, glDrawArraysInstanced (toGLtopology p) 0 (fromIntegral l) (fromIntegral il)) drawcall (PrimitiveArrayIndexedInstanced p i il a) binds = (attribs a binds, do bindIndexBuffer i glDrawElementsInstanced (toGLtopology p) (fromIntegral $ indexArrayLength i) (indexType i) (intPtrToPtr $ fromIntegral $ offset i * glSizeOf (indexType i)) (fromIntegral il)) bindIndexBuffer i = do case restart i of Just x -> do glEnable GL_PRIMITIVE_RESTART glPrimitiveRestartIndex (fromIntegral x) Nothing -> glDisable GL_PRIMITIVE_RESTART bname <- readIORef (iArrName i) glBindBuffer GL_ELEMENT_ARRAY_BUFFER bname glSizeOf GL_UNSIGNED_INT = 4 glSizeOf GL_UNSIGNED_SHORT = 2 glSizeOf GL_UNSIGNED_BYTE = 1 glSizeOf _ = error "toPrimitiveStream: Unknown indexArray type" assignIxs :: Int -> Binding -> [Int] -> [Binding -> (IO VAOKey, IO ())] -> [(IO VAOKey, IO ())] assignIxs n ix xxs@(x:xs) (f:fs) | x == n = f ix : assignIxs (n+1) (ix+1) xs fs | otherwise = assignIxs (n+1) ix xxs fs assignIxs _ _ [] _ = [] assignIxs _ _ _ _ = error "Too few attributes generated in toPrimitiveStream" attribs a binds = first sequence $ second sequence_ $ unzip $ assignIxs 0 0 binds $ execWriter (runStateT (mf a) 0) doForInputArray :: Int -> (s -> [[Binding] -> ((IO [VAOKey], IO ()), IO ())]) -> ShaderM s () doForInputArray n io = modifyRenderIO (\s -> s { inputArrayToRenderIOs = insert n io (inputArrayToRenderIOs s) } ) data InputIndices = InputIndices { inputVertexID :: VInt, inputInstanceID :: VInt } -- | Like 'fmap', but where the vertex and instance IDs are provided as arguments as well. withInputIndices :: (a -> InputIndices -> b) -> PrimitiveStream p a -> PrimitiveStream p b withInputIndices f = fmap (\a -> f a (InputIndices (scalarS' "gl_VertexID") (scalarS' "gl_InstanceID"))) type PointSize = VFloat -- | Like 'fmap', but where each point's size is provided as arguments as well, and a new point size is set for each point in addition to the new vertex value. -- -- When a 'PrimitiveStream' of 'Points' is created, all points will have the default size of 1. withPointSize :: (a -> PointSize -> (b, PointSize)) -> PrimitiveStream Points a -> PrimitiveStream Points b withPointSize f (PrimitiveStream xs) = PrimitiveStream $ map (\(a, (ps, d)) -> let (b, ps') = f a (fromMaybe (scalarS' "1") ps) in (b, (Just ps', d))) xs makeVertexFx norm x f styp typ b = do n <- get put $ n + 1 let combOffset = bStride b * bSkipElems b + bOffset b lift $ tell [\ix -> ( do bn <- readIORef $ bName b return $ VAOKey bn combOffset x norm (bInstanceDiv b) , do bn <- readIORef $ bName b let ix' = fromIntegral ix glEnableVertexAttribArray ix' glBindBuffer GL_ARRAY_BUFFER bn glVertexAttribDivisor ix' (fromIntegral $ bInstanceDiv b) glVertexAttribPointer ix' x typ (fromBool norm) (fromIntegral $ bStride b) (intPtrToPtr $ fromIntegral combOffset))] return (f styp $ useVInput styp n) makeVertexFnorm = makeVertexFx True makeVertexF = makeVertexFx False makeVertexI x f styp typ b = do n <- get put $ n + 1 let combOffset = bStride b * bSkipElems b + bOffset b lift $ tell [\ix -> ( do bn <- readIORef $ bName b return $ VAOKey bn combOffset x False (bInstanceDiv b) , do bn <- readIORef $ bName b let ix' = fromIntegral ix glEnableVertexAttribArray ix' glBindBuffer GL_ARRAY_BUFFER bn glVertexAttribDivisor ix' (fromIntegral $ bInstanceDiv b) glVertexAttribIPointer ix' x typ (fromIntegral $ bStride b) (intPtrToPtr $ fromIntegral combOffset))] return (f styp $ useVInput styp n) -- scalars unBnorm :: Normalized t -> t unBnorm (Normalized a) = a instance VertexInput (B Float) where type VertexFormat (B Float) = VFloat toVertex = ToVertex $ Kleisli $ makeVertexF 1 (const S) STypeFloat GL_FLOAT instance VertexInput (Normalized (B Int32)) where type VertexFormat (Normalized (B Int32)) = VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 1 (const S) STypeFloat GL_INT . unBnorm instance VertexInput (Normalized (B Word32)) where type VertexFormat (Normalized (B Word32)) = VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 1 (const S) STypeFloat GL_UNSIGNED_INT . unBnorm instance VertexInput (B Int32) where type VertexFormat (B Int32) = VInt toVertex = ToVertex $ Kleisli $ makeVertexI 1 (const S) STypeInt GL_INT instance VertexInput (B Word32) where type VertexFormat (B Word32) = VWord toVertex = ToVertex $ Kleisli $ makeVertexI 1 (const S) STypeUInt GL_UNSIGNED_INT -- B2 instance VertexInput (B2 Float) where type VertexFormat (B2 Float) = V2 VFloat toVertex = ToVertex $ Kleisli $ makeVertexF 2 vec2S (STypeVec 2) GL_FLOAT . unB2 instance VertexInput (Normalized (B2 Int32)) where type VertexFormat (Normalized (B2 Int32)) = V2 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_INT . unB2 . unBnorm instance VertexInput (Normalized (B2 Int16)) where type VertexFormat (Normalized (B2 Int16)) = V2 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_SHORT . unB2 . unBnorm instance VertexInput (Normalized (B2 Word32)) where type VertexFormat (Normalized (B2 Word32)) = V2 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_UNSIGNED_INT . unB2 . unBnorm instance VertexInput (Normalized (B2 Word16)) where type VertexFormat (Normalized (B2 Word16)) = V2 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_UNSIGNED_SHORT . unB2 . unBnorm instance VertexInput (B2 Int32) where type VertexFormat (B2 Int32) = V2 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeIVec 2) GL_INT . unB2 instance VertexInput (B2 Int16) where type VertexFormat (B2 Int16) = V2 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeIVec 2) GL_SHORT . unB2 instance VertexInput (B2 Word32) where type VertexFormat (B2 Word32) = V2 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeUVec 2) GL_UNSIGNED_INT . unB2 instance VertexInput (B2 Word16) where type VertexFormat (B2 Word16) = V2 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeUVec 2) GL_UNSIGNED_SHORT . unB2 -- B3 instance VertexInput (B3 Float) where type VertexFormat (B3 Float) = V3 VFloat toVertex = ToVertex $ Kleisli $ makeVertexF 3 vec3S (STypeVec 3) GL_FLOAT . unB3 instance VertexInput (Normalized (B3 Int32)) where type VertexFormat (Normalized (B3 Int32)) = V3 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_INT . unB3 . unBnorm instance VertexInput (Normalized (B3 Int16)) where type VertexFormat (Normalized (B3 Int16)) = V3 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_SHORT . unB3 . unBnorm instance VertexInput (Normalized (B3 Int8)) where type VertexFormat (Normalized (B3 Int8)) = V3 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_BYTE . unB3 . unBnorm instance VertexInput (Normalized (B3 Word32)) where type VertexFormat (Normalized (B3 Word32)) = V3 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_UNSIGNED_INT . unB3 . unBnorm instance VertexInput (Normalized (B3 Word16)) where type VertexFormat (Normalized (B3 Word16)) = V3 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_UNSIGNED_SHORT . unB3 . unBnorm instance VertexInput (Normalized (B3 Word8)) where type VertexFormat (Normalized (B3 Word8)) = V3 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_UNSIGNED_BYTE . unB3 . unBnorm instance VertexInput (B3 Int32) where type VertexFormat (B3 Int32) = V3 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeIVec 3) GL_INT . unB3 instance VertexInput (B3 Int16) where type VertexFormat (B3 Int16) = V3 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeIVec 3) GL_SHORT . unB3 instance VertexInput (B3 Int8) where type VertexFormat (B3 Int8) = V3 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeIVec 3) GL_BYTE . unB3 instance VertexInput (B3 Word32) where type VertexFormat (B3 Word32) = V3 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeUVec 3) GL_UNSIGNED_INT . unB3 instance VertexInput (B3 Word16) where type VertexFormat (B3 Word16) = V3 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeUVec 3) GL_UNSIGNED_SHORT . unB3 instance VertexInput (B3 Word8) where type VertexFormat (B3 Word8) = V3 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeUVec 3) GL_UNSIGNED_BYTE . unB3 -- B4 instance VertexInput (B4 Float) where type VertexFormat (B4 Float) = V4 VFloat toVertex = ToVertex $ Kleisli $ makeVertexF 4 vec4S (STypeVec 4) GL_FLOAT . unB4 instance VertexInput (Normalized (B4 Int32)) where type VertexFormat (Normalized (B4 Int32)) = V4 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_INT . unB4 . unBnorm instance VertexInput (Normalized (B4 Int16)) where type VertexFormat (Normalized (B4 Int16)) = V4 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_SHORT . unB4 . unBnorm instance VertexInput (Normalized (B4 Int8)) where type VertexFormat (Normalized (B4 Int8)) = V4 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_BYTE . unB4 . unBnorm instance VertexInput (Normalized (B4 Word32)) where type VertexFormat (Normalized (B4 Word32)) = V4 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_UNSIGNED_INT . unB4 . unBnorm instance VertexInput (Normalized (B4 Word16)) where type VertexFormat (Normalized (B4 Word16)) = V4 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_UNSIGNED_SHORT . unB4 . unBnorm instance VertexInput (Normalized (B4 Word8)) where type VertexFormat (Normalized (B4 Word8)) = V4 VFloat toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_UNSIGNED_BYTE . unB4 . unBnorm instance VertexInput (B4 Int32) where type VertexFormat (B4 Int32) = V4 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeIVec 4) GL_INT . unB4 instance VertexInput (B4 Int16) where type VertexFormat (B4 Int16) = V4 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeIVec 4) GL_SHORT . unB4 instance VertexInput (B4 Int8) where type VertexFormat (B4 Int8) = V4 VInt toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeIVec 4) GL_BYTE . unB4 instance VertexInput (B4 Word32) where type VertexFormat (B4 Word32) = V4 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeUVec 4) GL_UNSIGNED_INT . unB4 instance VertexInput (B4 Word16) where type VertexFormat (B4 Word16) = V4 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeUVec 4) GL_UNSIGNED_SHORT . unB4 instance VertexInput (B4 Word8) where type VertexFormat (B4 Word8) = V4 VWord toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeUVec 4) GL_UNSIGNED_BYTE . unB4 instance VertexInput () where type VertexFormat () = () toVertex = arr (const ()) instance (VertexInput a, VertexInput b) => VertexInput (a,b) where type VertexFormat (a,b) = (VertexFormat a, VertexFormat b) toVertex = proc ~(a,b) -> do a' <- toVertex -< a b' <- toVertex -< b returnA -< (a', b') instance (VertexInput a, VertexInput b, VertexInput c) => VertexInput (a,b,c) where type VertexFormat (a,b,c) = (VertexFormat a, VertexFormat b, VertexFormat c) toVertex = proc ~(a,b,c) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c returnA -< (a', b', c') instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d) => VertexInput (a,b,c,d) where type VertexFormat (a,b,c,d) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d) toVertex = proc ~(a,b,c,d) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c d' <- toVertex -< d returnA -< (a', b', c', d') instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d, VertexInput e) => VertexInput (a,b,c,d,e) where type VertexFormat (a,b,c,d,e) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d, VertexFormat e) toVertex = proc ~(a,b,c,d,e) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c d' <- toVertex -< d e' <- toVertex -< e returnA -< (a', b', c', d', e') instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d, VertexInput e, VertexInput f) => VertexInput (a,b,c,d,e,f) where type VertexFormat (a,b,c,d,e,f) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d, VertexFormat e, VertexFormat f) toVertex = proc ~(a,b,c,d,e,f) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c d' <- toVertex -< d e' <- toVertex -< e f' <- toVertex -< f returnA -< (a', b', c', d', e', f') instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d, VertexInput e, VertexInput f, VertexInput g) => VertexInput (a,b,c,d,e,f,g) where type VertexFormat (a,b,c,d,e,f,g) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d, VertexFormat e, VertexFormat f, VertexFormat g) toVertex = proc ~(a,b,c,d,e,f,g) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c d' <- toVertex -< d e' <- toVertex -< e f' <- toVertex -< f g' <- toVertex -< g returnA -< (a', b', c', d', e', f', g') instance VertexInput a => VertexInput (V0 a) where type VertexFormat (V0 a) = V0 (VertexFormat a) toVertex = arr (const V0) instance VertexInput a => VertexInput (V1 a) where type VertexFormat (V1 a) = V1 (VertexFormat a) toVertex = proc ~(V1 a) -> do a' <- toVertex -< a returnA -< V1 a' instance VertexInput a => VertexInput (V2 a) where type VertexFormat (V2 a) = V2 (VertexFormat a) toVertex = proc ~(V2 a b) -> do a' <- toVertex -< a b' <- toVertex -< b returnA -< V2 a' b' instance VertexInput a => VertexInput (V3 a) where type VertexFormat (V3 a) = V3 (VertexFormat a) toVertex = proc ~(V3 a b c) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c returnA -< V3 a' b' c' instance VertexInput a => VertexInput (V4 a) where type VertexFormat (V4 a) = V4 (VertexFormat a) toVertex = proc ~(V4 a b c d) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c d' <- toVertex -< d returnA -< V4 a' b' c' d' instance VertexInput a => VertexInput (Quaternion a) where type VertexFormat (Quaternion a) = Quaternion (VertexFormat a) toVertex = proc ~(Quaternion a v) -> do a' <- toVertex -< a v' <- toVertex -< v returnA -< Quaternion a' v' instance (VertexInput (f a), VertexInput a, HostFormat (f a) ~ f (HostFormat a), VertexFormat (f a) ~ f (VertexFormat a)) => VertexInput (Point f a) where type VertexFormat (Point f a) = Point f (VertexFormat a) toVertex = proc ~(P a) -> do a' <- toVertex -< a returnA -< P a' instance VertexInput a => VertexInput (Plucker a) where type VertexFormat (Plucker a) = Plucker (VertexFormat a) toVertex = proc ~(Plucker a b c d e f) -> do a' <- toVertex -< a b' <- toVertex -< b c' <- toVertex -< c d' <- toVertex -< d e' <- toVertex -< e f' <- toVertex -< f returnA -< Plucker a' b' c' d' e' f'
Teaspot-Studio/GPipe-Core
src/Graphics/GPipe/Internal/PrimitiveStream.hs
mit
22,384
13
18
6,885
7,189
3,654
3,535
325
10
module ASPico.Handler.Root.Affiliate ( ApiAffiliate , serverAffiliate ) where import ASPico.Prelude hiding (product) import Database.Persist.Sql (Entity(..), fromSqlKey) import Servant ((:>), FormUrlEncoded, JSON, Post, ReqBody, ServerT) import ASPico.Envelope (Envelope, returnSuccess) import ASPico.Error (AppErr) import ASPico.Form (AffiliateForm(..), AffiliateResp(..)) import ASPico.Monad (MonadASPicoDb, dbCreateAffiliate) type ApiAffiliate = "affiliate" :> ReqBody '[JSON, FormUrlEncoded] AffiliateForm :> Post '[JSON, FormUrlEncoded] (Envelope AffiliateResp) serverAffiliate :: (MonadError AppErr m, MonadASPicoDb m) => ServerT ApiAffiliate m serverAffiliate = affUrl affUrl :: (MonadError AppErr m, MonadASPicoDb m) => AffiliateForm -> m (Envelope AffiliateResp) affUrl form = do Entity k _ <- dbCreateAffiliate form returnSuccess . AffiliateResp . tshow . fromSqlKey $ k
arowM/ASPico
src/ASPico/Handler/Root/Affiliate.hs
mit
905
0
10
124
282
162
120
-1
-1
module StackLang where import Prelude hiding (EQ,If) -- Grammar for StackLang: -- -- num ::= (any number) -- bool ::= `true` | `false` -- prog ::= cmd* -- cmd ::= int push a number on the stack -- | bool push a boolean on the stack -- | `add` add the top two numbers the stack -- | `eq` check whether the top two elements are equal -- | `if` prog prog if the value on the top -- 1. Encode the above grammar as a set of Haskell data types type Num = Int type Prog = [Cmd] data Cmd = LitI Int | LitB Bool | Add | EQ | If Prog Prog deriving (Eq,Show) -- 2. Write a Haskell value that represents a StackLang program that: -- * checks whether 3 and 4 are equal -- * if so, returns the result of adding 5 and 6 -- * if not, returns the value false myProg :: Prog myProg = [LitI 3, LitI 4, EQ, If [LitI 5, LitI 6, Add] [LitB False]] -- 3. Write a Haskell function that takes two arguments x and y -- and generates a StackLang program that adds both x and y to -- the number on the top of the stack genAdd2 :: Int -> Int -> Prog genAdd2 x y = [LitI x, LitI y, Add, Add] -- 4. Write a Haskell function that takes a list of integers and -- generates a StackLang program that sums them all up. genSum :: [Int] -> Prog genSum [] = [LitI 0] genSum (x:xs) = genSum xs ++ [LitI x, Add]
siphayne/CS381
scratch/StackLang.hs
mit
1,454
0
8
453
243
145
98
17
1
module Utils where import Import hiding (group) import Data.Char (isSpace) import Data.Conduit.Binary (sinkLbs) import qualified Data.ByteString.Lazy.Char8 as LB8 import qualified Data.HashMap.Strict as M import qualified Data.List as L -- import Data.Hashable stringFields :: Int -> String -> Either String [String] stringFields n s | length xs == n = Right xs | otherwise = Left err where xs = stringFields' s err = s ++ " does not have " ++ show n ++ " fields!" stringFields' :: String -> [String] stringFields' s = snipSpaces <$> (splitOn ',' s) splitOn :: (Eq a) => a -> [a] -> [[a]] splitOn _ [] = [[]] splitOn x (y:ys) | x == y = [] : splitOn x ys | otherwise = (y:zs) : zss where zs:zss = splitOn x ys snipSpaces :: String -> String snipSpaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace fileLines :: FileInfo -> IO [String] fileLines file = do bytes <- runResourceT $ fileSource file $$ sinkLbs return (lines . LB8.unpack $ bytes) textString :: (IsString a) => Text -> a textString = fromString . unpack group :: (Eq k, Hashable k) => [(k, v)] -> M.HashMap k [v] group = groupBase M.empty groupBase :: (Eq k, Hashable k) => M.HashMap k [v] -> [(k, v)] -> M.HashMap k [v] groupBase = L.foldl' (\m (k, v) -> inserts k v m) groupList :: (Eq k, Hashable k) => [(k, v)] -> [(k, [v])] groupList = M.toList . group groupBy :: (Eq k, Hashable k) => (a -> k) -> [a] -> M.HashMap k [a] groupBy f = L.foldl' (\m x -> inserts (f x) x m) M.empty inserts :: (Eq k, Hashable k) => k -> v -> M.HashMap k [v] -> M.HashMap k [v] inserts k v m = M.insert k (v : M.lookupDefault [] k m) m
ranjitjhala/gradr
Utils.hs
mit
1,752
0
11
463
803
429
374
38
1
-- | Specification for the exercises of Chapter 6. module Chapter06Spec where import qualified Chapter06 as C6 import Data.List (sort) import Data.Proxy import Test.Hspec (Spec, describe, it, shouldBe) import Test.QuickCheck (Arbitrary (..), Property, property, (.&.), (===), (==>)) checkEquivalence :: (Arbitrary a, Show a, Show b, Eq b) => Proxy a -> (a -> b) -> (a -> b) -> Property checkEquivalence _ f g = property $ \x -> f x === g x newtype IncreasingList a = IL { incList :: [a] } deriving (Eq, Show) newtype NonEmptyList a = NEL { list :: [a] } deriving (Eq, Show) instance (Ord a, Arbitrary a) => Arbitrary (IncreasingList a) where arbitrary = IL . sort <$> arbitrary instance (Arbitrary a) => Arbitrary (NonEmptyList a) where arbitrary = do x <- arbitrary xs <- arbitrary return $ NEL (x:xs) checkIndex :: Int -> Property checkIndex i = checkEquivalence (Proxy :: Proxy (NonEmptyList Double)) (apply (!!) i) (apply (C6.!!) i) where apply f j (NEL xs) = f xs j' where j' = (abs j) `min` (length xs - 1) type TwoIncreasingLists = (IncreasingList Double, IncreasingList Double) spec :: Spec spec = do describe "Exercise 1: define a function that" $ do describe "returns true iff all logical values in a list are true" $ do it "returns True for the empty list" $ do C6.and ([]:: [Bool]) `shouldBe` True it "returns True if only True is in the list" $ do C6.and [True] `shouldBe` True it "returns False if only False is in the list" $ do C6.and [False] `shouldBe` False it "returns False if any value is False" $ do C6.and [True, False, False] `shouldBe` False C6.and [False, True, True] `shouldBe` False it "returns True if all values are True" $ do C6.and [True, True, True ] `shouldBe` True it "behaves equivalent to and" $ checkEquivalence (Proxy :: Proxy [Bool]) and C6.and describe "concatenates a list of lists" $ do it "returns empty list for the empty list" $ do C6.concat ([] :: [[Int]]) `shouldBe` [] it "returns the list for a list of only one list" $ do C6.concat ([[1,2,3]] :: [[Int]]) `shouldBe` [1,2,3] it "returns the concatenation of the list in the list" $ do C6.concat ([[1,2,3], [4,5,6], [7,8,9]] :: [[Int]]) `shouldBe` [1,2,3,4,5,6,7,8,9] it "behaves equivalent to concat" $ checkEquivalence (Proxy :: Proxy [String]) concat C6.concat describe "produces a list with n identical elements" $ do it "returns empty list for n < 0" $ do C6.replicate 0 True `shouldBe` [] C6.replicate 0 'a' `shouldBe` [] C6.replicate (-10::Int) True `shouldBe` [] it "returns a list with 1 element for n = 1" $ do C6.replicate 1 13 `shouldBe` [13] it "returns a list with n times the same element" $ do C6.replicate 3 'a' `shouldBe` "aaa" C6.replicate 2 (13::Int) `shouldBe` [13,13] it "behaves equivalent to replicate" $ property $ \i -> checkEquivalence (Proxy :: Proxy Char) (replicate i) (C6.replicate i) describe "selects the nth element of a list" $ do it "returns the element if n=0 and there is only one element" $ do ['a'] C6.!! 0 `shouldBe` 'a' it "returns the element if nth element" $ do "abcd" C6.!! 2 `shouldBe` 'c' it "behaves equivalent to !!" $ property $ checkIndex describe "decides if an element is in a list" $ do it "returns False if the list is empty" $ do C6.elem 'a' [] `shouldBe` False it "returns True if the element is in the list" $ do C6.elem 'a' "dcba" `shouldBe` True it "returns False if the element is not in the list" $ do C6.elem 'e' "dcba" `shouldBe` False it "behaves equivalent to elem" $ property $ \str -> checkEquivalence (Proxy :: Proxy [String]) (str `elem`) (str `C6.elem`) describe "Exercise 2: define a recursive function that" $ do describe "merges two sorted lists of values to give a single sorted list" $ do it "returns the empty list if both lists are empty" $ do C6.merge ([]::[Int]) ([]::[Int]) `shouldBe` [] it "returns the other list if one of both lists is empty" $ do C6.merge "foo" "" `shouldBe` "foo" C6.merge "" "foo" `shouldBe` "foo" it "merges the two lists" $ do C6.merge "foo" "abr" `shouldBe` "abfoor" it "behaves equivalent to sort" $ checkEquivalence (Proxy :: Proxy TwoIncreasingLists) (\(xs, ys) -> C6.merge (incList xs) (incList ys)) (\(xs, ys) -> sort (incList xs ++ incList ys)) describe "Exercise 3" $ do it "returns the empty list if the list is empty" $ do C6.msort ([]::[Int]) `shouldBe` [] it "returns the list if the has length 1" $ do C6.msort "a" `shouldBe` "a" it "returns the sorted list" $ do C6.msort "the quick brown fox jumps over the lazy dog" `shouldBe` " abcdeeefghhijklmnoooopqrrsttuuvwxyz" it "behaves equivalent to sort" $ do checkEquivalence (Proxy :: Proxy [[Int]]) sort C6.msort
EindhovenHaskellMeetup/meetup
courses/programming-in-haskell/pih-exercises/test/Chapter06Spec.hs
mit
5,372
0
20
1,581
1,730
903
827
100
1
module ProjectEuler.Problem004 (solve) where isPalindrome :: Integer -> Bool isPalindrome n = reverse xs == xs where xs = show n nDigitIntegers :: Integer -> [Integer] nDigitIntegers n = [10^(n-1)..(10^n)-1] solve :: Integer -> Integer solve n = maximum $ filter isPalindrome xs where xs = [a * b | a <- ys, b <- ys] ys = nDigitIntegers n
hachibu/project-euler
src/ProjectEuler/Problem004.hs
mit
358
0
9
79
156
83
73
10
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- | This module introduces functions that allow to run action in parallel with logging. module System.Wlog.Concurrent ( WaitingDelta (..) , CanLogInParallel , logWarningLongAction , logWarningWaitOnce , logWarningWaitLinear , logWarningWaitInf ) where import Universum import Control.Concurrent.Async.Lifted (withAsyncWithUnmask) import Control.Monad.Trans.Control (MonadBaseControl) import Fmt ((+|), (+||), (|+), (||+)) import GHC.Real ((%)) import Time (RatioNat, Second, Time, sec, threadDelay, timeMul, (+:+)) import System.Wlog.CanLog (WithLoggerIO, logWarning) -- | Data type to represent waiting strategy for printing warnings -- if action take too much time. data WaitingDelta -- | wait s seconds and stop execution = WaitOnce (Time Second) -- | wait s, s * 2, s * 3 , s * 4 , ... seconds | WaitLinear (Time Second) -- | wait m, m * q, m * q^2, m * q^3, ... microseconds | WaitGeometric (Time Second) RatioNat deriving (Show) -- | Constraint for something that can be logged in parallel with other action. type CanLogInParallel m = (MonadBaseControl IO m, WithLoggerIO m) -- | Run action and print warning if it takes more time than expected. logWarningLongAction :: forall m a . CanLogInParallel m => (Text -> m ()) -> WaitingDelta -> Text -> m a -> m a logWarningLongAction logFunc delta actionTag action = -- Previous implementation was -- -- bracket (fork $ waitAndWarn delta) killThread (const action) -- -- but this has a subtle problem: 'killThread' can be interrupted even -- when exceptions are masked, so it's possible that the forked thread is -- left running, polluting the logs with misinformation. -- -- 'withAsync' is assumed to take care of this, and indeed it does for -- 'Production's implementation, which uses the definition from the async -- package: 'uninterruptibleCancel' is used to kill the thread. -- -- thinking even more about it, unmasking auxilary thread is crucial if -- this function is going to be called under 'mask'. withAsyncWithUnmask (\unmask -> unmask $ waitAndWarn delta) (const action) where printWarning :: Time Second -> m () printWarning t = logFunc $ "Action `"+|actionTag|+"` took more than "+||t||+"" waitAndWarn :: WaitingDelta -> m () waitAndWarn (WaitOnce s) = delayAndPrint s s waitAndWarn (WaitLinear s) = let waitLoop :: Time Second -> m () waitLoop acc = do delayAndPrint s acc waitLoop (acc +:+ s) in waitLoop s waitAndWarn (WaitGeometric ms k) = let waitLoop :: Time Second -> Time Second -> m () waitLoop acc delayT = do let newAcc = acc +:+ delayT let newDelayT = k `timeMul` delayT delayAndPrint delayT newAcc waitLoop newAcc newDelayT in waitLoop (sec 0) ms delayAndPrint :: Time Second -> Time Second -> m () delayAndPrint delayT printT = do threadDelay delayT printWarning printT {- Helper functions to avoid dealing with data type -} -- | Specialization of 'logWarningLongAction' with 'WaitOnce'. logWarningWaitOnce :: CanLogInParallel m => Time Second -> Text -> m a -> m a logWarningWaitOnce = logWarningLongAction logWarning . WaitOnce -- | Specialization of 'logWarningLongAction' with 'WaiLinear'. logWarningWaitLinear :: CanLogInParallel m => Time Second -> Text -> m a -> m a logWarningWaitLinear = logWarningLongAction logWarning . WaitLinear -- | Specialization of 'logWarningLongAction' with 'WaitGeometric' -- with parameter @1.3@. Accepts 'Second'. logWarningWaitInf :: CanLogInParallel m => Time Second -> Text -> m a -> m a logWarningWaitInf = logWarningLongAction logWarning . (`WaitGeometric` (13 % 10))
serokell/log-warper
src/System/Wlog/Concurrent.hs
mit
4,062
0
16
990
781
421
360
57
3
{-# htermination negate :: Float -> Float #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_negate_3.hs
mit
46
0
2
8
3
2
1
1
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module SchoolOfHaskell.Scheduler.API where import Control.Applicative ((<$>), (<*>)) import Control.Lens (makeLenses) import Data.Aeson (ToJSON(..), FromJSON(..)) import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier) import Data.Data (Data) import Data.Text (Text) import Data.Typeable (Typeable) import Data.UUID.Types (UUID) import qualified Data.UUID.Types as UUID newtype ContainerSpec = ContainerSpec {_csImageName :: Text} deriving (Eq, Show, Data, Typeable) newtype ContainerReceipt = ContainerReceipt {_crID :: UUID} deriving (Eq, Data, Typeable) instance Show ContainerReceipt where show = show . _crID newtype ContainerId = ContainerId {_ciID :: Text} deriving (Eq, Show, Ord, Data, Typeable) data ContainerDetail = ContainerDetail {_cdID :: Text ,_cdAddress :: Maybe (Text, PortMappings) ,_cdStatus :: Maybe Text} deriving (Eq, Show, Data, Typeable) instance ToJSON UUID where toJSON = toJSON . UUID.toString instance FromJSON UUID where parseJSON val = do str <- parseJSON val case UUID.fromString str of Nothing -> fail "Failed to parse UUID from JSON" Just x -> return x newtype PortMappings = PortMappings [(Int,Int)] deriving (Eq, Show, Data, Typeable, ToJSON, FromJSON) ------------------------------------------------------------------------------ -- Constants -- | Receipt used for local development. devReceipt :: ContainerReceipt devReceipt = ContainerReceipt (UUID.fromWords 0 0 0 0) ------------------------------------------------------------------------------ -- Lenses and aeson instances $(let opts n = defaultOptions { fieldLabelModifier = drop n } in concat <$> mapM (\(n, x) -> (++) <$> makeLenses x <*> deriveJSON (opts n) x) [ (3, ''ContainerSpec) , (3, ''ContainerReceipt) , (3, ''ContainerId) , (3, ''ContainerDetail) ])
fpco/schoolofhaskell
soh-scheduler-api/src/SchoolOfHaskell/Scheduler/API.hs
mit
2,070
0
16
418
573
330
243
47
1
length' [] = 0 length' (x:xs) = 1 + (length' xs) append' [] = id append' (x:xs) = (x:).append' xs -- A trivial way reverse' [] = [] reverse' (x:xs) = (reverse' xs) ++ [x] reverse2 = rev [] where rev a [] = a rev a (x:xs) = rev (x:a) xs fix f = f (fix f) reverse3 = fix (\ f a x -> case x of [] -> a (x:xs) -> f (x:a)xs) [] concat' [] = [] concat' (x:xs) = x : concat' xs intersperse _ ys | length ys < 2 = ys intersperse x (y:ys) = y : x : intersperse x ys zip' _ [] = [] zip' [] _ = [] zip' (x:xs) (y:ys) = (x, y) : zip' xs ys unzip' [] = ([], []) unzip' ((x,y):l) = (x:l1, y:l2) where (l1, l2) = unzip l zipwith f [] _ = [] zipwith f _ [] = [] zipwith f (x:xs) (y:ys) = f x y : zipwith f xs ys
MaKToff/SPbSU_Homeworks
Semester 3/Classwork/cw01.hs
mit
760
0
13
234
542
279
263
26
2
szachy is xD mialo byc warcaby xD w erlangu zrobic strange sort itp.. wszysstko to co w haskelu
RAFIRAF/HASKELL
CHESS2016.hs
mit
97
2
5
19
44
19
25
-1
-1
{- ****************************************************************************** * JSHOP * * * * Module: ParseMonad * * Purpose: Monad for scanning and parsing * * Authors: Nick Brunt, Henrik Nilsson * * * * Based on the HMTC equivalent * * Copyright (c) Henrik Nilsson, 2006 - 2011 * * http://www.cs.nott.ac.uk/~nhn/ * * * * Revisions for JavaScript * * Copyright (c) Nick Brunt, 2011 - 2012 * * * ****************************************************************************** -} module ParseMonad where -- Standard library imports import Control.Monad.Identity import Control.Monad.Error import Control.Monad.State -- JSHOP module imports import Token --import Lexer data LexerMode = Normal | InComment | InRegex deriving Show data LexerState = LS {rest :: String, lineno :: Int, mode :: LexerMode, tr :: [String], nl :: Bool, rest2 :: String, expectRegex :: Bool, lastToken :: (Maybe Token)} deriving Show startState str = LS {rest = str, lineno = 1, mode = Normal, tr = [], nl = False, rest2 = "", expectRegex = False, lastToken = Nothing} type P = StateT LexerState (ErrorT String Identity) getLineNo :: P Int getLineNo = do s <- get return (lineno s) {- -- | Monad for scanning and parsing. -- The scanner and parser are both monadic, following the design outlined -- in the Happy documentation on monadic parsers. The parse monad P -- is built on top of the diagnostics monad D, additionally keeping track -- of the input and current source code position, and exploiting that -- the source code position is readily available to avoid having to pass -- the position as an explicit argument. module ParseMonad ( -- The parse monad P (..), -- Not abstract. Instances: Monad. unP, -- :: P a -> (Int -> Int -> String -> D a) emitInfoP, -- :: String -> P () emitWngP, -- :: String -> P () emitErrP, -- :: String -> P () failP, -- :: String -> P a getSrcPosP, -- :: P SrcPos runP -- :: String -> P a -> D a ) where -- JSHOP module imports import SrcPos import Diagnostics newtype P a = P (Int -> Int -> String -> D a) unP :: P a -> (Int -> Int -> String -> D a) unP (P x) = x instance Monad P where return a = P (\_ _ _ -> return a) p >>= f = P (\l c s -> unP p l c s >>= \a -> unP (f a) l c s) -- Liftings of useful computations from the underlying D monad, taking -- advantage of the fact that source code positions are available. -- | Emits an information message. emitInfoP :: String -> P () emitInfoP msg = P (\l c _ -> emitInfoD (SrcPos l c) msg) -- | Emits a warning message. emitWngP :: String -> P () emitWngP msg = P (\l c _ -> emitWngD (SrcPos l c) msg) -- | Emits an error message. emitErrP :: String -> P () emitErrP msg = P (\l c _ -> emitErrD (SrcPos l c) msg) -- | Emits an error message and fails. failP :: String -> P a failP msg = P (\l c _ -> failD (SrcPos l c) msg) -- | Gets the current source code position. getSrcPosP :: P SrcPos getSrcPosP = P (\l c _ -> return (SrcPos l c)) -- | Runs parser (and scanner), yielding a result in the diagnostics monad D. runP :: P a -> String -> D a runP p s = unP p 1 1 s -}
nbrunt/JSHOP
src/old/ver2/ParseMonad.hs
mit
4,096
0
10
1,645
226
139
87
34
1
----------------------------------------------------------------------------- -- -- Module : Topology -- Copyright : -- License : AllRightsReserved -- -- Maintainer : -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Topology ( cycles ) where import Prelude hiding (cycle, elem) import Data.Bits (bit, xor) import Data.List ((\\)) import Data.Collections (fromList, elem) import Data.Cycle (Cycle) import Util (headMaybe, cshiftL, log2) type GenFunc = Int -> Int generate :: Eq a => (a -> a) -> [a] -> [a] generate f ls@(l:_) = if new `elem` ls then ls else generate f (new : ls) where new = f l generate _ [] = error "Must provide init value for generate" cycle :: Int -> GenFunc -> [Cycle Int] cycle n f = map fromList $ step [] 0 where allNums = [0 .. 2 ^ n - 1] step res init = case findInit of Nothing -> res' Just init' -> step res' init' where new = generate f [init] res' = new : res findInit = headMaybe $ allNums \\ concat res' genFuncs :: Int -> [GenFunc] genFuncs pow = map (genFunc pow) [1 .. n] where n = log2 pow genFunc :: Int -> Int -> GenFunc genFunc pow i = cshiftL pow i . xor (if odd i then f else l) where f = 1 l = bit (pow - 1) cycles :: Int -> [Cycle Int] cycles pow = concatMap (cycle pow) $ genFuncs pow
uvNikita/TopologyRouting
src/Topology.hs
mit
1,494
0
10
423
505
279
226
32
2
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : $Header$ Description : embedding from CASL to VSE, plus wrapping procedures with default implementations Copyright : (c) M.Codescu, DFKI Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : Mihai.Codescu@dfki.de Stability : provisional Portability : non-portable (imports Logic.Logic) The embedding comorphism from CASL to VSE. -} module Comorphisms.CASL2VSEImport (CASL2VSEImport(..)) where import Logic.Logic import Logic.Comorphism import CASL.Logic_CASL import CASL.Sublogic as SL import CASL.Sign import CASL.AS_Basic_CASL import CASL.Morphism import VSE.Logic_VSE import VSE.As import VSE.Ana import Common.AS_Annotation import Common.Id import Common.ProofTree import Common.Result import qualified Common.Lib.MapSet as MapSet import qualified Data.Set as Set import qualified Data.Map as Map -- | The identity of the comorphism data CASL2VSEImport = CASL2VSEImport deriving (Show) instance Language CASL2VSEImport -- default definition is okay instance Comorphism CASL2VSEImport CASL CASL_Sublogics CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS CASLSign CASLMor Symbol RawSymbol ProofTree VSE () VSEBasicSpec Sentence SYMB_ITEMS SYMB_MAP_ITEMS VSESign VSEMor Symbol RawSymbol () where sourceLogic CASL2VSEImport = CASL sourceSublogic CASL2VSEImport = SL.cFol targetLogic CASL2VSEImport = VSE mapSublogic CASL2VSEImport _ = Just () map_theory CASL2VSEImport = mapCASLTheory map_morphism CASL2VSEImport = return . mapMor map_sentence CASL2VSEImport _ = return . mapFORMULA map_symbol CASL2VSEImport = error "nyi" -- check these 3, but should be fine has_model_expansion CASL2VSEImport = True is_weakly_amalgamable CASL2VSEImport = True isInclusionComorphism CASL2VSEImport = True mapCASLTheory :: (CASLSign, [Named CASLFORMULA]) -> Result (VSESign, [Named Sentence]) mapCASLTheory (sig, n_sens) = do let (tsig, genAx) = mapSig sig tsens = map (mapNamed mapFORMULA) n_sens case not $ null $ checkCases tsig (tsens ++ genAx) of True -> fail "case error in signature" _ -> return (tsig, tsens ++ genAx) mkIfProg :: FORMULA () -> Program mkIfProg f = mkRanged $ If f (mkRanged $ Return aTrue) $ mkRanged $ Return aFalse mapSig :: CASLSign -> (VSESign, [Named Sentence]) mapSig sign = let wrapSort (procsym, axs) s = let restrName = gnRestrName s eqName = gnEqName s sProcs = [(restrName, Profile [Procparam In s] Nothing), (eqName, Profile [Procparam In s, Procparam In s] (Just uBoolean))] sSens = [makeNamed ("ga_restriction_" ++ show s) $ ExtFORMULA $ mkRanged (Defprocs [Defproc Proc restrName [xVar] (mkRanged (Block [] (mkRanged Skip))) nullRange]) ,makeNamed ("ga_equality_" ++ show s) $ ExtFORMULA $ mkRanged (Defprocs [Defproc Func eqName (map mkSimpleId ["x", "y"]) (mkRanged (Block [] (mkIfProg (Strong_equation (Qual_var (mkSimpleId "x") s nullRange) (Qual_var (mkSimpleId "y") s nullRange) nullRange)))) nullRange]) ] in (sProcs ++ procsym, sSens ++ axs) (sortProcs, sortSens) = foldl wrapSort ([],[]) $ Set.toList $ sortSet sign wrapOp (procsym, axs) (i, opTypes) = let funName = mkGenName i fProcs = map (\profile -> (funName, Profile (map (Procparam In) $ opArgs profile) (Just $ opRes profile))) opTypes fSens = map (\ (OpType fKind w s) -> let vars = genVars w in makeNamed "" $ ExtFORMULA $ Ranged (Defprocs [Defproc Func funName (map fst vars) ( Ranged (Block [] (Ranged (Block [Var_decl [yVar] s nullRange] (Ranged (Seq (Ranged (Assign yVar (Application (Qual_op_name i (Op_type fKind w s nullRange) nullRange ) (map (\(v, ss) -> Qual_var v ss nullRange) vars) nullRange)) nullRange) (Ranged (Return (Qual_var yVar s nullRange)) nullRange) )--end seq nullRange) )--end block nullRange)-- end procedure body ) nullRange) nullRange] ) nullRange ) opTypes in (procsym ++ fProcs, axs ++ fSens) (opProcs, opSens) = foldl wrapOp ([], []) $ MapSet.toList $ opMap sign wrapPred (procsym, axs) (i, predTypes) = let procName = mkGenName i pProcs = map (\profile -> (procName, Profile (map (Procparam In) $ predArgs profile) (Just uBoolean))) predTypes pSens = map (\ (PredType w) -> let vars = genVars w in makeNamed "" $ ExtFORMULA $ mkRanged (Defprocs [Defproc Func procName (map fst vars) (mkRanged (Block [] (mkIfProg (Predication (Qual_pred_name i (Pred_type w nullRange) nullRange) (map (\(v, ss) -> Qual_var v ss nullRange) vars) nullRange)))) nullRange] ) ) predTypes in (procsym ++ pProcs, axs ++ pSens) (predProcs, predSens) = foldl wrapPred ([],[]) $ MapSet.toList $ predMap sign procs = Procs $ Map.fromList (sortProcs ++ opProcs ++ predProcs) newPreds = procsToPredMap procs newOps = procsToOpMap procs in(sign { opMap = addOpMapSet (opMap sign) newOps, predMap = addMapSet (predMap sign) newPreds, extendedInfo = procs, sentences = [] }, sortSens ++ opSens ++ predSens) mapMor :: CASLMor -> VSEMor mapMor m = let (om, pm) = vseMorExt m in m { msource = fst $ mapSig $ msource m , mtarget = fst $ mapSig $ mtarget m , op_map = Map.union om $ op_map m , pred_map = Map.union pm $ pred_map m , extended_map = emptyMorExt }
nevrenato/Hets_Fork
Comorphisms/CASL2VSEImport.hs
gpl-2.0
7,891
0
46
3,564
1,813
950
863
164
2
predecessor = predecessor successor :: Bool successor = successor
evolutics/haskell-formatter
testsuite/resources/source/comments/empty_lines/between_top_level_functions/with_type_signature/0/Input.hs
gpl-3.0
66
0
4
9
16
9
7
3
1
import System.IO import System.Environment(getArgs) import System.Process import qualified Data.ByteString.Char8 as Byte import Control.Concurrent import System.Exit import System.Directory(removeFile) first :: [a] -> a first (x:xs) = x give :: Byte.ByteString -> [[String]] give file = map (map (Byte.unpack)) $ fmap (Byte.split '|') $ (Byte.split '\n' file) process :: [String] -> String process x = foldl (\acc x -> acc ++ " " ++ x) "" x mapping :: [[String]] -> IO (Maybe a) mapping (x:xs) = do --forkIO $ do putStrLn $ "judge " ++ (process x) list <- readCreateProcessWithExitCode ((shell $ "Judge/judge " ++ (process x) ) {cwd = Just "Judge"}) "" some <- mapping xs return Nothing mapping [] = do return Nothing main = do input <- Byte.readFile "request.txt" mapping $ give input removeFile "request.txt" return ()
prannayk/conj
vader.hs
gpl-3.0
840
0
14
148
363
187
176
25
1
data Cont r a = Cont ((a -> r) -> r)
hmemcpy/milewski-ctfp-pdf
src/content/3.5/code/haskell/snippet23.hs
gpl-3.0
36
0
10
10
26
15
11
1
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE DeriveFunctor #-} -- | Abstract Haskell syntax for expressions. module Language.Haskell.Syntax.HsExpr (SrcLoc, LHsExpr, LGRHS, LMatch, LStmt, LHsCmd, LHsTupArg, LHsCmdTop, LStmtLR, CmdLStmt, ParStmtBlock(..), HsArrAppType(..), HsCmdTop(..), HsExpr(..), GRHS(..), GRHSs(..), HsTupArg(..), HsSplice(..), MatchGroup(..), Match(..), HsCmd(..), HsStmtContext (..), ExprLStmt, StmtLR(..), TransForm(..), ArithSeqInfo(..), HsMatchContext (..), FunctionFixity(..), HsBracket(..), CmdStmt(..), Stmt(..), HsRecordBinds(..), ExprStmt(..)) where -- friends: import Language.Haskell.Syntax.HsDecls import Language.Haskell.Syntax.HsPat import Language.Haskell.Syntax.HsLit import Language.Haskell.Syntax.HsTypes import Language.Haskell.Syntax.HsBinds import Language.Haskell.Syntax.BasicTypes import Language.Haskell.Utility.FastString import Language.Haskell.Syntax.SrcLoc -- libraries: import Data.Data hiding (Fixity(..)) {- ************************************************************************ * * \subsection{Expressions proper} * * ************************************************************************ -} -- * Expressions proper type LHsExpr id = Located (HsExpr id) -- | A Haskell expression. data HsExpr id = HsVar (Located id) -- ^ Variable -- See Note [Located RdrNames] | HsRecFld (AmbiguousFieldOcc id) -- ^ Variable pointing to record selector | HsOverLabel FastString -- ^ Overloaded label (See Note [Overloaded labels] -- in GHC.OverloadedLabels) | HsIPVar HsIPName -- ^ Implicit parameter | HsOverLit (HsOverLit id) -- ^ Overloaded literals | HsLit HsLit -- ^ Simple (non-overloaded) literals | HsLam (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsLamCase (MatchGroup id (LHsExpr id)) -- ^ Lambda-case -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsApp (LHsExpr id) (LHsExpr id) -- ^ Application | HsAppType (LHsExpr id) (LHsWcType id) -- ^ Visible type application -- -- Explicit type argument; e.g f @Int x y -- NB: Has wildcards, but no implicit quantification -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt', -- | Operator applications: -- NB Bracketed ops such as (+) come out as Vars. -- NB We need an expr for the operator in an OpApp/Section since -- the typechecker may need to apply the operator to a few types. | OpApp (LHsExpr id) -- left operand (LHsExpr id) -- operator (LHsExpr id) -- right operand -- | Negation operator. Contains the negated expression and the name -- of 'negate' -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus' -- For details on above see note [Api annotations] in ApiAnnotation | NegApp (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsPar (LHsExpr id) -- ^ Parenthesised expr; see Note [Parens in HsSyn] | SectionL (LHsExpr id) -- operand; see Note [Sections in HsSyn] (LHsExpr id) -- operator | SectionR (LHsExpr id) -- operator; see Note [Sections in HsSyn] (LHsExpr id) -- operand -- | Used for explicit tuples and sections thereof -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitTuple [LHsTupArg id] Boxity -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCase (LHsExpr id) (MatchGroup id (LHsExpr id)) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsIf (LHsExpr id) -- predicate (LHsExpr id) -- then part (LHsExpr id) -- else part -- | Multi-way if -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf' -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation | HsMultiIf [LGRHS id (LHsExpr id)] -- | let(rec) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsLet (Located (HsLocalBinds id)) (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsDo (HsStmtContext id) -- The parameterisation is unimportant -- because in this context we never use -- the PatGuard or ParStmt variant (Located [ExprLStmt id]) -- "do":one or more stmts -- | Syntactic list: [a,b,c,...] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitList [LHsExpr id] -- | Syntactic parallel array: [:e1, ..., en:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnVbar' -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitPArr [LHsExpr id] -- | Record construction -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordCon { rcon_con_name :: Located id -- The constructor name; -- not used after type checking , rcon_flds :: HsRecordBinds id } -- The fields -- | Record update -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordUpd { rupd_expr :: LHsExpr id , rupd_flds :: [LHsRecUpdField id] } -- For a type family, the arg types are of the *instance* tycon, -- not the family tycon -- | Expression with an explicit type signature. @e :: type@ -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | ExprWithTySig (LHsExpr id) (LHsSigWcType id) -- | Arithmetic sequence -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ArithSeq (ArithSeqInfo id) -- | Arithmetic sequence for parallel array -- -- > [:e1..e2:] or [:e1, e2..e3:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | PArrSeq (ArithSeqInfo id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@, -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsSCC SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- "set cost centre" SCC pragma (LHsExpr id) -- expr whose cost is to be measured -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@, -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- hdaume: core annotation (LHsExpr id) ----------------------------------------------------------- -- MetaHaskell Extensions -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsBracket (HsBracket id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsSpliceE (HsSplice id) ----------------------------------------------------------- -- Arrow notation extension -- | @proc@ notation for Arrows -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc', -- 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | HsProc (LPat id) -- arrow abstraction, proc (LHsCmdTop id) -- body of the abstraction -- always has an empty stack --------------------------------------- -- static pointers extension -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic', -- For details on above see note [Api annotations] in ApiAnnotation | HsStatic (LHsExpr id) -- Body --------------------------------------- -- The following are commands, not expressions proper -- They are only used in the parsing stage and are removed -- immediately in parser.RdrHsSyn.checkCommand -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation | HsArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands --------------------------------------- -- Haskell program coverage (Hpc) Support | HsBinTick Int -- module-local tick number for True Int -- module-local tick number for False (LHsExpr id) -- sub-expression -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnMinus', -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon', -- 'ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTickPragma -- A pragma introduced tick SourceText -- Note [Pragma source text] in BasicTypes (StringLiteral,(Int,Int),(Int,Int)) -- external span for this tick ((SourceText,SourceText),(SourceText,SourceText)) -- Source text for the four integers used in the span. -- See note [Pragma source text] in BasicTypes (LHsExpr id) --------------------------------------- -- These constructors only appear temporarily in the parser. -- The renamer translates them into the Right Thing. | EWildPat -- wildcard -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | EAsPat (Located id) -- as pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | EViewPat (LHsExpr id) -- view pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | ELazyPat (LHsExpr id) -- ~ pattern deriving instance (Data id) => Data (HsExpr id) -- | HsTupArg is used for tuple sections -- (,a,) is represented by ExplicitTuple [Missing ty1, Present a, Missing ty3] -- Which in turn stands for (\x:ty1 \y:ty2. (x,a,y)) type LHsTupArg id = Located (HsTupArg id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation data HsTupArg id = Present (LHsExpr id) -- ^ The argument | Missing deriving instance (Data id) => Data (HsTupArg id) {- ************************************************************************ * * \subsection{Commands (in arrow abstractions)} * * ************************************************************************ We re-use HsExpr to represent these. -} type LHsCmd id = Located (HsCmd id) data HsCmd id -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands | HsCmdApp (LHsCmd id) (LHsExpr id) | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdPar (LHsCmd id) -- parenthesised command -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdCase (LHsExpr id) (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdIf (LHsExpr id) -- predicate (LHsCmd id) -- then part (LHsCmd id) -- else part -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdLet (Located (HsLocalBinds id)) -- let(rec) (LHsCmd id) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdDo (Located [CmdLStmt id]) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation deriving instance (Data id) => Data (HsCmd id) data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp deriving Data {- | Top-level command, introducing a new arrow. This may occur inside a proc (where the stack is empty) or as an argument of a command-forming operator. -} type LHsCmdTop id = Located (HsCmdTop id) data HsCmdTop id = HsCmdTop (LHsCmd id) deriving instance (Data id) => Data (HsCmdTop id) {- ************************************************************************ * * \subsection{Record binds} * * ************************************************************************ -} type HsRecordBinds id = HsRecFields id (LHsExpr id) {- ************************************************************************ * * \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes} * * ************************************************************************ @Match@es are sets of pattern bindings and right hand sides for functions, patterns or case branches. For example, if a function @g@ is defined as: \begin{verbatim} g (x,y) = y g ((x:ys),y) = y+1, \end{verbatim} then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@. It is always the case that each element of an @[Match]@ list has the same number of @pats@s inside it. This corresponds to saying that a function defined by pattern matching must have the same number of patterns in each equation. -} data MatchGroup id body = MG { mg_alts :: Located [LMatch id body] -- The alternatives , mg_origin :: Origin } -- The type is the type of the entire group -- t1 -> ... -> tn -> tr -- where there are n patterns deriving instance (Data body,Data id) => Data (MatchGroup id body) type LMatch id body = Located (Match id body) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a -- list -- For details on above see note [Api annotations] in ApiAnnotation data Match id body = Match { m_ctxt :: HsMatchContext ( id), -- See note [m_ctxt in Match] m_pats :: [LPat id], -- The patterns m_type :: (Maybe (LHsType id)), -- A type signature for the result of the match -- Nothing after typechecking -- NB: No longer supported m_grhss :: (GRHSs id body) } deriving instance (Data body,Data id) => Data (Match id body) -- For details on above see note [Api annotations] in ApiAnnotation data GRHSs id body = GRHSs { grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs grhssLocalBinds :: Located (HsLocalBinds id) -- ^ The where clause } deriving instance (Data body,Data id) => Data (GRHSs id body) type LGRHS id body = Located (GRHS id body) -- | Guarded Right Hand Side. data GRHS id body = GRHS [GuardLStmt id] -- Guards body -- Right hand side deriving instance (Data body,Data id) => Data (GRHS id body) {- ************************************************************************ * * \subsection{Do stmts and list comprehensions} * * ************************************************************************ -} type LStmt id body = Located (StmtLR id id body) type LStmtLR idL idR body = Located (StmtLR idL idR body) type Stmt id body = StmtLR id id body type CmdLStmt id = LStmt id (LHsCmd id) type CmdStmt id = Stmt id (LHsCmd id) type ExprLStmt id = LStmt id (LHsExpr id) type ExprStmt id = Stmt id (LHsExpr id) type GuardLStmt id = LStmt id (LHsExpr id) -- The SyntaxExprs in here are used *only* for do-notation and monad -- comprehensions, which have rebindable syntax. Otherwise they are unused. -- | API Annotations when in qualifier lists or guards -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen', -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy', -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing' -- For details on above see note [Api annotations] in ApiAnnotation data StmtLR idL idR body -- body should always be (LHs**** idR) = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp, -- and (after the renamer) DoExpr, MDoExpr -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff body Bool -- True <=> return was stripped by ApplicativeDo -- For details on above see note [Api annotations] in ApiAnnotation | BindStmt (LPat idL) body | BodyStmt body -- See Note [BodyStmt] -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet' -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@, -- For details on above see note [Api annotations] in ApiAnnotation | LetStmt (Located (HsLocalBindsLR idL idR)) -- ParStmts only occur in a list/monad comprehension | ParStmt [ParStmtBlock idL idR] | TransStmt { trS_form :: TransForm, trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group' -- which generates the tuples to be grouped trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map] trS_using :: LHsExpr idR, trS_by :: Maybe (LHsExpr idR) -- "by e" (optional) -- Invariant: if trS_form = GroupBy, then grp_by = Just e } -- See Note [Monad Comprehensions] -- Recursive statement (see Note [How RecStmt works] below) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec' -- For details on above see note [Api annotations] in ApiAnnotation | RecStmt { recS_stmts :: [LStmtLR idL idR body] -- The next two fields are only valid after renaming , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the -- stmts that are used in stmts that follow the RecStmt , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones, -- that are used before they are bound in the stmts of -- the RecStmt. -- An Id can be in both groups -- Both sets of Ids are (now) treated monomorphically -- See Note [How RecStmt works] for why they are separate } deriving instance (Data body, Data idL, Data idR) => Data (StmtLR idL idR body) data TransForm -- The 'f' below is the 'using' function, 'e' is the by function = ThenForm -- then f or then f by e (depending on trS_by) | GroupForm -- then group using f or then group by e using f (depending on trS_by) deriving Data data ParStmtBlock idL idR = ParStmtBlock [ExprLStmt idL] [idR] -- The variables to be returned deriving instance (Data idL, Data idR) => Data (ParStmtBlock idL idR) data ApplicativeArg idL idR = ApplicativeArgOne -- pat <- expr (pat must be irrefutable) (LPat idL) (LHsExpr idL) | ApplicativeArgMany -- do { stmts; return vars } [ExprLStmt idL] -- stmts (HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn) (LPat idL) -- (v1,...,vn) deriving instance (Data idL, Data idR) => Data (ApplicativeArg idL idR) {- Note [The type of bind in Stmts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some Stmts, notably BindStmt, keep the (>>=) bind operator. We do NOT assume that it has type (>>=) :: m a -> (a -> m b) -> m b In some cases (see Trac #303, #1537) it might have a more exotic type, such as (>>=) :: m i j a -> (a -> m j k b) -> m i k b So we must be careful not to make assumptions about the type. In particular, the monad may not be uniform throughout. Note [TransStmt binder map] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The [(idR,idR)] in a TransStmt behaves as follows: * Before renaming: [] * After renaming: [ (x27,x27), ..., (z35,z35) ] These are the variables bound by the stmts to the left of the 'group' and used either in the 'by' clause, or in the stmts following the 'group' Each item is a pair of identical variables. * After typechecking: [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ] Each pair has the same unique, but different *types*. Note [BodyStmt] ~~~~~~~~~~~~~~~ BodyStmts are a bit tricky, because what they mean depends on the context. Consider the following contexts: A do expression of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E any_ty: do { ....; E; ... } E :: m any_ty Translation: E >> ... A list comprehensions of type [elt_ty] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] [ .. | ..., E, ... ] [ .. | .... | ..., E | ... ] E :: Bool Translation: if E then fail else ... A guard list, guarding a RHS of type rhs_ty ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs... E :: Bool Translation: if E then fail else ... A monad comprehension of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] E :: Bool Translation: guard E >> ... Array comprehensions are handled like list comprehensions. Note [How RecStmt works] ~~~~~~~~~~~~~~~~~~~~~~~~ Example: HsDo [ BindStmt x ex , RecStmt { recS_rec_ids = [a, c] , recS_stmts = [ BindStmt b (return (a,c)) , LetStmt a = ...b... , BindStmt c ec ] , recS_later_ids = [a, b] , return (a b) ] Here, the RecStmt binds a,b,c; but - Only a,b are used in the stmts *following* the RecStmt, - Only a,c are used in the stmts *inside* the RecStmt *before* their bindings Why do we need *both* rec_ids and later_ids? For monads they could be combined into a single set of variables, but not for arrows. That follows from the types of the respective feedback operators: mfix :: MonadFix m => (a -> m a) -> m a loop :: ArrowLoop a => a (b,d) (c,d) -> a b c * For mfix, the 'a' covers the union of the later_ids and the rec_ids * For 'loop', 'c' is the later_ids and 'd' is the rec_ids Note [Typing a RecStmt] ~~~~~~~~~~~~~~~~~~~~~~~ A (RecStmt stmts) types as if you had written (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) -> do { stmts ; return (v1,..vn, r1, ..., rm) }) where v1..vn are the later_ids r1..rm are the rec_ids Note [Monad Comprehensions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monad comprehensions require separate functions like 'return' and '>>=' for desugaring. These functions are stored in the statements used in monad comprehensions. For example, the 'return' of the 'LastStmt' expression is used to lift the body of the monad comprehension: [ body | stmts ] => stmts >>= \bndrs -> return body In transform and grouping statements ('then ..' and 'then group ..') the 'return' function is required for nested monad comprehensions, for example: [ body | stmts, then f, rest ] => f [ env | stmts ] >>= \bndrs -> [ body | rest ] BodyStmts require the 'Control.Monad.guard' function for boolean expressions: [ body | exp, stmts ] => guard exp >> [ body | stmts ] Parallel statements require the 'Control.Monad.Zip.mzip' function: [ body | stmts1 | stmts2 | .. ] => mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body In any other context than 'MonadComp', the fields for most of these 'SyntaxExpr's stay bottom. -} {- ************************************************************************ * * Template Haskell quotation brackets * * ************************************************************************ -} data HsSplice id = HsNativSplice -- $n(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsTypedSplice -- $$z or $$(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsUntypedSplice -- $z or $(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice id -- Splice point id -- Quoter SrcSpan -- The span of the enclosed string FastString -- The enclosed string deriving instance (Data id) => Data (HsSplice id) data UntypedSpliceFlavour = UntypedExpSplice | UntypedPatSplice | UntypedTypeSplice | UntypedDeclSplice deriving Data {- Note [Pending Splices] ~~~~~~~~~~~~~~~~~~~~~~ When we rename an untyped bracket, we name and lift out all the nested splices, so that when the typechecker hits the bracket, it can typecheck those nested splices without having to walk over the untyped bracket code. So for example [| f $(g x) |] looks like HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x))) which the renamer rewrites to HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x))) [PendingRnSplice UntypedExpSplice sn (g x)] * The 'sn' is the Name of the splice point, the SplicePointName * The PendingRnExpSplice gives the splice that splice-point name maps to; and the typechecker can now conveniently find these sub-expressions * The other copy of the splice, in the second argument of HsSpliceE in the renamed first arg of HsRnBracketOut is used only for pretty printing There are four varieties of pending splices generated by the renamer, distinguished by their UntypedSpliceFlavour * Pending expression splices (UntypedExpSplice), e.g., [|$(f x) + 2|] UntypedExpSplice is also used for * quasi-quotes, where the pending expression expands to $(quoter "...blah...") (see RnSplice.makePending, HsQuasiQuote case) * cross-stage lifting, where the pending expression expands to $(lift x) (see RnSplice.checkCrossStageLifting) * Pending pattern splices (UntypedPatSplice), e.g., [| \$(f x) -> x |] * Pending type splices (UntypedTypeSplice), e.g., [| f :: $(g x) |] * Pending declaration (UntypedDeclSplice), e.g., [| let $(f x) in ... |] There is a fifth variety of pending splice, which is generated by the type checker: * Pending *typed* expression splices, (PendingTcSplice), e.g., [||1 + $$(f 2)||] It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the output of the renamer. However, when pretty printing the output of the renamer, e.g., in a type error message, we *do not* want to print out the pending splices. In contrast, when pretty printing the output of the type checker, we *do* want to print the pending splices. So splitting them up seems to make sense, although I hate to add another constructor to HsExpr. -} data HsBracket id = ExpBr (LHsExpr id) -- [| expr |] | PatBr (LPat id) -- [p| pat |] | DecBrL [LHsDecl id] -- [d| decls |]; result of parser | DecBrG (HsGroup id) -- [d| decls |]; result of renamer | TypBr (LHsType id) -- [t| type |] | VarBr Bool id -- True: 'x, False: ''T -- (The Bool flag is used only in pprHsBracket) | TExpBr (LHsExpr id) -- [|| expr ||] | NativBr (LHsExpr id) -- [n| expr |] deriving instance (Data id) => Data (HsBracket id) {- ************************************************************************ * * \subsection{Enumerations and list comprehensions} * * ************************************************************************ -} data ArithSeqInfo id = From (LHsExpr id) | FromThen (LHsExpr id) (LHsExpr id) | FromTo (LHsExpr id) (LHsExpr id) | FromThenTo (LHsExpr id) (LHsExpr id) (LHsExpr id) deriving instance (Data id) => Data (ArithSeqInfo id) {- ************************************************************************ * * \subsection{HsMatchCtxt} * * ************************************************************************ -} data FunctionFixity = Prefix | Infix deriving (Typeable,Data,Eq) -- | Context of a Match data HsMatchContext id = FunRhs (Located id) FunctionFixity -- ^Function binding for f, fixity | LambdaExpr -- ^Patterns of a lambda | CaseAlt -- ^Patterns and guards on a case alternative | IfAlt -- ^Guards of a multi-way if alternative | ProcExpr -- ^Patterns of a proc | PatBindRhs -- ^A pattern binding eg [y] <- e = e | RecUpd -- ^Record update [used only in DsExpr to -- tell matchWrapper what sort of -- runtime error message to generate] | StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension, -- pattern guard, etc | ThPatSplice -- ^A Template Haskell pattern splice | ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |] | PatSyn -- ^A pattern synonym declaration deriving Functor deriving instance (Data id) => Data (HsMatchContext id) data HsStmtContext id = ListComp | MonadComp | PArrComp -- ^Parallel array comprehension | DoExpr -- ^do { ... } | MDoExpr -- ^mdo { ... } ie recursive do-expression | ArrowExpr -- ^do-notation in an arrow-command context | GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs | PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing | ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt | TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt deriving Functor deriving instance (Data id) => Data (HsStmtContext id)
shayan-najd/HsParser
Language/Haskell/Syntax/HsExpr.hs
gpl-3.0
39,089
0
12
11,831
3,151
1,962
1,189
306
0