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 FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} -- | Facilities for handling Futhark benchmark results. A Futhark -- benchmark program is just like a Futhark test program. module Futhark.Bench ( RunResult (..), DataResult (..), BenchResult (..), Result (..), encodeBenchResults, decodeBenchResults, binaryName, benchmarkDataset, RunOptions (..), prepareBenchmarkProgram, CompileOptions (..), ) where import Control.Applicative import Control.Monad.Except import qualified Data.Aeson as JSON import qualified Data.Aeson.Key as JSON import qualified Data.Aeson.KeyMap as JSON import qualified Data.ByteString.Char8 as SBS import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.Map as M import Data.Maybe import qualified Data.Text as T import Futhark.Server import Futhark.Test import System.Exit import System.FilePath import System.Process.ByteString (readProcessWithExitCode) import System.Timeout (timeout) -- | The runtime of a single succesful run. newtype RunResult = RunResult {runMicroseconds :: Int} deriving (Eq, Show) -- | The measurements resulting from various successful runs of a -- benchmark (same dataset). data Result = Result { runResults :: [RunResult], memoryMap :: M.Map T.Text Int, stdErr :: T.Text } deriving (Eq, Show) -- | The results for a single named dataset is either an error message, or -- runtime measurements, the number of bytes used, and the stderr that was -- produced. data DataResult = DataResult String (Either T.Text Result) deriving (Eq, Show) -- | The results for all datasets for some benchmark program. data BenchResult = BenchResult FilePath [DataResult] deriving (Eq, Show) newtype DataResults = DataResults {unDataResults :: [DataResult]} newtype BenchResults = BenchResults {unBenchResults :: [BenchResult]} instance JSON.ToJSON Result where toJSON (Result runres memmap err) = JSON.toJSON (runres, memmap, err) instance JSON.FromJSON Result where parseJSON = fmap (\(runres, memmap, err) -> Result runres memmap err) . JSON.parseJSON instance JSON.ToJSON RunResult where toJSON = JSON.toJSON . runMicroseconds instance JSON.FromJSON RunResult where parseJSON = fmap RunResult . JSON.parseJSON instance JSON.ToJSON DataResults where toJSON (DataResults rs) = JSON.object $ map dataResultJSON rs toEncoding (DataResults rs) = JSON.pairs $ mconcat $ map (uncurry (JSON..=) . dataResultJSON) rs instance JSON.FromJSON DataResults where parseJSON = JSON.withObject "datasets" $ \o -> DataResults <$> mapM datasetResult (JSON.toList o) where datasetResult (k, v) = DataResult (JSON.toString k) <$> ((Right <$> success v) <|> (Left <$> JSON.parseJSON v)) success = JSON.withObject "result" $ \o -> Result <$> o JSON..: "runtimes" <*> o JSON..: "bytes" <*> o JSON..: "stderr" dataResultJSON :: DataResult -> (JSON.Key, JSON.Value) dataResultJSON (DataResult desc (Left err)) = (JSON.fromString desc, JSON.toJSON err) dataResultJSON (DataResult desc (Right (Result runtimes bytes progerr))) = ( JSON.fromString desc, JSON.object [ ("runtimes", JSON.toJSON $ map runMicroseconds runtimes), ("bytes", JSON.toJSON bytes), ("stderr", JSON.toJSON progerr) ] ) benchResultJSON :: BenchResult -> (JSON.Key, JSON.Value) benchResultJSON (BenchResult prog r) = ( JSON.fromString prog, JSON.object [("datasets", JSON.toJSON $ DataResults r)] ) instance JSON.ToJSON BenchResults where toJSON (BenchResults rs) = JSON.object $ map benchResultJSON rs instance JSON.FromJSON BenchResults where parseJSON = JSON.withObject "benchmarks" $ \o -> BenchResults <$> mapM onBenchmark (JSON.toList o) where onBenchmark (k, v) = BenchResult (JSON.toString k) <$> JSON.withObject "benchmark" onBenchmark' v onBenchmark' o = fmap unDataResults . JSON.parseJSON =<< o JSON..: "datasets" -- | Transform benchmark results to a JSON bytestring. encodeBenchResults :: [BenchResult] -> LBS.ByteString encodeBenchResults = JSON.encode . BenchResults -- | Decode benchmark results from a JSON bytestring. decodeBenchResults :: LBS.ByteString -> Either String [BenchResult] decodeBenchResults = fmap unBenchResults . JSON.eitherDecode' --- Running benchmarks -- | How to run a benchmark. data RunOptions = RunOptions { runRuns :: Int, runTimeout :: Int, runVerbose :: Int, -- | Invoked for every runtime measured during the run. Can be -- used to provide a progress bar. runResultAction :: Maybe (Int -> IO ()) } -- | Run the benchmark program on the indicated dataset. benchmarkDataset :: Server -> RunOptions -> FutharkExe -> FilePath -> T.Text -> Values -> Maybe Success -> FilePath -> IO (Either T.Text ([RunResult], T.Text)) benchmarkDataset server opts futhark program entry input_spec expected_spec ref_out = runExceptT $ do output_types <- cmdEither $ cmdOutputs server entry input_types <- cmdEither $ cmdInputs server entry let outs = ["out" <> T.pack (show i) | i <- [0 .. length output_types -1]] ins = ["in" <> T.pack (show i) | i <- [0 .. length input_types -1]] cmdMaybe . liftIO $ cmdClear server let freeOuts = cmdMaybe (cmdFree server outs) freeIns = cmdMaybe (cmdFree server ins) loadInput = valuesAsVars server (zip ins $ map inputType input_types) futhark dir input_spec reloadInput = freeIns >> loadInput loadInput let runtime l | Just l' <- T.stripPrefix "runtime: " l, [(x, "")] <- reads $ T.unpack l' = Just x | otherwise = Nothing doRun = do call_lines <- cmdEither (cmdCall server entry outs ins) when (any inputConsumed input_types) reloadInput case mapMaybe runtime call_lines of [call_runtime] -> do liftIO $ fromMaybe (const $ pure ()) (runResultAction opts) call_runtime return (RunResult call_runtime, call_lines) [] -> throwError "Could not find runtime in output." ls -> throwError $ "Ambiguous runtimes: " <> T.pack (show ls) maybe_call_logs <- liftIO . timeout (runTimeout opts * 1000000) . runExceptT $ do -- First one uncounted warmup run. void $ cmdEither $ cmdCall server entry outs ins freeOuts xs <- replicateM (runRuns opts -1) (doRun <* freeOuts) y <- doRun pure $ xs ++ [y] call_logs <- case maybe_call_logs of Nothing -> throwError . T.pack $ "Execution exceeded " ++ show (runTimeout opts) ++ " seconds." Just x -> liftEither x freeIns report <- cmdEither $ cmdReport server vs <- readResults server outs <* freeOuts maybe_expected <- liftIO $ maybe (return Nothing) (fmap Just . getExpectedValues) expected_spec case maybe_expected of Just expected -> checkResult program expected vs Nothing -> pure () return ( map fst call_logs, T.unlines $ map (T.unlines . snd) call_logs <> report ) where getExpectedValues (SuccessValues vs) = getValues futhark dir vs getExpectedValues SuccessGenerateValues = getExpectedValues $ SuccessValues $ InFile ref_out dir = takeDirectory program -- | How to compile a benchmark. data CompileOptions = CompileOptions { compFuthark :: String, compBackend :: String, compOptions :: [String] } progNotFound :: String -> String progNotFound s = s ++ ": command not found" -- | Compile and produce reference datasets. prepareBenchmarkProgram :: MonadIO m => Maybe Int -> CompileOptions -> FilePath -> [InputOutputs] -> m (Either (String, Maybe SBS.ByteString) ()) prepareBenchmarkProgram concurrency opts program cases = do let futhark = compFuthark opts ref_res <- runExceptT $ ensureReferenceOutput concurrency (FutharkExe futhark) "c" program cases case ref_res of Left err -> return $ Left ( "Reference output generation for " ++ program ++ " failed:\n" ++ unlines (map T.unpack err), Nothing ) Right () -> do (futcode, _, futerr) <- liftIO $ readProcessWithExitCode futhark ( [compBackend opts, program, "-o", binaryName program, "--server"] <> compOptions opts ) "" case futcode of ExitSuccess -> return $ Right () ExitFailure 127 -> return $ Left (progNotFound futhark, Nothing) ExitFailure _ -> return $ Left ("Compilation of " ++ program ++ " failed:\n", Just futerr)
diku-dk/futhark
src/Futhark/Bench.hs
isc
8,612
0
23
1,927
2,459
1,287
1,172
195
6
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} -- | -- Module: Aws.Sns.Commands.ConfirmSubscription -- Copyright: Copyright © 2014 AlephCloud Systems, Inc. -- License: MIT -- Maintainer: Lars Kuhtz <[email protected]> -- Stability: experimental -- -- /API Version: 2013-03-31/ -- -- Verifies an endpoint owner's intent to receive messages by validating the -- token sent to the endpoint by an earlier Subscribe action. If the token is -- valid, the action creates a new subscription and returns its Amazon Resource -- Name (ARN). This call requires an AWS signature only when the -- AuthenticateOnUnsubscribe flag is set to "true". -- -- <http://docs.aws.amazon.com/sns/2010-03-31/APIReference/API_ConfirmSubscription.html> -- module Aws.Sns.Commands.ConfirmSubscription ( ConfirmSubscription(..) , ConfirmSubscriptionResponse(..) , ConfirmSubscriptionErrors(..) ) where import Aws.Core import Aws.General import Aws.Sns.Core import Control.Applicative import Control.Monad.Trans.Resource (throwM) import Data.Monoid import Data.String import qualified Data.Text as T import Data.Typeable import Text.XML.Cursor (($//), (&/)) import qualified Text.XML.Cursor as CU confirmSubscriptionAction :: SnsAction confirmSubscriptionAction = SnsActionConfirmSubscription -- -------------------------------------------------------------------------- -- -- Subscription Confirmation Token newtype SubscriptionConfirmationToken = SubscriptionConfirmationToken { subscriptionConfirmationTokenText :: T.Text } deriving (Show, Read, Eq, Ord, Monoid, IsString, Typeable) -- -------------------------------------------------------------------------- -- -- Confirm Subscription data ConfirmSubscription = ConfirmSubscription { confirmSubscriptionAuthenticateOnUnsubscribe:: !Bool -- ^ Disallows unauthenticated unsubscribes of the subscription. If the -- value of this parameter is true and the request has an AWS signature, -- then only the topic owner and the subscription owner can unsubscribe the -- endpoint. The unsubscribe action requires AWS authentication. , confirmSubscriptionToken :: !SubscriptionConfirmationToken -- ^ Short-lived token sent to an endpoint during the Subscribe action. , confirmSubscriptionTopicArn :: Arn -- ^ The ARN of the topic for which you wish to confirm a subscription. } deriving (Show, Read, Eq, Ord, Typeable) data ConfirmSubscriptionResponse = ConfirmSubscriptionResponse { confirmSubscriptionResSubscriptionArn :: !Arn -- ^ The ARN of the created subscription. } deriving (Show, Read, Eq, Ord, Typeable) instance ResponseConsumer r ConfirmSubscriptionResponse where type ResponseMetadata ConfirmSubscriptionResponse = SnsMetadata responseConsumer _ = snsXmlResponseConsumer p where p el = ConfirmSubscriptionResponse <$> arn el arn el = do t <- force "Missing topic ARN" $ el $// CU.laxElement "ConfirmSubscriptionResult" &/ CU.laxElement "SubscriptionArn" &/ CU.content case fromText t of Right a -> return a Left e -> throwM $ SnsResponseDecodeError $ "failed to parse subscription ARN (" <> t <> "): " <> (T.pack . show) e instance SignQuery ConfirmSubscription where type ServiceConfiguration ConfirmSubscription = SnsConfiguration signQuery ConfirmSubscription{..} = snsSignQuery SnsQuery { snsQueryMethod = Get , snsQueryAction = confirmSubscriptionAction , snsQueryParameters = authOnUnsubscribe <> [ ("Token", Just $ subscriptionConfirmationTokenText confirmSubscriptionToken) , ("TopicArn", Just $ toText confirmSubscriptionTopicArn) ] , snsQueryBody = Nothing } where authOnUnsubscribe = if confirmSubscriptionAuthenticateOnUnsubscribe then [ ("AuthenticateOnUnsubscribe", Just "true") ] else [] instance Transaction ConfirmSubscription ConfirmSubscriptionResponse instance AsMemoryResponse ConfirmSubscriptionResponse where type MemoryResponse ConfirmSubscriptionResponse = ConfirmSubscriptionResponse loadToMemory = return -- -------------------------------------------------------------------------- -- -- Errors -- -- Currently not used for requests. It's included for future usage -- and as reference. data ConfirmSubscriptionErrors = ConfirmSubscriptionAuthorizationError -- ^ Indicates that the user has been denied access to the requested resource. -- -- /Code 403/ | ConfirmSubscriptionInternalError -- ^ Indicates an internal service error. -- -- /Code 500/ | ConfirmSubscriptionInvalidParameter -- ^ Indicates that a request parameter does not comply with the associated constraints. -- -- /Code 400/ | ConfirmSubscriptionNotFound -- ^ Indicates that the requested resource does not exist. -- -- /Code 404/ | ConfirmSubscriptionSubscriptionLimitExceeded -- ^ Indicates that the customer already owns the maximum allowed number of subscriptions. -- -- /Code 403/ deriving (Show, Read, Eq, Ord, Enum, Bounded, Typeable)
alephcloud/hs-aws-sns
src/Aws/Sns/Commands/ConfirmSubscription.hs
mit
5,437
0
17
1,050
678
403
275
77
1
-- | Socket related types module Network.Anonymous.I2P.Types.Socket where import qualified Network.Socket as NS -- | Alias for a hostname type HostName = NS.HostName -- | Alias for a port number type PortNumber = NS.PortNumber -- | Socket types data SocketType = -- | Virtual streams are guaranteed to be sent reliably and in order, with -- failure and success notification as soon as it is available. Streams are -- bidirectional communication sockets between two I2P destinations, but their -- opening has to be requested by one of them. VirtualStream | -- | While I2P doesn't inherently contain a FROM address, for ease of use -- an additional layer is provided as repliable datagrams - unordered -- and unreliable messages of up to 31744 bytes that include a FROM -- address (leaving up to 1KB for header material). This FROM address -- is authenticated internally by SAM (making use of the destination's -- signing key to verify the source) and includes replay prevention. DatagramRepliable | -- | Squeezing the most out of I2P's bandwidth, SAM allows clients to send -- and receive anonymous datagrams, leaving authentication and reply -- information up to the client themselves. These datagrams are -- unreliable and unordered, and may be up to 32768 bytes. DatagramAnonymous
bitemyapp/haskell-network-anonymous-i2p
src/Network/Anonymous/I2P/Types/Socket.hs
mit
1,325
0
5
251
64
49
15
8
0
module PCProblem.Quiz where -- -- $Id$ import PCProblem.Type import PCProblem.Param import PCProblem.Generator import Inter.Types import Inter.Quiz import Challenger.Partial import Data.Array import Autolib.Reporter import Data.List (isPrefixOf) import Autolib.ToDoc import Autolib.Informed instance OrderScore PCProblem where scoringOrder _ = Increasing instance Partial PCProblem PCP Folge where describe p i = vcat [ text "Lösen Sie diese Instanz des Postschen Korrespondenz-Problems:" , nest 4 $ toDoc i ] initial p i = case do let PCP uvs = i (k, (u,v)) <- zip [1..] uvs guard $ isPrefixOf u v || isPrefixOf v u return k of [] -> [ ] -- sollte nicht passieren k : ks -> [k] -- so könnte es losgehen partial p i @ ( PCP uvs ) b = do let n = fromIntegral $ length uvs let wrong = do k <- b ; guard $ not $ 1 <= k && k <= n ; return k when ( not $ null wrong ) $ do inform $ text "Diese Indizes sind nicht erlaubt:" reject $ nest 4 $ toDoc wrong let ( us, vs ) = lr i b inform $ vcat [ text "Aus Ihrer Folge entstehen die Zeichenketten:" -- , toDoc us, toDoc vs -- fix for bug #80 , text us, text vs ] let com = common us vs urest = drop (length com) us vrest = drop (length com) vs when ( not (null urest) && not ( null vrest )) $ do reject $ vcat [ text "Die eine muß ein Präfix der anderen sein," , text "nach Löschen des gemeinsamen Präfixes" , nest 4 $ toDoc com , text "entstehen jedoch die Reste" , nest 4 $ toDoc ( urest, vrest ) ] total p i b = do when ( null b ) $ do reject $ text "Das Lösungswort darf nicht leer sein." let ( us, vs ) = lr i b assert ( us == vs ) $ text "Sind die Zeichenketten gleich?" -------------------------------------------------------------------------- make_quiz :: Make make_quiz = quiz PCProblem PCProblem.Param.g make_fixed :: Make make_fixed = direct PCProblem ( PCP [ ("bba","b"),("a","b"),("b","ab") ] )
florianpilz/autotool
src/PCProblem/Quiz.hs
gpl-2.0
2,169
27
14
662
692
356
336
-1
-1
{-# LANGUAGE TypeFamilies #-} module Lamdu.Sugar.Convert.DefExpr.OutdatedDefs ( scan ) where import Control.Applicative ((<|>)) import qualified Control.Lens.Extended as Lens import Control.Monad (foldM) import Control.Monad.Transaction (MonadTransaction(..)) import qualified Data.Map as Map import qualified Data.Monoid as Monoid import qualified Data.Set as Set import Hyper import Hyper.Syntax (funcIn, funcOut) import Hyper.Syntax.Row (RowExtend(..), freExtends, freRest) import Hyper.Syntax.Scheme (sTyp) import Lamdu.Calc.Definition (depsGlobalTypes) import Lamdu.Calc.Infer (alphaEq) import qualified Lamdu.Calc.Lens as ExprLens import qualified Lamdu.Calc.Term as V import qualified Lamdu.Calc.Type as T import qualified Lamdu.Data.Definition as Def import qualified Lamdu.Data.Ops as DataOps import qualified Lamdu.Data.Ops.Subexprs as SubExprs import Lamdu.Expr.IRef (ValI, HRef) import qualified Lamdu.Expr.IRef as ExprIRef import qualified Lamdu.Sugar.Convert.PostProcess as PostProcess import qualified Lamdu.Sugar.Convert.Type as ConvertType import Lamdu.Sugar.Internal import Lamdu.Sugar.Internal.EntityId (EntityId) import qualified Lamdu.Sugar.Internal.EntityId as EntityId import qualified Lamdu.Sugar.Types as Sugar import Revision.Deltum.Transaction (Transaction) import qualified Revision.Deltum.Transaction as Transaction import Lamdu.Prelude type T = Transaction data IsHoleArg = IsHoleArg | NotHoleArg deriving Eq argToHoleFunc :: Lens.Traversal' (Ann a # V.Term) (Ann a # V.Term) argToHoleFunc = ExprLens.valApply . Lens.filteredBy (V.appFunc . ExprLens.valHole) . V.appArg recursivelyFixExpr :: Monad m => (IsHoleArg -> Ann a # V.Term -> Maybe ((IsHoleArg -> Ann a # V.Term -> m ()) -> m ())) -> Ann a # V.Term -> m () recursivelyFixExpr mFix = go NotHoleArg where go isHoleArg expr = case mFix isHoleArg expr of Just fix -> fix go Nothing -> recurse expr recurse x = case x ^? argToHoleFunc of Just arg -> go IsHoleArg arg Nothing -> htraverse_ ( \case HWitness V.W_Term_Term -> go NotHoleArg _ -> const (pure ()) ) (x ^. hVal) changeFuncRes :: Monad m => V.Var -> Ann (HRef m) # V.Term -> T m () changeFuncRes usedDefVar = recursivelyFixExpr mFix where mFix NotHoleArg (Ann pl (V.BLeaf (V.LVar v))) | v == usedDefVar = DataOps.applyHoleTo pl & void & const & Just mFix isHoleArg (Ann pl (V.BApp (V.App (Ann _ (V.BLeaf (V.LVar v))) arg))) | v == usedDefVar = Just $ \go -> do when (isHoleArg == NotHoleArg) (void (DataOps.applyHoleTo pl)) go NotHoleArg arg mFix _ _ = Nothing -- | Only if hole not already applied to it applyHoleTo :: Monad m => Ann (HRef m) # V.Term -> T m () applyHoleTo x | Lens.has argToHoleFunc x || Lens.has ExprLens.valHole x = pure () | otherwise = x ^. hAnn & DataOps.applyHoleTo & void data RecordChange = RecordChange { fieldsAdded :: Set T.Tag , fieldsRemoved :: Set T.Tag , fieldsChanged :: Map T.Tag ArgChange } data ArgChange = ArgChange | ArgRecordChange RecordChange fixArg :: Monad m => ArgChange -> Ann (HRef m) # V.Term -> (IsHoleArg -> Ann (HRef m) # V.Term -> T m ()) -> T m () fixArg ArgChange arg go = do applyHoleTo arg go IsHoleArg arg fixArg (ArgRecordChange recChange) arg go = ( if Set.null (fieldsRemoved recChange) then arg ^. hAnn . ExprIRef.iref <$ changeFields (fieldsChanged recChange) arg go else do go IsHoleArg arg V.App <$> DataOps.newHole ?? arg ^. hAnn . ExprIRef.iref <&> V.BApp >>= ExprIRef.newValI ) >>= addFields (fieldsAdded recChange) >>= arg ^. hAnn . ExprIRef.setIref addFields :: Monad m => Set T.Tag -> ValI m -> Transaction m (ValI m) addFields fields src = foldM addField src fields where addField x tag = RowExtend tag <$> DataOps.newHole ?? x <&> V.BRecExtend >>= ExprIRef.newValI changeFields :: Monad m => Map T.Tag ArgChange -> Ann (HRef m) # V.Term -> (IsHoleArg -> Ann (HRef m) # V.Term -> T m ()) -> T m () changeFields changes arg go | Lens.hasn't traverse changes = go NotHoleArg arg | otherwise = case arg ^. hVal of V.BRecExtend (RowExtend tag fieldVal rest) -> case changes ^. Lens.at tag of Nothing -> do go NotHoleArg fieldVal changeFields changes rest go Just fieldChange -> do fixArg fieldChange fieldVal go changeFields (changes & Lens.at tag .~ Nothing) rest go _ -> fixArg ArgChange arg go changeFuncArg :: Monad m => ArgChange -> V.Var -> Ann (HRef m) # V.Term -> T m () changeFuncArg change usedDefVar = recursivelyFixExpr mFix where mFix NotHoleArg (Ann pl (V.BLeaf (V.LVar v))) | v == usedDefVar = DataOps.applyHoleTo pl & void & const & Just mFix _ (Ann _ (V.BApp (V.App (Ann _ (V.BLeaf (V.LVar v))) arg))) | v == usedDefVar = fixArg change arg & Just mFix _ _ = Nothing isPartSame :: Lens.Getting (Monoid.First (Pure # T.Type)) (Pure # T.Type) (Pure # T.Type) -> Pure # T.Scheme -> Pure # T.Scheme -> Bool isPartSame part preType newType = do prePart <- (_Pure . sTyp) (^? part) preType newPart <- (_Pure . sTyp) (^? part) newType alphaEq prePart newPart & guard & Lens.has Lens._Just argChangeType :: Pure # T.Scheme -> Pure # T.Scheme -> ArgChange argChangeType prevArg newArg = do prevProd <- prevArg ^? _Pure . sTyp . _Pure . T._TRecord . T.flatRow prevProd ^? freRest . _Pure . T._REmpty newProd <- newArg ^? _Pure . sTyp . _Pure . T._TRecord . T.flatRow newProd ^? freRest . _Pure . T._REmpty let prevTags = prevProd ^. freExtends & Map.keysSet let newTags = newProd ^. freExtends & Map.keysSet let changedTags = Map.intersectionWith fieldChange (prevProd ^. freExtends) (newProd ^. freExtends) & Map.mapMaybe id ArgRecordChange RecordChange { fieldsAdded = Set.difference newTags prevTags , fieldsRemoved = Set.difference prevTags newTags , fieldsChanged = changedTags } & pure & fromMaybe ArgChange where fieldChange prevField newField | alphaEq prevFieldScheme newFieldScheme = Nothing | otherwise = argChangeType prevFieldScheme newFieldScheme & Just where prevFieldScheme = prevArg & _Pure . sTyp .~ prevField newFieldScheme = newArg & _Pure . sTyp .~ newField fixDefExpr :: Monad m => Pure # T.Scheme -> Pure # T.Scheme -> V.Var -> Ann (HRef m) # V.Term -> T m () fixDefExpr prevType newType usedDefVar defExpr = -- Function result changed (arg is the same). changeFuncRes usedDefVar defExpr <$ guard (isPartSame (_Pure . T._TFun . funcIn) prevType newType) <|> do isPartSame (_Pure . T._TFun . funcOut) prevType newType & guard -- Function arg changed (result is the same). prevArg <- (_Pure . sTyp) (^? _Pure . T._TFun . funcIn) prevType newArg <- (_Pure . sTyp) (^? _Pure . T._TFun . funcIn) newType changeFuncArg (argChangeType prevArg newArg) usedDefVar defExpr & pure & fromMaybe (SubExprs.onGetVars (DataOps.applyHoleTo <&> void) usedDefVar defExpr) updateDefType :: Monad m => Pure # T.Scheme -> Pure # T.Scheme -> V.Var -> Def.Expr (Ann (HRef m) # V.Term) -> (Def.Expr (ValI m) -> T m ()) -> T m PostProcess.Result -> T m () updateDefType prevType newType usedDefVar defExpr setDefExpr typeCheck = do defExpr <&> (^. hAnn . ExprIRef.iref) & Def.exprFrozenDeps . depsGlobalTypes . Lens.at usedDefVar ?~ newType & setDefExpr x <- typeCheck case x of PostProcess.GoodExpr -> pure () PostProcess.BadExpr{} -> fixDefExpr prevType newType usedDefVar (defExpr ^. Def.expr) scan :: MonadTransaction n m => EntityId -> Def.Expr (Ann (HRef n) # V.Term) -> (Def.Expr (ValI n) -> T n ()) -> T n PostProcess.Result -> m (Map V.Var (Sugar.DefinitionOutdatedType InternalName (T n) ())) scan entityId defExpr setDefExpr typeCheck = defExpr ^@.. Def.exprFrozenDeps . depsGlobalTypes . Lens.itraversed & traverse (uncurry scanDef) <&> mconcat where scanDef globalVar usedType = ExprIRef.defI globalVar & Transaction.readIRef & transaction <&> (^. Def.defType) >>= processDef globalVar usedType processDef globalVar usedType newUsedDefType | alphaEq usedType newUsedDefType = pure mempty | otherwise = do usedTypeS <- ConvertType.convertScheme (EntityId.usedTypeOf entityId) usedType currentTypeS <- ConvertType.convertScheme (EntityId.currentTypeOf entityId) newUsedDefType globalVar Lens.~~> Sugar.DefinitionOutdatedType { Sugar._defTypeWhenUsed = usedTypeS , Sugar._defTypeCurrent = currentTypeS , Sugar._defTypeUseCurrent = updateDefType usedType newUsedDefType globalVar defExpr setDefExpr typeCheck } & pure
lamdu/lamdu
src/Lamdu/Sugar/Convert/DefExpr/OutdatedDefs.hs
gpl-3.0
10,061
0
20
3,142
3,163
1,604
1,559
-1
-1
main = take 100 (iterate (/. 10000.0) 1.0)
roberth/uu-helium
test/simple/correct/Underflow.hs
gpl-3.0
43
1
8
8
26
12
14
1
1
main :: Bool -> () main = \True -> ()
roberth/uu-helium
test/staticwarnings/Lambda1.hs
gpl-3.0
40
0
8
12
30
14
16
2
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -Wall -Werror #-} {-| A simple logger that reads `LogEntry` from a `TBChan` and dumps JSON-formatted strings to `stdout`. -} module GameServer.Log ( -- * Types LoggerEnv -- * Constructor & Destructor , newLog, stopLogger, fakeLogger -- * Logging functions , logInfo, logError, withLog )where import Control.Concurrent.Async (Async, async, cancel) import Control.Concurrent.Chan.Unagi (InChan, OutChan, newChan, readChan, writeChan) import Control.Monad (forever) import Control.Monad.Trans (MonadIO (..)) import Data.Aeson import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime) import System.IO (Handle, stdout) -- | Environment to control a logger thread. data LoggerEnv m = LoggerEnv { logger :: Maybe Logger , loggerId :: Text , logInfo :: forall a . (ToJSON a) => a -> m () , logError :: forall a . (ToJSON a) => a -> m () , withLog :: forall a b . (ToJSON a) => a -> m b -> m b , stopLogger :: m () } type Logger = InChan BS.ByteString fakeLogger :: (MonadIO m) => LoggerEnv m fakeLogger = LoggerEnv Nothing "foo" (const $ pure ()) (const $ pure ()) (\ _ -> id) (pure ()) -- |Starts an asynchronous log-processing thread and returns an initialised `LoggerEnv`. newLog :: (MonadIO m) => Text -> m (LoggerEnv m) newLog loggerId = liftIO $ do (inchan,outchan) <- newChan loggerThread <- async $ runLog outchan stdout let logger = Just inchan logInfo a = logEvent' inchan loggerId a logError a = logError' inchan loggerId a withLog a act = withLog' inchan loggerId a act stopLogger = stopLogger' loggerThread return $ LoggerEnv {..} runLog :: OutChan BS.ByteString -> Handle -> IO a runLog chan hdl = forever $ do toLog <- readChan chan BS.hPutStr hdl . (<> "\n") $ toLog stopLogger' :: (MonadIO m) => Async () -> m () stopLogger' = liftIO . cancel logEvent' :: (ToJSON a, MonadIO m) => Logger -> Text -> a -> m () logEvent' chan logId message = do ts <- liftIO getCurrentTime liftIO $ writeChan chan $ LBS.toStrict $ encode $ object [ "timestamp" .= ts , "loggerId" .= logId , "message" .= message ] withLog' :: (ToJSON a, MonadIO m) => Logger -> Text -> a -> m b -> m b withLog' chan logId message act = do startTime <- liftIO getCurrentTime logStart chan logId startTime message b <- act endTime <- liftIO getCurrentTime logEnd chan logId startTime endTime message pure b logStart :: (ToJSON a, MonadIO m) => Logger -> Text -> UTCTime -> a -> m () logStart chan logId ts command = liftIO $ writeChan chan $ LBS.toStrict $ encode $ object [ "timestamp" .= ts , "servicer" .= logId , "message" .= command ] logEnd :: (ToJSON a, MonadIO m) => Logger -> Text -> UTCTime -> UTCTime -> a -> m () logEnd chan logId ts en outcome = liftIO $ writeChan chan $ LBS.toStrict $ encode $ object [ "timestamp" .= en , "durationMs" .= ((diffUTCTime en ts) * 1000) , "servicer" .= logId , "message" .= outcome ] logError' :: (ToJSON a, MonadIO m) => Logger -> Text -> a -> m () logError' chan logId err = liftIO $ do ts <- liftIO getCurrentTime liftIO $ writeChan chan $ LBS.toStrict $ encode $ object [ "timestamp" .= ts , "servicer" .= logId , "error" .= err ]
abailly/hsgames
game-server/src/GameServer/Log.hs
apache-2.0
4,188
0
13
1,476
1,194
629
565
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Taken quite directly from the Peyton Jones/Lester paper. -} {-# LANGUAGE CPP #-} -- | A module concerned with finding the free variables of an expression. module CoreFVs ( -- * Free variables of expressions and binding groups exprFreeVars, exprFreeVarsDSet, exprFreeVarsList, exprFreeIds, exprFreeIdsDSet, exprFreeIdsList, exprsFreeIdsDSet, exprsFreeIdsList, exprsFreeVars, exprsFreeVarsList, bindFreeVars, -- * Selective free variables of expressions InterestingVarFun, exprSomeFreeVars, exprsSomeFreeVars, exprSomeFreeVarsList, exprsSomeFreeVarsList, -- * Free variables of Rules, Vars and Ids varTypeTyCoVars, varTypeTyCoFVs, idUnfoldingVars, idFreeVars, dIdFreeVars, bndrRuleAndUnfoldingVarsDSet, idFVs, idRuleVars, idRuleRhsVars, stableUnfoldingVars, ruleRhsFreeVars, ruleFreeVars, rulesFreeVars, rulesFreeVarsDSet, ruleLhsFreeIds, ruleLhsFreeIdsList, vectsFreeVars, expr_fvs, -- * Orphan names orphNamesOfType, orphNamesOfCo, orphNamesOfAxiom, orphNamesOfTypes, orphNamesOfCoCon, exprsOrphNames, orphNamesOfFamInst, -- * Core syntax tree annotation with free variables FVAnn, -- annotation, abstract CoreExprWithFVs, -- = AnnExpr Id FVAnn CoreExprWithFVs', -- = AnnExpr' Id FVAnn CoreBindWithFVs, -- = AnnBind Id FVAnn CoreAltWithFVs, -- = AnnAlt Id FVAnn freeVars, -- CoreExpr -> CoreExprWithFVs freeVarsBind, -- CoreBind -> DVarSet -> (DVarSet, CoreBindWithFVs) freeVarsOf, -- CoreExprWithFVs -> DIdSet freeVarsOfAnn ) where #include "HsVersions.h" import GhcPrelude import CoreSyn import Id import IdInfo import NameSet import UniqSet import Unique (Uniquable (..)) import Name import VarSet import Var import Type import TyCoRep import TyCon import CoAxiom import FamInstEnv import TysPrim( funTyConName ) import Maybes( orElse ) import Util import BasicTypes( Activation ) import Outputable import FV {- ************************************************************************ * * \section{Finding the free variables of an expression} * * ************************************************************************ This function simply finds the free variables of an expression. So far as type variables are concerned, it only finds tyvars that are * free in type arguments, * free in the type of a binder, but not those that are free in the type of variable occurrence. -} -- | Find all locally-defined free Ids or type variables in an expression -- returning a non-deterministic set. exprFreeVars :: CoreExpr -> VarSet exprFreeVars = fvVarSet . exprFVs -- | Find all locally-defined free Ids or type variables in an expression -- returning a composable FV computation. See Note [FV naming conventions] in FV -- for why export it. exprFVs :: CoreExpr -> FV exprFVs = filterFV isLocalVar . expr_fvs -- | Find all locally-defined free Ids or type variables in an expression -- returning a deterministic set. exprFreeVarsDSet :: CoreExpr -> DVarSet exprFreeVarsDSet = fvDVarSet . exprFVs -- | Find all locally-defined free Ids or type variables in an expression -- returning a deterministically ordered list. exprFreeVarsList :: CoreExpr -> [Var] exprFreeVarsList = fvVarList . exprFVs -- | Find all locally-defined free Ids in an expression exprFreeIds :: CoreExpr -> IdSet -- Find all locally-defined free Ids exprFreeIds = exprSomeFreeVars isLocalId -- | Find all locally-defined free Ids in an expression -- returning a deterministic set. exprFreeIdsDSet :: CoreExpr -> DIdSet -- Find all locally-defined free Ids exprFreeIdsDSet = exprSomeFreeVarsDSet isLocalId -- | Find all locally-defined free Ids in an expression -- returning a deterministically ordered list. exprFreeIdsList :: CoreExpr -> [Id] -- Find all locally-defined free Ids exprFreeIdsList = exprSomeFreeVarsList isLocalId -- | Find all locally-defined free Ids in several expressions -- returning a deterministic set. exprsFreeIdsDSet :: [CoreExpr] -> DIdSet -- Find all locally-defined free Ids exprsFreeIdsDSet = exprsSomeFreeVarsDSet isLocalId -- | Find all locally-defined free Ids in several expressions -- returning a deterministically ordered list. exprsFreeIdsList :: [CoreExpr] -> [Id] -- Find all locally-defined free Ids exprsFreeIdsList = exprsSomeFreeVarsList isLocalId -- | Find all locally-defined free Ids or type variables in several expressions -- returning a non-deterministic set. exprsFreeVars :: [CoreExpr] -> VarSet exprsFreeVars = fvVarSet . exprsFVs -- | Find all locally-defined free Ids or type variables in several expressions -- returning a composable FV computation. See Note [FV naming conventions] in FV -- for why export it. exprsFVs :: [CoreExpr] -> FV exprsFVs exprs = mapUnionFV exprFVs exprs -- | Find all locally-defined free Ids or type variables in several expressions -- returning a deterministically ordered list. exprsFreeVarsList :: [CoreExpr] -> [Var] exprsFreeVarsList = fvVarList . exprsFVs -- | Find all locally defined free Ids in a binding group bindFreeVars :: CoreBind -> VarSet bindFreeVars (NonRec b r) = fvVarSet $ filterFV isLocalVar $ rhs_fvs (b,r) bindFreeVars (Rec prs) = fvVarSet $ filterFV isLocalVar $ addBndrs (map fst prs) (mapUnionFV rhs_fvs prs) -- | Finds free variables in an expression selected by a predicate exprSomeFreeVars :: InterestingVarFun -- ^ Says which 'Var's are interesting -> CoreExpr -> VarSet exprSomeFreeVars fv_cand e = fvVarSet $ filterFV fv_cand $ expr_fvs e -- | Finds free variables in an expression selected by a predicate -- returning a deterministically ordered list. exprSomeFreeVarsList :: InterestingVarFun -- ^ Says which 'Var's are interesting -> CoreExpr -> [Var] exprSomeFreeVarsList fv_cand e = fvVarList $ filterFV fv_cand $ expr_fvs e -- | Finds free variables in an expression selected by a predicate -- returning a deterministic set. exprSomeFreeVarsDSet :: InterestingVarFun -- ^ Says which 'Var's are interesting -> CoreExpr -> DVarSet exprSomeFreeVarsDSet fv_cand e = fvDVarSet $ filterFV fv_cand $ expr_fvs e -- | Finds free variables in several expressions selected by a predicate exprsSomeFreeVars :: InterestingVarFun -- Says which 'Var's are interesting -> [CoreExpr] -> VarSet exprsSomeFreeVars fv_cand es = fvVarSet $ filterFV fv_cand $ mapUnionFV expr_fvs es -- | Finds free variables in several expressions selected by a predicate -- returning a deterministically ordered list. exprsSomeFreeVarsList :: InterestingVarFun -- Says which 'Var's are interesting -> [CoreExpr] -> [Var] exprsSomeFreeVarsList fv_cand es = fvVarList $ filterFV fv_cand $ mapUnionFV expr_fvs es -- | Finds free variables in several expressions selected by a predicate -- returning a deterministic set. exprsSomeFreeVarsDSet :: InterestingVarFun -- ^ Says which 'Var's are interesting -> [CoreExpr] -> DVarSet exprsSomeFreeVarsDSet fv_cand e = fvDVarSet $ filterFV fv_cand $ mapUnionFV expr_fvs e -- Comment about obselete code -- We used to gather the free variables the RULES at a variable occurrence -- with the following cryptic comment: -- "At a variable occurrence, add in any free variables of its rule rhss -- Curiously, we gather the Id's free *type* variables from its binding -- site, but its free *rule-rhs* variables from its usage sites. This -- is a little weird. The reason is that the former is more efficient, -- but the latter is more fine grained, and a makes a difference when -- a variable mentions itself one of its own rule RHSs" -- Not only is this "weird", but it's also pretty bad because it can make -- a function seem more recursive than it is. Suppose -- f = ...g... -- g = ... -- RULE g x = ...f... -- Then f is not mentioned in its own RHS, and needn't be a loop breaker -- (though g may be). But if we collect the rule fvs from g's occurrence, -- it looks as if f mentions itself. (This bites in the eftInt/eftIntFB -- code in GHC.Enum.) -- -- Anyway, it seems plain wrong. The RULE is like an extra RHS for the -- function, so its free variables belong at the definition site. -- -- Deleted code looked like -- foldVarSet add_rule_var var_itself_set (idRuleVars var) -- add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var -- | otherwise = set -- SLPJ Feb06 addBndr :: CoreBndr -> FV -> FV addBndr bndr fv fv_cand in_scope acc = (varTypeTyCoFVs bndr `unionFV` -- Include type variables in the binder's type -- (not just Ids; coercion variables too!) FV.delFV bndr fv) fv_cand in_scope acc addBndrs :: [CoreBndr] -> FV -> FV addBndrs bndrs fv = foldr addBndr fv bndrs expr_fvs :: CoreExpr -> FV expr_fvs (Type ty) fv_cand in_scope acc = tyCoFVsOfType ty fv_cand in_scope acc expr_fvs (Coercion co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc expr_fvs (Var var) fv_cand in_scope acc = FV.unitFV var fv_cand in_scope acc expr_fvs (Lit _) fv_cand in_scope acc = emptyFV fv_cand in_scope acc expr_fvs (Tick t expr) fv_cand in_scope acc = (tickish_fvs t `unionFV` expr_fvs expr) fv_cand in_scope acc expr_fvs (App fun arg) fv_cand in_scope acc = (expr_fvs fun `unionFV` expr_fvs arg) fv_cand in_scope acc expr_fvs (Lam bndr body) fv_cand in_scope acc = addBndr bndr (expr_fvs body) fv_cand in_scope acc expr_fvs (Cast expr co) fv_cand in_scope acc = (expr_fvs expr `unionFV` tyCoFVsOfCo co) fv_cand in_scope acc expr_fvs (Case scrut bndr ty alts) fv_cand in_scope acc = (expr_fvs scrut `unionFV` tyCoFVsOfType ty `unionFV` addBndr bndr (mapUnionFV alt_fvs alts)) fv_cand in_scope acc where alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs) expr_fvs (Let (NonRec bndr rhs) body) fv_cand in_scope acc = (rhs_fvs (bndr, rhs) `unionFV` addBndr bndr (expr_fvs body)) fv_cand in_scope acc expr_fvs (Let (Rec pairs) body) fv_cand in_scope acc = addBndrs (map fst pairs) (mapUnionFV rhs_fvs pairs `unionFV` expr_fvs body) fv_cand in_scope acc --------- rhs_fvs :: (Id, CoreExpr) -> FV rhs_fvs (bndr, rhs) = expr_fvs rhs `unionFV` bndrRuleAndUnfoldingFVs bndr -- Treat any RULES as extra RHSs of the binding --------- exprs_fvs :: [CoreExpr] -> FV exprs_fvs exprs = mapUnionFV expr_fvs exprs tickish_fvs :: Tickish Id -> FV tickish_fvs (Breakpoint _ ids) = FV.mkFVs ids tickish_fvs _ = emptyFV {- ************************************************************************ * * \section{Free names} * * ************************************************************************ -} -- | Finds the free /external/ names of an expression, notably -- including the names of type constructors (which of course do not show -- up in 'exprFreeVars'). exprOrphNames :: CoreExpr -> NameSet -- There's no need to delete local binders, because they will all -- be /internal/ names. exprOrphNames e = go e where go (Var v) | isExternalName n = unitNameSet n | otherwise = emptyNameSet where n = idName v go (Lit _) = emptyNameSet go (Type ty) = orphNamesOfType ty -- Don't need free tyvars go (Coercion co) = orphNamesOfCo co go (App e1 e2) = go e1 `unionNameSet` go e2 go (Lam v e) = go e `delFromNameSet` idName v go (Tick _ e) = go e go (Cast e co) = go e `unionNameSet` orphNamesOfCo co go (Let (NonRec _ r) e) = go e `unionNameSet` go r go (Let (Rec prs) e) = exprsOrphNames (map snd prs) `unionNameSet` go e go (Case e _ ty as) = go e `unionNameSet` orphNamesOfType ty `unionNameSet` unionNameSets (map go_alt as) go_alt (_,_,r) = go r -- | Finds the free /external/ names of several expressions: see 'exprOrphNames' for details exprsOrphNames :: [CoreExpr] -> NameSet exprsOrphNames es = foldr (unionNameSet . exprOrphNames) emptyNameSet es {- ********************************************************************** %* * orphNamesXXX %* * %********************************************************************* -} orphNamesOfTyCon :: TyCon -> NameSet orphNamesOfTyCon tycon = unitNameSet (getName tycon) `unionNameSet` case tyConClass_maybe tycon of Nothing -> emptyNameSet Just cls -> unitNameSet (getName cls) orphNamesOfType :: Type -> NameSet orphNamesOfType ty | Just ty' <- coreView ty = orphNamesOfType ty' -- Look through type synonyms (Trac #4912) orphNamesOfType (TyVarTy _) = emptyNameSet orphNamesOfType (LitTy {}) = emptyNameSet orphNamesOfType (TyConApp tycon tys) = orphNamesOfTyCon tycon `unionNameSet` orphNamesOfTypes tys orphNamesOfType (ForAllTy bndr res) = orphNamesOfType (binderKind bndr) `unionNameSet` orphNamesOfType res orphNamesOfType (FunTy arg res) = unitNameSet funTyConName -- NB! See Trac #8535 `unionNameSet` orphNamesOfType arg `unionNameSet` orphNamesOfType res orphNamesOfType (AppTy fun arg) = orphNamesOfType fun `unionNameSet` orphNamesOfType arg orphNamesOfType (CastTy ty co) = orphNamesOfType ty `unionNameSet` orphNamesOfCo co orphNamesOfType (CoercionTy co) = orphNamesOfCo co orphNamesOfThings :: (a -> NameSet) -> [a] -> NameSet orphNamesOfThings f = foldr (unionNameSet . f) emptyNameSet orphNamesOfTypes :: [Type] -> NameSet orphNamesOfTypes = orphNamesOfThings orphNamesOfType orphNamesOfCo :: Coercion -> NameSet orphNamesOfCo (Refl _ ty) = orphNamesOfType ty orphNamesOfCo (TyConAppCo _ tc cos) = unitNameSet (getName tc) `unionNameSet` orphNamesOfCos cos orphNamesOfCo (AppCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (ForAllCo _ kind_co co) = orphNamesOfCo kind_co `unionNameSet` orphNamesOfCo co orphNamesOfCo (FunCo _ co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (CoVarCo _) = emptyNameSet orphNamesOfCo (AxiomInstCo con _ cos) = orphNamesOfCoCon con `unionNameSet` orphNamesOfCos cos orphNamesOfCo (UnivCo p _ t1 t2) = orphNamesOfProv p `unionNameSet` orphNamesOfType t1 `unionNameSet` orphNamesOfType t2 orphNamesOfCo (SymCo co) = orphNamesOfCo co orphNamesOfCo (TransCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (NthCo _ co) = orphNamesOfCo co orphNamesOfCo (LRCo _ co) = orphNamesOfCo co orphNamesOfCo (InstCo co arg) = orphNamesOfCo co `unionNameSet` orphNamesOfCo arg orphNamesOfCo (CoherenceCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (KindCo co) = orphNamesOfCo co orphNamesOfCo (SubCo co) = orphNamesOfCo co orphNamesOfCo (AxiomRuleCo _ cs) = orphNamesOfCos cs orphNamesOfCo (HoleCo _) = emptyNameSet orphNamesOfProv :: UnivCoProvenance -> NameSet orphNamesOfProv UnsafeCoerceProv = emptyNameSet orphNamesOfProv (PhantomProv co) = orphNamesOfCo co orphNamesOfProv (ProofIrrelProv co) = orphNamesOfCo co orphNamesOfProv (PluginProv _) = emptyNameSet orphNamesOfCos :: [Coercion] -> NameSet orphNamesOfCos = orphNamesOfThings orphNamesOfCo orphNamesOfCoCon :: CoAxiom br -> NameSet orphNamesOfCoCon (CoAxiom { co_ax_tc = tc, co_ax_branches = branches }) = orphNamesOfTyCon tc `unionNameSet` orphNamesOfCoAxBranches branches orphNamesOfAxiom :: CoAxiom br -> NameSet orphNamesOfAxiom axiom = orphNamesOfTypes (concatMap coAxBranchLHS $ fromBranches $ coAxiomBranches axiom) `extendNameSet` getName (coAxiomTyCon axiom) orphNamesOfCoAxBranches :: Branches br -> NameSet orphNamesOfCoAxBranches = foldr (unionNameSet . orphNamesOfCoAxBranch) emptyNameSet . fromBranches orphNamesOfCoAxBranch :: CoAxBranch -> NameSet orphNamesOfCoAxBranch (CoAxBranch { cab_lhs = lhs, cab_rhs = rhs }) = orphNamesOfTypes lhs `unionNameSet` orphNamesOfType rhs -- | orphNamesOfAxiom collects the names of the concrete types and -- type constructors that make up the LHS of a type family instance, -- including the family name itself. -- -- For instance, given `type family Foo a b`: -- `type instance Foo (F (G (H a))) b = ...` would yield [Foo,F,G,H] -- -- Used in the implementation of ":info" in GHCi. orphNamesOfFamInst :: FamInst -> NameSet orphNamesOfFamInst fam_inst = orphNamesOfAxiom (famInstAxiom fam_inst) {- ************************************************************************ * * \section[freevars-everywhere]{Attaching free variables to every sub-expression} * * ************************************************************************ -} -- | Those variables free in the right hand side of a rule returned as a -- non-deterministic set ruleRhsFreeVars :: CoreRule -> VarSet ruleRhsFreeVars (BuiltinRule {}) = noFVs ruleRhsFreeVars (Rule { ru_fn = _, ru_bndrs = bndrs, ru_rhs = rhs }) = fvVarSet $ filterFV isLocalVar $ addBndrs bndrs (expr_fvs rhs) -- See Note [Rule free var hack] -- | Those variables free in the both the left right hand sides of a rule -- returned as a non-deterministic set ruleFreeVars :: CoreRule -> VarSet ruleFreeVars = fvVarSet . ruleFVs -- | Those variables free in the both the left right hand sides of a rule -- returned as FV computation ruleFVs :: CoreRule -> FV ruleFVs (BuiltinRule {}) = emptyFV ruleFVs (Rule { ru_fn = _do_not_include -- See Note [Rule free var hack] , ru_bndrs = bndrs , ru_rhs = rhs, ru_args = args }) = filterFV isLocalVar $ addBndrs bndrs (exprs_fvs (rhs:args)) -- | Those variables free in the both the left right hand sides of rules -- returned as FV computation rulesFVs :: [CoreRule] -> FV rulesFVs = mapUnionFV ruleFVs -- | Those variables free in the both the left right hand sides of rules -- returned as a deterministic set rulesFreeVarsDSet :: [CoreRule] -> DVarSet rulesFreeVarsDSet rules = fvDVarSet $ rulesFVs rules idRuleRhsVars :: (Activation -> Bool) -> Id -> VarSet -- Just the variables free on the *rhs* of a rule idRuleRhsVars is_active id = mapUnionVarSet get_fvs (idCoreRules id) where get_fvs (Rule { ru_fn = fn, ru_bndrs = bndrs , ru_rhs = rhs, ru_act = act }) | is_active act -- See Note [Finding rule RHS free vars] in OccAnal.hs = delOneFromUniqSet_Directly fvs (getUnique fn) -- Note [Rule free var hack] where fvs = fvVarSet $ filterFV isLocalVar $ addBndrs bndrs (expr_fvs rhs) get_fvs _ = noFVs -- | Those variables free in the right hand side of several rules rulesFreeVars :: [CoreRule] -> VarSet rulesFreeVars rules = mapUnionVarSet ruleFreeVars rules ruleLhsFreeIds :: CoreRule -> VarSet -- ^ This finds all locally-defined free Ids on the left hand side of a rule -- and returns them as a non-deterministic set ruleLhsFreeIds = fvVarSet . ruleLhsFVIds ruleLhsFreeIdsList :: CoreRule -> [Var] -- ^ This finds all locally-defined free Ids on the left hand side of a rule -- and returns them as a determinisitcally ordered list ruleLhsFreeIdsList = fvVarList . ruleLhsFVIds ruleLhsFVIds :: CoreRule -> FV -- ^ This finds all locally-defined free Ids on the left hand side of a rule -- and returns an FV computation ruleLhsFVIds (BuiltinRule {}) = emptyFV ruleLhsFVIds (Rule { ru_bndrs = bndrs, ru_args = args }) = filterFV isLocalId $ addBndrs bndrs (exprs_fvs args) {- Note [Rule free var hack] (Not a hack any more) ~~~~~~~~~~~~~~~~~~~~~~~~~ We used not to include the Id in its own rhs free-var set. Otherwise the occurrence analyser makes bindings recursive: f x y = x+y RULE: f (f x y) z ==> f x (f y z) However, the occurrence analyser distinguishes "non-rule loop breakers" from "rule-only loop breakers" (see BasicTypes.OccInfo). So it will put this 'f' in a Rec block, but will mark the binding as a non-rule loop breaker, which is perfectly inlinable. -} -- |Free variables of a vectorisation declaration vectsFreeVars :: [CoreVect] -> VarSet vectsFreeVars = mapUnionVarSet vectFreeVars where vectFreeVars (Vect _ rhs) = fvVarSet $ filterFV isLocalId $ expr_fvs rhs vectFreeVars (NoVect _) = noFVs vectFreeVars (VectType _ _ _) = noFVs vectFreeVars (VectClass _) = noFVs vectFreeVars (VectInst _) = noFVs -- this function is only concerned with values, not types {- ************************************************************************ * * \section[freevars-everywhere]{Attaching free variables to every sub-expression} * * ************************************************************************ The free variable pass annotates every node in the expression with its NON-GLOBAL free variables and type variables. -} type FVAnn = DVarSet -- | Every node in a binding group annotated with its -- (non-global) free variables, both Ids and TyVars, and type. type CoreBindWithFVs = AnnBind Id FVAnn -- | Every node in an expression annotated with its -- (non-global) free variables, both Ids and TyVars, and type. type CoreExprWithFVs = AnnExpr Id FVAnn type CoreExprWithFVs' = AnnExpr' Id FVAnn -- | Every node in an expression annotated with its -- (non-global) free variables, both Ids and TyVars, and type. type CoreAltWithFVs = AnnAlt Id FVAnn freeVarsOf :: CoreExprWithFVs -> DIdSet -- ^ Inverse function to 'freeVars' freeVarsOf (fvs, _) = fvs -- | Extract the vars reported in a FVAnn freeVarsOfAnn :: FVAnn -> DIdSet freeVarsOfAnn fvs = fvs noFVs :: VarSet noFVs = emptyVarSet aFreeVar :: Var -> DVarSet aFreeVar = unitDVarSet unionFVs :: DVarSet -> DVarSet -> DVarSet unionFVs = unionDVarSet unionFVss :: [DVarSet] -> DVarSet unionFVss = unionDVarSets delBindersFV :: [Var] -> DVarSet -> DVarSet delBindersFV bs fvs = foldr delBinderFV fvs bs delBinderFV :: Var -> DVarSet -> DVarSet -- This way round, so we can do it multiple times using foldr -- (b `delBinderFV` s) -- * removes the binder b from the free variable set s, -- * AND *adds* to s the free variables of b's type -- -- This is really important for some lambdas: -- In (\x::a -> x) the only mention of "a" is in the binder. -- -- Also in -- let x::a = b in ... -- we should really note that "a" is free in this expression. -- It'll be pinned inside the /\a by the binding for b, but -- it seems cleaner to make sure that a is in the free-var set -- when it is mentioned. -- -- This also shows up in recursive bindings. Consider: -- /\a -> letrec x::a = x in E -- Now, there are no explicit free type variables in the RHS of x, -- but nevertheless "a" is free in its definition. So we add in -- the free tyvars of the types of the binders, and include these in the -- free vars of the group, attached to the top level of each RHS. -- -- This actually happened in the defn of errorIO in IOBase.hs: -- errorIO (ST io) = case (errorIO# io) of -- _ -> bottom -- where -- bottom = bottom -- Never evaluated delBinderFV b s = (s `delDVarSet` b) `unionFVs` dVarTypeTyCoVars b -- Include coercion variables too! varTypeTyCoVars :: Var -> TyCoVarSet -- Find the type/kind variables free in the type of the id/tyvar varTypeTyCoVars var = fvVarSet $ varTypeTyCoFVs var dVarTypeTyCoVars :: Var -> DTyCoVarSet -- Find the type/kind/coercion variables free in the type of the id/tyvar dVarTypeTyCoVars var = fvDVarSet $ varTypeTyCoFVs var varTypeTyCoFVs :: Var -> FV varTypeTyCoFVs var = tyCoFVsOfType (varType var) idFreeVars :: Id -> VarSet idFreeVars id = ASSERT( isId id) fvVarSet $ idFVs id dIdFreeVars :: Id -> DVarSet dIdFreeVars id = fvDVarSet $ idFVs id idFVs :: Id -> FV -- Type variables, rule variables, and inline variables idFVs id = ASSERT( isId id) varTypeTyCoFVs id `unionFV` bndrRuleAndUnfoldingFVs id bndrRuleAndUnfoldingVarsDSet :: Id -> DVarSet bndrRuleAndUnfoldingVarsDSet id = fvDVarSet $ bndrRuleAndUnfoldingFVs id bndrRuleAndUnfoldingFVs :: Id -> FV bndrRuleAndUnfoldingFVs id | isId id = idRuleFVs id `unionFV` idUnfoldingFVs id | otherwise = emptyFV idRuleVars ::Id -> VarSet -- Does *not* include CoreUnfolding vars idRuleVars id = fvVarSet $ idRuleFVs id idRuleFVs :: Id -> FV idRuleFVs id = ASSERT( isId id) FV.mkFVs (dVarSetElems $ ruleInfoFreeVars (idSpecialisation id)) idUnfoldingVars :: Id -> VarSet -- Produce free vars for an unfolding, but NOT for an ordinary -- (non-inline) unfolding, since it is a dup of the rhs -- and we'll get exponential behaviour if we look at both unf and rhs! -- But do look at the *real* unfolding, even for loop breakers, else -- we might get out-of-scope variables idUnfoldingVars id = fvVarSet $ idUnfoldingFVs id idUnfoldingFVs :: Id -> FV idUnfoldingFVs id = stableUnfoldingFVs (realIdUnfolding id) `orElse` emptyFV stableUnfoldingVars :: Unfolding -> Maybe VarSet stableUnfoldingVars unf = fvVarSet `fmap` stableUnfoldingFVs unf stableUnfoldingFVs :: Unfolding -> Maybe FV stableUnfoldingFVs unf = case unf of CoreUnfolding { uf_tmpl = rhs, uf_src = src } | isStableSource src -> Just (filterFV isLocalVar $ expr_fvs rhs) DFunUnfolding { df_bndrs = bndrs, df_args = args } -> Just (filterFV isLocalVar $ FV.delFVs (mkVarSet bndrs) $ exprs_fvs args) -- DFuns are top level, so no fvs from types of bndrs _other -> Nothing {- ************************************************************************ * * \subsection{Free variables (and types)} * * ************************************************************************ -} freeVarsBind :: CoreBind -> DVarSet -- Free vars of scope of binding -> (CoreBindWithFVs, DVarSet) -- Return free vars of binding + scope freeVarsBind (NonRec binder rhs) body_fvs = ( AnnNonRec binder rhs2 , freeVarsOf rhs2 `unionFVs` body_fvs2 `unionFVs` bndrRuleAndUnfoldingVarsDSet binder ) where rhs2 = freeVars rhs body_fvs2 = binder `delBinderFV` body_fvs freeVarsBind (Rec binds) body_fvs = ( AnnRec (binders `zip` rhss2) , delBindersFV binders all_fvs ) where (binders, rhss) = unzip binds rhss2 = map freeVars rhss rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2 binders_fvs = fvDVarSet $ mapUnionFV bndrRuleAndUnfoldingFVs binders all_fvs = rhs_body_fvs `unionFVs` binders_fvs -- The "delBinderFV" happens after adding the idSpecVars, -- since the latter may add some of the binders as fvs freeVars :: CoreExpr -> CoreExprWithFVs -- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node freeVars = go where go :: CoreExpr -> CoreExprWithFVs go (Var v) | isLocalVar v = (aFreeVar v `unionFVs` ty_fvs, AnnVar v) | otherwise = (emptyDVarSet, AnnVar v) where ty_fvs = dVarTypeTyCoVars v -- Do we need this? go (Lit lit) = (emptyDVarSet, AnnLit lit) go (Lam b body) = ( b_fvs `unionFVs` (b `delBinderFV` body_fvs) , AnnLam b body' ) where body'@(body_fvs, _) = go body b_ty = idType b b_fvs = tyCoVarsOfTypeDSet b_ty go (App fun arg) = ( freeVarsOf fun' `unionFVs` freeVarsOf arg' , AnnApp fun' arg' ) where fun' = go fun arg' = go arg go (Case scrut bndr ty alts) = ( (bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyCoVarsOfTypeDSet ty -- don't need to look at (idType bndr) -- b/c that's redundant with scrut , AnnCase scrut2 bndr ty alts2 ) where scrut2 = go scrut (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts alts_fvs = unionFVss alts_fvs_s fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2), (con, args, rhs2)) where rhs2 = go rhs go (Let bind body) = (bind_fvs, AnnLet bind2 body2) where (bind2, bind_fvs) = freeVarsBind bind (freeVarsOf body2) body2 = go body go (Cast expr co) = ( freeVarsOf expr2 `unionFVs` cfvs , AnnCast expr2 (cfvs, co) ) where expr2 = go expr cfvs = tyCoVarsOfCoDSet co go (Tick tickish expr) = ( tickishFVs tickish `unionFVs` freeVarsOf expr2 , AnnTick tickish expr2 ) where expr2 = go expr tickishFVs (Breakpoint _ ids) = mkDVarSet ids tickishFVs _ = emptyDVarSet go (Type ty) = (tyCoVarsOfTypeDSet ty, AnnType ty) go (Coercion co) = (tyCoVarsOfCoDSet co, AnnCoercion co)
shlevy/ghc
compiler/coreSyn/CoreFVs.hs
bsd-3-clause
30,461
0
14
7,644
5,449
2,933
2,516
408
11
{-# LANGUAGE CPP #-} {-# LANGUAGE MultiParamTypeClasses #-} -- for 'Bind' class. {-# LANGUAGE ConstraintKinds #-} -- for 'Bind' class. {-# LANGUAGE TypeFamilies #-} -- for 'Bind' class. {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeOperators #-} -- For ':*:' instance and others. #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) -- Some of the constraints may be unnecessary, but they are intentional. -- This is especially true for the 'Fail' instances. {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif -- | Representation of supermonads in Haskell. module Control.Super.Monad ( -- * Supermonads Bind(..), Return(..), Fail(..) -- * Super-Applicatives , Applicative(..), pure , Functor(..) -- * Conveniences , Monad ) where import Prelude ( String , Maybe(..), Either(..) , Functor(..) , (.), ($), const, id ) import qualified Prelude as P import Data.Functor.Identity ( Identity ) import GHC.Exts ( Constraint ) -- To define standard instances: import qualified Data.Monoid as Mon import qualified Data.Proxy as Proxy import qualified Data.Functor.Product as Product import qualified Data.Functor.Compose as Compose #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) import qualified Data.Complex as Complex import qualified Data.Semigroup as Semigroup import qualified Data.List.NonEmpty as NonEmpty #endif import qualified Control.Arrow as Arrow import qualified Control.Applicative as App import qualified Control.Monad.ST as ST import qualified Control.Monad.ST.Lazy as STL import qualified Text.ParserCombinators.ReadP as Read import qualified Text.ParserCombinators.ReadPrec as Read import qualified GHC.Conc as STM #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) import qualified GHC.Generics as Generics #endif -- To define "transformers" instances: import qualified Control.Monad.Trans.Cont as Cont import qualified Control.Monad.Trans.Except as Except import qualified Control.Monad.Trans.Identity as Identity import qualified Control.Monad.Trans.Maybe as Maybe import qualified Control.Monad.Trans.RWS.Lazy as RWSL import qualified Control.Monad.Trans.RWS.Strict as RWSS import qualified Control.Monad.Trans.Reader as Reader import qualified Control.Monad.Trans.State.Lazy as StateL import qualified Control.Monad.Trans.State.Strict as StateS import qualified Control.Monad.Trans.Writer.Lazy as WriterL import qualified Control.Monad.Trans.Writer.Strict as WriterS -- ----------------------------------------------------------------------------- -- Super-Applicative Type Class -- ----------------------------------------------------------------------------- infixl 4 <*>, <*, *> -- | TODO class (Functor m, Functor n, Functor p) => Applicative m n p where type ApplicativeCts m n p :: Constraint type ApplicativeCts m n p = () (<*>) :: (ApplicativeCts m n p) => m (a -> b) -> n a -> p b (*>) :: (ApplicativeCts m n p) => m a -> n b -> p b ma *> nb = (id <$ ma) <*> nb (<*) :: (ApplicativeCts m n p) => m a -> n b -> p a ma <* nb = fmap const ma <*> nb -- | 'pure' is defined in terms of return. pure :: (Return f, ReturnCts f) => a -> f a pure = return -- Standard Instances ---------------------------------------------------------- instance Applicative ((->) r) ((->) r) ((->) r) where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Identity Identity Identity where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative [] [] [] where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Maybe Maybe Maybe where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative P.IO P.IO P.IO where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative (Either e) (Either e) (Either e) where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Mon.First Mon.First Mon.First where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Mon.Last Mon.Last Mon.Last where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Applicative Mon.Sum Mon.Sum Mon.Sum where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Mon.Product Mon.Product Mon.Product where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Mon.Dual Mon.Dual Mon.Dual where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) #endif instance (Applicative m n p) => Applicative (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) where type ApplicativeCts (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) = ApplicativeCts m n p mf <*> na = Mon.Alt $ (Mon.getAlt mf) <*> (Mon.getAlt na) mf *> na = Mon.Alt $ (Mon.getAlt mf) *> (Mon.getAlt na) mf <* na = Mon.Alt $ (Mon.getAlt mf) <* (Mon.getAlt na) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Applicative Semigroup.Min Semigroup.Min Semigroup.Min where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Semigroup.Max Semigroup.Max Semigroup.Max where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Semigroup.Option Semigroup.Option Semigroup.Option where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Semigroup.First Semigroup.First Semigroup.First where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Semigroup.Last Semigroup.Last Semigroup.Last where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) #endif instance Applicative Proxy.Proxy Proxy.Proxy Proxy.Proxy where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Applicative Complex.Complex Complex.Complex Complex.Complex where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative NonEmpty.NonEmpty NonEmpty.NonEmpty NonEmpty.NonEmpty where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) #endif instance (Applicative m1 n1 p1, Applicative m2 n2 p2) => Applicative (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) where type ApplicativeCts (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) = (ApplicativeCts m1 n1 p1, ApplicativeCts m2 n2 p2) Product.Pair m1 m2 <*> Product.Pair n1 n2 = Product.Pair (m1 <*> n1) (m2 <*> n2) Product.Pair m1 m2 *> Product.Pair n1 n2 = Product.Pair (m1 *> n1) (m2 *> n2) Product.Pair m1 m2 <* Product.Pair n1 n2 = Product.Pair (m1 <* n1) (m2 <* n2) instance (Applicative f g h, Applicative f' g' h') => Applicative (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') where type ApplicativeCts (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') = (ApplicativeCts f g h, ApplicativeCts f' g' h') Compose.Compose f <*> Compose.Compose x = Compose.Compose $ fmap (<*>) f <*> x Compose.Compose f *> Compose.Compose x = Compose.Compose $ fmap ( *>) f <*> x Compose.Compose f <* Compose.Compose x = Compose.Compose $ fmap (<* ) f <*> x instance Applicative Read.ReadP Read.ReadP Read.ReadP where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative Read.ReadPrec Read.ReadPrec Read.ReadPrec where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative (ST.ST s) (ST.ST s) (ST.ST s) where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance Applicative (STL.ST s) (STL.ST s) (STL.ST s) where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance (Arrow.Arrow a) => Applicative (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) -- | TODO / FIXME: The wrapped monad instances for 'Functor' and 'P.Monad' are both -- based on @m@ being a monad, although the functor instance should only be -- dependend on @m@ being a functor (as can be seen below). This can only be -- fixed by either giving a custom version of 'App.WrappedMonad' here or by fixing -- the version of 'App.WrappedMonad' in base. -- Once this issue is fixed we can replace the 'P.Monad' constraint -- with a 'Functor' constraint. -- -- > instance (Functor m) => Functor (App.WrappedMonad m) where -- > fmap f m = App.WrapMonad $ fmap (App.unwrapMonad m) f -- instance (Applicative m m m, P.Monad m) => Applicative (App.WrappedMonad m) (App.WrappedMonad m) (App.WrappedMonad m) where type ApplicativeCts (App.WrappedMonad m) (App.WrappedMonad m) (App.WrappedMonad m) = ApplicativeCts m m m mf <*> na = App.WrapMonad $ (App.unwrapMonad mf) <*> (App.unwrapMonad na) mf *> na = App.WrapMonad $ (App.unwrapMonad mf) *> (App.unwrapMonad na) mf <* na = App.WrapMonad $ (App.unwrapMonad mf) <* (App.unwrapMonad na) instance Applicative STM.STM STM.STM STM.STM where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Applicative Generics.U1 Generics.U1 Generics.U1 where (<*>) = (P.<*>) (<*) = (P.<*) (*>) = (P.*>) instance (Applicative f g h) => Applicative (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) where type ApplicativeCts (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) = ApplicativeCts f g h (Generics.Rec1 mf) <*> (Generics.Rec1 ma) = Generics.Rec1 $ mf <*> ma (Generics.Rec1 mf) *> (Generics.Rec1 ma) = Generics.Rec1 $ mf *> ma (Generics.Rec1 mf) <* (Generics.Rec1 ma) = Generics.Rec1 $ mf <* ma instance (Applicative f g h, Applicative f' g' h') => Applicative (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') where type ApplicativeCts (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') = (ApplicativeCts f g h, ApplicativeCts f' g' h') (f Generics.:*: g) <*> (f' Generics.:*: g') = (f <*> f') Generics.:*: (g <*> g') (f Generics.:*: g) *> (f' Generics.:*: g') = (f *> f') Generics.:*: (g *> g') (f Generics.:*: g) <* (f' Generics.:*: g') = (f <* f') Generics.:*: (g <* g') instance (Applicative f g h, Applicative f' g' h') => Applicative (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') where type ApplicativeCts (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') = (ApplicativeCts f g h, ApplicativeCts f' g' h') (Generics.Comp1 mf) <*> (Generics.Comp1 ma) = Generics.Comp1 $ fmap (<*>) mf <*> ma instance Applicative f g h => Applicative (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) where type ApplicativeCts (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) = ApplicativeCts f g h (Generics.M1 mf) <*> (Generics.M1 ma) = Generics.M1 $ mf <*> ma (Generics.M1 mf) *> (Generics.M1 ma) = Generics.M1 $ mf *> ma (Generics.M1 mf) <* (Generics.M1 ma) = Generics.M1 $ mf <* ma #endif -- "transformers" package instances: ------------------------------------------- -- Continuations are so wierd... -- | TODO / FIXME: Still need to figure out how and if we can generalize the continuation implementation. instance Applicative (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) where type ApplicativeCts (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) = () f <*> a = Cont.ContT $ \ c -> Cont.runContT f $ \ g -> Cont.runContT a (c . g) {-# INLINE (<*>) #-} instance (Applicative m n p) => Applicative (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) where type ApplicativeCts (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) = (ApplicativeCts m n p) Except.ExceptT f <*> Except.ExceptT v = Except.ExceptT $ fmap (<*>) f <*> v {-# INLINEABLE (<*>) #-} instance (Applicative m n p) => Applicative (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) where type ApplicativeCts (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) = (ApplicativeCts m n p) Identity.IdentityT m <*> Identity.IdentityT k = Identity.IdentityT $ m <*> k {-# INLINE (<*>) #-} instance (Applicative m n p) => Applicative (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) where type ApplicativeCts (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) = (ApplicativeCts m n p) Maybe.MaybeT f <*> Maybe.MaybeT x = Maybe.MaybeT $ fmap (<*>) f <*> x {-# INLINE (<*>) #-} instance (P.Monoid w, Bind m n p) => Applicative (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) where type ApplicativeCts (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) = (BindCts m n p) RWSL.RWST mf <*> RWSL.RWST ma = RWSL.RWST $ \r s -> mf r s >>= \ ~(f, s', w) -> fmap (\ ~(a, s'', w') -> (f a, s'', P.mappend w w')) (ma r s') {-# INLINE (<*>) #-} instance (P.Monoid w, Bind m n p) => Applicative (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) where type ApplicativeCts (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) = (BindCts m n p) RWSS.RWST mf <*> RWSS.RWST ma = RWSS.RWST $ \r s -> mf r s >>= \ (f, s', w) -> fmap (\ (a, s'', w') -> (f a, s'', P.mappend w w')) (ma r s') {-# INLINE (<*>) #-} instance (Applicative m n p) => Applicative (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) where type ApplicativeCts (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) = (ApplicativeCts m n p) Reader.ReaderT mf <*> Reader.ReaderT ma = Reader.ReaderT $ \r -> mf r <*> ma r {-# INLINE (<*>) #-} instance (Bind m n p) => Applicative (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) where type ApplicativeCts (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) = (BindCts m n p) StateL.StateT mf <*> StateL.StateT ma = StateL.StateT $ \s -> mf s >>= \ ~(f, s') -> fmap (\ ~(a, s'') -> (f a, s'')) (ma s') {-# INLINE (<*>) #-} instance (Bind m n p) => Applicative (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) where type ApplicativeCts (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) = (BindCts m n p) StateS.StateT mf <*> StateS.StateT ma = StateS.StateT $ \s -> mf s >>= \ (f, s') -> fmap (\ (a, s'') -> (f a, s'')) (ma s') {-# INLINE (<*>) #-} instance (P.Monoid w, Applicative m n p) => Applicative (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) where type ApplicativeCts (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) = (ApplicativeCts m n p) WriterL.WriterT mf <*> WriterL.WriterT ma = WriterL.WriterT $ fmap (\ ~(f, w) ~(a, w') -> (f a, P.mappend w w')) mf <*> ma {-# INLINE (<*>) #-} instance (P.Monoid w, Applicative m n p) => Applicative (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) where type ApplicativeCts (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) = (ApplicativeCts m n p) WriterS.WriterT mf <*> WriterS.WriterT ma = WriterS.WriterT $ fmap (\ (f, w) (a, w') -> (f a, P.mappend w w')) mf <*> ma {-# INLINE (<*>) #-} -- ----------------------------------------------------------------------------- -- Supermonad Type Class - Bind -- ----------------------------------------------------------------------------- infixl 1 >>, >>= -- | Representation of bind operations for supermonads. -- A proper supermonad consists of an instance -- for 'Bind', 'Return' and optionally 'Fail'. -- -- The instances are required to follow a certain scheme. -- If the type constructor of your supermonad is @M@ there -- may only be exactly one 'Bind' and one 'Return' instance -- that look as follows: -- -- > instance Bind (M ...) (M ...) (M ...) where -- > ... -- > instance Return (M ...) where -- > ... -- -- This is enforced by the plugin. A compilation error will -- result from either instance missing or multiple instances -- for @M@. -- -- For supermonads we expect the usual monad laws to hold: -- -- * @'return' a '>>=' k = k a@ -- * @m '>>=' 'return' = m@ -- * @m '>>=' (\\x -> k x '>>=' h) = (m '>>=' k) '>>=' h@ -- * @'fmap' f xs = xs '>>=' 'return' . f@ -- class (Functor m, Functor n, Functor p) => Bind m n p where type BindCts m n p :: Constraint type BindCts m n p = () (>>=) :: (BindCts m n p) => m a -> (a -> n b) -> p b (>>) :: (BindCts m n p) => m a -> n b -> p b ma >> mb = ma >>= const mb instance Bind ((->) r) ((->) r) ((->) r) where (>>=) = (P.>>=) instance Bind Identity Identity Identity where (>>=) = (P.>>=) instance Bind [] [] [] where (>>=) = (P.>>=) instance Bind P.Maybe P.Maybe P.Maybe where (>>=) = (P.>>=) instance Bind P.IO P.IO P.IO where (>>=) = (P.>>=) instance Bind (P.Either e) (P.Either e) (P.Either e) where (>>=) = (P.>>=) instance Bind Mon.First Mon.First Mon.First where (>>=) = (P.>>=) instance Bind Mon.Last Mon.Last Mon.Last where (>>=) = (P.>>=) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Bind Mon.Sum Mon.Sum Mon.Sum where (>>=) = (P.>>=) instance Bind Mon.Product Mon.Product Mon.Product where (>>=) = (P.>>=) instance Bind Mon.Dual Mon.Dual Mon.Dual where (>>=) = (P.>>=) #endif instance (Bind m n p) => Bind (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) where type BindCts (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) = BindCts m n p m >>= f = Mon.Alt $ (Mon.getAlt m) >>= (Mon.getAlt . f) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Bind Semigroup.Min Semigroup.Min Semigroup.Min where (>>=) = (P.>>=) instance Bind Semigroup.Max Semigroup.Max Semigroup.Max where (>>=) = (P.>>=) instance Bind Semigroup.Option Semigroup.Option Semigroup.Option where (>>=) = (P.>>=) instance Bind Semigroup.First Semigroup.First Semigroup.First where (>>=) = (P.>>=) instance Bind Semigroup.Last Semigroup.Last Semigroup.Last where (>>=) = (P.>>=) #endif instance Bind Proxy.Proxy Proxy.Proxy Proxy.Proxy where (>>=) = (P.>>=) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Bind Complex.Complex Complex.Complex Complex.Complex where (>>=) = (P.>>=) instance Bind NonEmpty.NonEmpty NonEmpty.NonEmpty NonEmpty.NonEmpty where (>>=) = (P.>>=) #endif instance (Bind m1 n1 p1, Bind m2 n2 p2) => Bind (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) where type BindCts (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) = (BindCts m1 n1 p1, BindCts m2 n2 p2) Product.Pair m1 m2 >>= f = Product.Pair (m1 >>= (fstP . f)) (m2 >>= (sndP . f)) where fstP (Product.Pair a _) = a sndP (Product.Pair _ b) = b instance Bind Read.ReadP Read.ReadP Read.ReadP where (>>=) = (P.>>=) instance Bind Read.ReadPrec Read.ReadPrec Read.ReadPrec where (>>=) = (P.>>=) instance Bind (ST.ST s) (ST.ST s) (ST.ST s) where (>>=) = (P.>>=) instance Bind (STL.ST s) (STL.ST s) (STL.ST s) where (>>=) = (P.>>=) instance (Arrow.ArrowApply a) => Bind (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) where (>>=) = (P.>>=) -- | TODO / FIXME: The wrapped monad instances for 'Functor' and 'P.Monad' are both -- based on @m@ being a monad, although the functor instance should only be -- dependend on @m@ being a functor (as can be seen below). This can only be -- fixed by either giving a custom version of 'App.WrappedMonad' here or by fixing -- the version of 'App.WrappedMonad' in base. -- Once this issue is fixed we can replace the 'P.Monad' constraint -- with a 'Functor' constraint. -- -- > instance (Functor m) => Functor (App.WrappedMonad m) where -- > fmap f m = App.WrapMonad $ fmap (App.unwrapMonad m) f -- instance (Bind m m m, P.Monad m) => Bind (App.WrappedMonad m) (App.WrappedMonad m) (App.WrappedMonad m) where type BindCts (App.WrappedMonad m) (App.WrappedMonad m) (App.WrappedMonad m) = BindCts m m m m >>= f = App.WrapMonad $ (App.unwrapMonad m) >>= (App.unwrapMonad . f) instance Bind STM.STM STM.STM STM.STM where (>>=) = (P.>>=) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Bind Generics.U1 Generics.U1 Generics.U1 where (>>=) = (P.>>=) instance (Bind m n p) => Bind (Generics.Rec1 m) (Generics.Rec1 n) (Generics.Rec1 p) where type BindCts (Generics.Rec1 m) (Generics.Rec1 n) (Generics.Rec1 p) = BindCts m n p (Generics.Rec1 mf) >>= f = Generics.Rec1 $ mf >>= (Generics.unRec1 . f) instance (Bind f g h, Bind f' g' h') => Bind (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') where type BindCts (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') = (BindCts f g h, BindCts f' g' h') (f Generics.:*: g) >>= m = (f >>= \a -> let (f' Generics.:*: _g') = m a in f') Generics.:*: (g >>= \a -> let (_f' Generics.:*: g') = m a in g') instance Bind f g h => Bind (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) where type BindCts (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) = BindCts f g h (Generics.M1 ma) >>= f = Generics.M1 $ ma >>= Generics.unM1 . f #endif -- "transformers" package instances: ------------------------------------------- -- Continuations are so wierd... -- | TODO / FIXME: Still need to figure out how and if we can generalize the continuation implementation. instance {- (Bind m n p) => -} Bind (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) where type BindCts (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) = () -- (BindCts m n p) m >>= k = Cont.ContT $ \ c -> Cont.runContT m (\ x -> Cont.runContT (k x) c) {-# INLINE (>>=) #-} instance (Bind m n p, Return n) => Bind (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) where type BindCts (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) = (BindCts m n p, ReturnCts n) m >>= k = Except.ExceptT $ Except.runExceptT m >>= \ a -> case a of Left e -> return (Left e) Right x -> Except.runExceptT (k x) {-# INLINE (>>=) #-} instance (Bind m n p) => Bind (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) where type BindCts (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) = (BindCts m n p) m >>= k = Identity.IdentityT $ Identity.runIdentityT m >>= (Identity.runIdentityT . k) {-# INLINE (>>=) #-} instance (Return n, Bind m n p) => Bind (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) where type BindCts (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) = (ReturnCts n, BindCts m n p) x >>= f = Maybe.MaybeT $ Maybe.runMaybeT x >>= \v -> case v of Nothing -> return Nothing Just y -> Maybe.runMaybeT (f y) {-# INLINE (>>=) #-} instance (P.Monoid w, Bind m n p) => Bind (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) where type BindCts (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) = (BindCts m n p) m >>= k = RWSL.RWST $ \ r s -> RWSL.runRWST m r s >>= \ ~(a, s', w) -> fmap (\ ~(b, s'',w') -> (b, s'', w `P.mappend` w')) $ RWSL.runRWST (k a) r s' {-# INLINE (>>=) #-} instance (P.Monoid w, Bind m n p) => Bind (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) where type BindCts (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) = (BindCts m n p) m >>= k = RWSS.RWST $ \ r s -> RWSS.runRWST m r s >>= \ (a, s', w) -> fmap (\(b, s'',w') -> (b, s'', w `P.mappend` w')) $ RWSS.runRWST (k a) r s' {-# INLINE (>>=) #-} instance (Bind m n p) => Bind (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) where type BindCts (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) = (BindCts m n p) m >>= k = Reader.ReaderT $ \ r -> Reader.runReaderT m r >>= \ a -> Reader.runReaderT (k a) r {-# INLINE (>>=) #-} instance (Bind m n p) => Bind (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) where type BindCts (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) = (BindCts m n p) m >>= k = StateL.StateT $ \ s -> StateL.runStateT m s >>= \ ~(a, s') -> StateL.runStateT (k a) s' {-# INLINE (>>=) #-} instance (Bind m n p) => Bind (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) where type BindCts (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) = (BindCts m n p) m >>= k = StateS.StateT $ \ s -> StateS.runStateT m s >>= \ (a, s') -> StateS.runStateT (k a) s' {-# INLINE (>>=) #-} instance (P.Monoid w, Bind m n p) => Bind (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) where type BindCts (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) = (BindCts m n p) m >>= k = WriterL.WriterT $ WriterL.runWriterT m >>= \ ~(a, w) -> fmap (\ ~(b, w') -> (b, w `P.mappend` w')) $ WriterL.runWriterT (k a) {-# INLINE (>>=) #-} instance (P.Monoid w, Bind m n p) => Bind (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) where type BindCts (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) = (BindCts m n p) m >>= k = WriterS.WriterT $ WriterS.runWriterT m >>= \ (a, w) -> fmap (\ (b, w') -> (b, w `P.mappend` w')) $ WriterS.runWriterT (k a) {-# INLINE (>>=) #-} -- ----------------------------------------------------------------------------- -- Return Type Class -- ----------------------------------------------------------------------------- -- | See 'Bind' or 'Ap' for details on laws and requirements. class (Functor m) => Return m where type ReturnCts m :: Constraint type ReturnCts m = () return :: (ReturnCts m) => a -> m a instance Return ((->) r) where return = P.return instance Return Identity where return = P.return instance Return [] where return = P.return instance Return P.Maybe where return = P.return instance Return P.IO where return = P.return instance Return (P.Either e) where return = P.return instance Return Mon.First where return = P.return instance Return Mon.Last where return = P.return #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Return Mon.Sum where return = P.return instance Return Mon.Product where return = P.return instance Return Mon.Dual where return = P.return #endif instance (Return a) => Return (Mon.Alt a) where type ReturnCts (Mon.Alt a) = ReturnCts a return a = Mon.Alt $ return a #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Return Semigroup.Min where return = P.return instance Return Semigroup.Max where return = P.return instance Return Semigroup.Option where return = P.return instance Return Semigroup.First where return = P.return instance Return Semigroup.Last where return = P.return #endif instance Return Proxy.Proxy where return = P.return #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Return Complex.Complex where return = P.return instance Return NonEmpty.NonEmpty where return = P.return #endif instance (Return m1, Return m2) => Return (Product.Product m1 m2) where type ReturnCts (Product.Product m1 m2) = (ReturnCts m1, ReturnCts m2) return a = Product.Pair (return a) (return a) instance (Return f, Return f') => Return (Compose.Compose f f') where type ReturnCts (Compose.Compose f f') = (ReturnCts f, ReturnCts f') return = Compose.Compose . return . return instance Return Read.ReadP where return = P.return instance Return Read.ReadPrec where return = P.return instance Return (ST.ST s) where return = P.return instance Return (STL.ST s) where return = P.return instance (Arrow.ArrowApply a) => Return (Arrow.ArrowMonad a) where return = P.return -- | TODO / FIXME: This has the same issue as the 'Bind' instance for 'App.WrappedMonad'. instance (Return m, P.Monad m) => Return (App.WrappedMonad m) where type ReturnCts (App.WrappedMonad m) = ReturnCts m return a = App.WrapMonad $ return a instance Return STM.STM where return = P.return #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Return Generics.U1 where return = P.return instance (Return m) => Return (Generics.Rec1 m) where type ReturnCts (Generics.Rec1 m) = ReturnCts m return = Generics.Rec1 . return instance (Return f, Return g) => Return (f Generics.:*: g) where type ReturnCts (f Generics.:*: g) = (ReturnCts f, ReturnCts g) return a = return a Generics.:*: return a instance (Return f, Return g) => Return (f Generics.:.: g) where type ReturnCts (f Generics.:.: g) = (ReturnCts f, ReturnCts g) return = Generics.Comp1 . return . return instance Return f => Return (Generics.M1 i c f) where type ReturnCts (Generics.M1 i c f) = ReturnCts f return = Generics.M1 . return #endif -- "transformers" package instances: ------------------------------------------- -- Continuations are so weird... instance {- (Return m) => -} Return (Cont.ContT r m) where type ReturnCts (Cont.ContT r m) = () -- ReturnCts m return x = Cont.ContT ($ x) {-# INLINE return #-} instance (Return m) => Return (Except.ExceptT e m) where type ReturnCts (Except.ExceptT e m) = ReturnCts m return = Except.ExceptT . return . Right {-# INLINE return #-} instance (Return m) => Return (Identity.IdentityT m) where type ReturnCts (Identity.IdentityT m) = ReturnCts m return = (Identity.IdentityT) . return {-# INLINE return #-} instance (Return m) => Return (Maybe.MaybeT m) where type ReturnCts (Maybe.MaybeT m) = ReturnCts m return = Maybe.MaybeT . return . Just {-# INLINE return #-} instance (P.Monoid w, Return m) => Return (RWSL.RWST r w s m) where type ReturnCts (RWSL.RWST r w s m) = ReturnCts m return a = RWSL.RWST $ \ _ s -> return (a, s, P.mempty) {-# INLINE return #-} instance (P.Monoid w, Return m) => Return (RWSS.RWST r w s m) where type ReturnCts (RWSS.RWST r w s m) = ReturnCts m return a = RWSS.RWST $ \ _ s -> return (a, s, P.mempty) {-# INLINE return #-} instance (Return m) => Return (Reader.ReaderT r m) where type ReturnCts (Reader.ReaderT r m) = ReturnCts m return = Reader.ReaderT . const . return {-# INLINE return #-} instance (Return m) => Return (StateL.StateT s m) where type ReturnCts (StateL.StateT s m) = ReturnCts m return x = StateL.StateT $ \s -> return (x, s) {-# INLINE return #-} instance (Return m) => Return (StateS.StateT s m) where type ReturnCts (StateS.StateT s m) = ReturnCts m return x = StateS.StateT $ \s -> return (x, s) {-# INLINE return #-} instance (P.Monoid w, Return m) => Return (WriterL.WriterT w m) where type ReturnCts (WriterL.WriterT w m) = ReturnCts m return a = WriterL.WriterT $ return (a, P.mempty) {-# INLINE return #-} instance (P.Monoid w, Return m) => Return (WriterS.WriterT w m) where type ReturnCts (WriterS.WriterT w m) = ReturnCts m return a = WriterS.WriterT $ return (a, P.mempty) {-# INLINE return #-} -- ----------------------------------------------------------------------------- -- Fail Type Class -- ----------------------------------------------------------------------------- -- | See 'Bind' for details on laws and requirements. class Fail m where type FailCts m :: Constraint type FailCts m = () fail :: (FailCts m) => String -> m a instance Fail ((->) r) where fail = P.fail instance Fail Identity where fail = P.fail instance Fail [] where fail = P.fail instance Fail P.Maybe where fail = P.fail instance Fail P.IO where fail = P.fail instance Fail (P.Either e) where fail = P.fail instance Fail Mon.First where fail = P.fail instance Fail Mon.Last where fail = P.fail #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Fail Mon.Sum where fail = P.fail instance Fail Mon.Product where fail = P.fail instance Fail Mon.Dual where fail = P.fail #endif instance (Fail a) => Fail (Mon.Alt a) where type FailCts (Mon.Alt a) = (FailCts a) fail a = Mon.Alt $ fail a #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Fail Semigroup.Min where fail = P.fail instance Fail Semigroup.Max where fail = P.fail instance Fail Semigroup.Option where fail = P.fail instance Fail Semigroup.First where fail = P.fail instance Fail Semigroup.Last where fail = P.fail #endif instance Fail Proxy.Proxy where fail = P.fail #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Fail Complex.Complex where fail = P.fail instance Fail NonEmpty.NonEmpty where fail = P.fail #endif instance (Fail m1, Fail m2) => Fail (Product.Product m1 m2) where type FailCts (Product.Product m1 m2) = (FailCts m1, FailCts m2) fail a = Product.Pair (fail a) (fail a) instance Fail Read.ReadP where fail = P.fail instance Fail Read.ReadPrec where fail = P.fail instance Fail (ST.ST s) where fail = P.fail instance Fail (STL.ST s) where fail = P.fail instance (Arrow.ArrowApply a) => Fail (Arrow.ArrowMonad a) where fail = P.fail -- | TODO / FIXME: This has the same issue as the 'Bind' instance for 'App.WrappedMonad'. instance (Fail m, P.Monad m) => Fail (App.WrappedMonad m) where type FailCts (App.WrappedMonad m) = (FailCts m) fail a = App.WrapMonad $ fail a instance Fail STM.STM where fail = P.fail #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) instance Fail Generics.U1 where fail = P.fail instance (Fail m) => Fail (Generics.Rec1 m) where type FailCts (Generics.Rec1 m) = FailCts m fail = Generics.Rec1 . fail instance (Fail f, Fail g) => Fail (f Generics.:*: g) where type FailCts (f Generics.:*: g) = (FailCts f, FailCts g) fail a = fail a Generics.:*: fail a instance Fail f => Fail (Generics.M1 i c f) where type FailCts (Generics.M1 i c f) = FailCts f fail = Generics.M1 . fail #endif -- "transformers" package instances: ------------------------------------------- instance (Fail m) => Fail (Cont.ContT r m) where type FailCts (Cont.ContT r m) = (FailCts m) fail = (Cont.ContT) . const . fail {-# INLINE fail #-} instance (Fail m) => Fail (Except.ExceptT e m) where type FailCts (Except.ExceptT e m) = (FailCts m) fail = Except.ExceptT . fail {-# INLINE fail #-} instance (Fail m) => Fail (Identity.IdentityT m) where type FailCts (Identity.IdentityT m) = (FailCts m) fail msg = Identity.IdentityT $ fail msg {-# INLINE fail #-} instance (Return m) => Fail (Maybe.MaybeT m) where type FailCts (Maybe.MaybeT m) = (ReturnCts m) fail _ = Maybe.MaybeT (return Nothing) {-# INLINE fail #-} instance (P.Monoid w, Fail m) => Fail (RWSL.RWST r w s m) where type FailCts (RWSL.RWST r w s m) = (FailCts m) fail msg = RWSL.RWST $ \ _ _ -> fail msg {-# INLINE fail #-} instance (P.Monoid w, Fail m) => Fail (RWSS.RWST r w s m) where type FailCts (RWSS.RWST r w s m) = (FailCts m) fail msg = RWSS.RWST $ \ _ _ -> fail msg {-# INLINE fail #-} instance (Fail m) => Fail (Reader.ReaderT r m) where type FailCts (Reader.ReaderT r m) = (FailCts m) fail = Reader.ReaderT . const . fail {-# INLINE fail #-} instance (Fail m) => Fail (StateL.StateT s m) where type FailCts (StateL.StateT s m) = (FailCts m) fail = StateL.StateT . const . fail {-# INLINE fail #-} instance (Fail m) => Fail (StateS.StateT s m) where type FailCts (StateS.StateT s m) = (FailCts m) fail = StateS.StateT . const . fail {-# INLINE fail #-} instance (P.Monoid w, Fail m) => Fail (WriterL.WriterT w m) where type FailCts (WriterL.WriterT w m) = (FailCts m) fail msg = WriterL.WriterT $ fail msg {-# INLINE fail #-} instance (P.Monoid w, Fail m) => Fail (WriterS.WriterT w m) where type FailCts (WriterS.WriterT w m) = (FailCts m) fail msg = WriterS.WriterT $ fail msg {-# INLINE fail #-} -- ----------------------------------------------------------------------------- -- Convenient type synonyms -- ----------------------------------------------------------------------------- -- | A short-hand for writing polymorphic standard monad functions. type family Monad m :: Constraint where Monad m = (Bind m m m, Return m, Fail m)
jbracker/supermonad-plugin
src/Control/Super/Monad.hs
bsd-3-clause
35,259
0
15
6,793
13,738
7,447
6,291
471
1
{-# LANGUAGE TemplateHaskell #-} module Board.Space.Space where import Board.Adventure.Adventure import Board.Follower.Follower import Board.Object.Object import Data.Map import TalismanErrors.TalismanErrors import Control.Lens import Data.List as List class DrawCards a where cardsToDraw :: a -> Int data SpaceType = Fields1Space | Fields2Space | Fields3Space | Fields4Space | Fields5Space | Fields6Space | ForestSpace | RuinsSpace | TavernSpace | Plains1Space | Plains2Space | Plains3Space | Plains4Space | Woods1Space | Woods2Space | Woods3Space | Hills1Space | Hills2Space | CitySpace | ChapelSpace | SentinelSpace | GraveyardSpace | VillageSpace | CragsSpace deriving (Eq, Ord, Show, Enum) instance DrawCards SpaceType where cardsToDraw Fields1Space = 1 cardsToDraw Fields2Space = 1 cardsToDraw Fields3Space = 1 cardsToDraw Fields4Space = 1 cardsToDraw Fields5Space = 1 cardsToDraw Fields6Space = 1 cardsToDraw ForestSpace = 1 cardsToDraw RuinsSpace = 1 cardsToDraw TavernSpace = 1 cardsToDraw Plains1Space = 1 cardsToDraw Plains2Space = 1 cardsToDraw Plains3Space = 1 cardsToDraw Plains4Space = 1 cardsToDraw Woods1Space = 1 cardsToDraw Woods2Space = 1 cardsToDraw Woods3Space = 1 cardsToDraw Hills1Space = 1 cardsToDraw Hills2Space = 1 cardsToDraw CitySpace = 1 cardsToDraw ChapelSpace = 1 cardsToDraw SentinelSpace = 1 cardsToDraw GraveyardSpace= 1 cardsToDraw VillageSpace = 1 cardsToDraw CragsSpace = 1 data Space = Space { _freeFollowers :: [Follower] , _freeObjects :: [Object] , _adventures :: [Adventure] , _spaceType :: SpaceType } deriving (Show, Eq) makeLenses ''Space instance DrawCards Space where cardsToDraw space = cardsToDraw $ space ^. spaceType type Board = Map SpaceType Space type BoardLayout = Map SpaceType [SpaceType] boardLayout :: BoardLayout boardLayout = fromList [ (ChapelSpace , [Hills1Space, Fields6Space]) , (Hills1Space , [ChapelSpace, SentinelSpace]) , (SentinelSpace, [Hills1Space, Woods1Space]) , (Woods1Space, [SentinelSpace, GraveyardSpace]) , (GraveyardSpace, [Woods1Space, Fields1Space]) , (Fields1Space, [GraveyardSpace, VillageSpace]) , (VillageSpace, [Fields1Space, Fields2Space]) , (Fields2Space, [VillageSpace, ForestSpace]) , (ForestSpace, [Fields2Space, Plains1Space]) , (Plains1Space, [ForestSpace, RuinsSpace]) , (RuinsSpace, [Plains1Space, Fields3Space]) , (Fields3Space, [RuinsSpace, TavernSpace]) , (TavernSpace, [Fields3Space, Plains2Space]) , (Plains2Space, [TavernSpace, Woods2Space]) , (Woods2Space, [Plains2Space, Plains3Space]) , (Plains3Space, [Woods2Space, Hills2Space]) , (Hills2Space, [Plains3Space, Fields4Space]) , (Fields4Space, [Hills2Space, CitySpace]) , (CitySpace, [Fields4Space, Fields5Space]) , (Fields5Space, [CitySpace, Woods3Space]) , (Woods3Space, [Fields5Space, Plains4Space]) , (Plains4Space, [Woods3Space, CragsSpace]) , (CragsSpace, [Plains4Space, Fields6Space]) , (Fields6Space, [CragsSpace, ChapelSpace]) ] {-Initialize previous with current space as it doesn't matter in the beginning anyway, the filtering should just not happen (in this case it will happen but no space can be it's own neigbour so nothing will be filtered. It's nasty, it's true. -} movementOptions :: Int -> SpaceType -> Either TalismanErrors [SpaceType] movementOptions dieRoll curSpace = movementOptionsEither boardLayout dieRoll curSpace curSpace movementOptionsEither :: BoardLayout -> Int -> SpaceType -> SpaceType -> Either TalismanErrors [SpaceType] movementOptionsEither _ 0 previous curSpace = Right [curSpace] movementOptionsEither layout x previous curSpace = do neighbours <- maybe (Left SpaceTypeNotFound) Right $ layout ^. at curSpace let neighboursButNoBackTracking = List.filter (/= previous) neighbours listOfLists <- traverse (movementOptionsEither layout (x-1) curSpace) neighboursButNoBackTracking return . concat $ listOfLists movementOptionsMaybe :: BoardLayout -> Int -> SpaceType -> SpaceType -> Maybe [SpaceType] movementOptionsMaybe _ 0 previous curSpace = Just [curSpace] movementOptionsMaybe layout x previous curSpace = do neighbours <- layout ^. at curSpace let neighboursButNoBackTracking = List.filter (/= previous) neighbours listOfLists <- traverse (movementOptionsMaybe layout (x-1) curSpace) neighboursButNoBackTracking return . concat $ listOfLists createInitialBoard :: Board createInitialBoard = fromList $ zip fieldsTypeList $ fmap createStartingSpace fieldsTypeList where fieldsTypeList = [Fields1Space ..] createStartingSpace :: SpaceType -> Space createStartingSpace spaceType = Space { _spaceType = spaceType , _freeFollowers = [] , _freeObjects = [] , _adventures = [] } lookupSpaces :: [SpaceType] -> Board -> Either TalismanErrors [Space] lookupSpaces spaceTypes board = traverse (\spaceType -> maybe (Left SpaceTypeNotFound) Right $ board ^. at spaceType) spaceTypes
charleso/intellij-haskforce
tests/gold/codeInsight/TotalProject/Board/Space/Space.hs
apache-2.0
5,309
0
12
1,120
1,327
755
572
130
1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} module Elm.Utils ( (|>), (<|) , getAsset , run, unwrappedRun , CommandError(..) , isDeclaration ) where import Control.Monad.Except (MonadError, MonadIO, liftIO, throwError) import qualified Data.List as List import System.Directory (doesFileExist) import System.Environment (getEnv) import System.Exit (ExitCode(ExitSuccess, ExitFailure)) import System.FilePath ((</>)) import System.IO.Error (tryIOError) import System.Process (readProcessWithExitCode) import qualified AST.Expression.Source as Source import qualified AST.Pattern as Pattern import qualified Elm.Compiler.Version as Version import qualified Elm.Package as Pkg import qualified Parse.Helpers as Parse import qualified Parse.Expression as Parse import qualified Reporting.Annotation as A {-| Forward function application `x |> f == f x`. This function is useful for avoiding parenthesis and writing code in a more natural way. -} (|>) :: a -> (a -> b) -> b x |> f = f x {-| Backward function application `f <| x == f x`. This function is useful for avoiding parenthesis. -} (<|) :: (a -> b) -> a -> b f <| x = f x infixr 0 <| infixl 0 |> -- RUN EXECUTABLES data CommandError = MissingExe String | CommandFailed String String {-| Run a command, throw an error if the command is not found or if something goes wrong. -} run :: (MonadError String m, MonadIO m) => String -> [String] -> m String run command args = do result <- liftIO (unwrappedRun command args) case result of Right out -> return out Left err -> throwError (context (message err)) where context msg = "failure when running:" ++ concatMap (' ':) (command:args) ++ "\n" ++ msg message err = case err of CommandFailed stderr stdout -> stdout ++ stderr MissingExe msg -> msg unwrappedRun :: String -> [String] -> IO (Either CommandError String) unwrappedRun command args = do (exitCode, stdout, stderr) <- readProcessWithExitCode command args "" return $ case exitCode of ExitSuccess -> Right stdout ExitFailure code -> if code == 127 then Left (missingExe command) -- UNIX else if code == 9009 then Left (missingExe command) -- Windows else Left (CommandFailed stdout stderr) missingExe :: String -> CommandError missingExe command = MissingExe $ "Could not find command `" ++ command ++ "`. Do you have it installed?\n\ \ Can it be run from anywhere? Is it on your PATH?" -- GET STATIC ASSETS {-| Get the absolute path to a data file. If you install with cabal it will look in a directory generated by cabal. If that is not found, it will look for the directory pointed to by the environment variable ELM_HOME. -} getAsset :: String -> (FilePath -> IO FilePath) -> FilePath -> IO FilePath getAsset project getDataFileName name = do path <- getDataFileName name exists <- doesFileExist path if exists then return path else do environment <- tryIOError (getEnv "ELM_HOME") case environment of Right env -> return (env </> project </> name) Left _ -> fail (errorNotFound name) errorNotFound :: FilePath -> String errorNotFound name = unlines [ "Unable to find the ELM_HOME environment variable when searching" , "for the " ++ name ++ " file." , "" , "If you installed Elm Platform with the Mac or Windows installer, it looks like" , "ELM_HOME was not set automatically. Look up how to set environment variables" , "on your platform and set ELM_HOME to the directory that contains Elm's static" , "files:" , "" , " * On Mac it is /usr/local/share/elm" , " * On Windows it is one of the following:" , " C:/Program Files/Elm Platform/" ++ (Pkg.versionToString Version.version) ++ "/share" , " C:/Program Files (x86)/Elm Platform/" ++ (Pkg.versionToString Version.version) ++ "/share" , "" , "If you installed using npm, you have to set ELM_HOME to a certain directory" , "of the form .../node_modules/elm/share" , "" , "If it seems like a more complex issue, please report it here:" , " <https://github.com/elm-lang/elm-platform/issues>" ] -- DECL CHECKER isDeclaration :: String -> Maybe String isDeclaration string = case Parse.iParse Parse.definition string of Right (A.A _ (Source.Definition pattern _)) -> Just (List.intercalate "$" (Pattern.boundVarList pattern)) _ -> Nothing
laszlopandy/elm-compiler
src/Elm/Utils.hs
bsd-3-clause
4,764
0
16
1,225
1,001
548
453
107
4
{-| Module : Idris.Package Description : Functionality for working with Idris packages. License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE CPP #-} module Idris.Package where import System.Directory import System.Environment import System.Exit import System.FilePath (addExtension, addTrailingPathSeparator, dropExtension, hasExtension, takeDirectory, takeExtension, takeFileName, (</>)) import System.IO import System.Process import Util.System import Control.Monad import Control.Monad.Trans.Except (runExceptT) import Control.Monad.Trans.State.Strict (execStateT) import Data.Either (partitionEithers) import Data.List import Data.List.Split (splitOn) import Idris.AbsSyntax import Idris.Core.TT import Idris.Error (ifail) import Idris.IBC import Idris.IdrisDoc import Idris.Imports import Idris.Main (idris, idrisMain) import Idris.Options import Idris.Output import Idris.Parser (loadModule) import Idris.Package.Common import Idris.Package.Parser import IRTS.System -- To build a package: -- * read the package description -- * check all the library dependencies exist -- * invoke the makefile if there is one -- * invoke idris on each module, with idris_opts -- * install everything into datadir/pname, if install flag is set getPkgDesc :: FilePath -> IO PkgDesc getPkgDesc = parseDesc -- --------------------------------------------------------- [ Build Packages ] -- | Run the package through the idris compiler. buildPkg :: [Opt] -- ^ Command line options -> Bool -- ^ Provide Warnings -> (Bool, FilePath) -- ^ (Should we install, Location of iPKG file) -> IO () buildPkg copts warnonly (install, fp) = do pkgdesc <- parseDesc fp dir <- getCurrentDirectory let idx' = pkgIndex $ pkgname pkgdesc idx = PkgIndex $ case opt getIBCSubDir copts of (ibcsubdir:_) -> ibcsubdir </> idx' [] -> idx' oks <- mapM (testLib warnonly (pkgname pkgdesc)) (libdeps pkgdesc) when (and oks) $ do m_ist <- inPkgDir pkgdesc $ do make (makefile pkgdesc) case (execout pkgdesc) of Nothing -> do case mergeOptions copts (idx : NoREPL : Verbose 1 : idris_opts pkgdesc) of Left emsg -> do putStrLn emsg exitWith (ExitFailure 1) Right opts -> do auditPackage (AuditIPkg `elem` opts) pkgdesc buildMods opts (modules pkgdesc) Just o -> do let exec = dir </> o case mergeOptions copts (idx : NoREPL : Verbose 1 : Output exec : idris_opts pkgdesc) of Left emsg -> do putStrLn emsg exitWith (ExitFailure 1) Right opts -> do auditPackage (AuditIPkg `elem` opts) pkgdesc buildMain opts (idris_main pkgdesc) case m_ist of Nothing -> exitWith (ExitFailure 1) Just ist -> do -- Quit with error code if there was a problem case errSpan ist of Just _ -> exitWith (ExitFailure 1) _ -> return () when install $ installPkg (opt getIBCSubDir copts) pkgdesc where buildMain opts (Just mod) = buildMods opts [mod] buildMain _ Nothing = do putStrLn "Can't build an executable: No main module given" exitWith (ExitFailure 1) -- --------------------------------------------------------- [ Check Packages ] -- | Type check packages only -- -- This differs from build in that executables are not built, if the -- package contains an executable. checkPkg :: [Opt] -- ^ Command line Options -> Bool -- ^ Show Warnings -> Bool -- ^ quit on failure -> FilePath -- ^ Path to ipkg file. -> IO () checkPkg copts warnonly quit fpath = do pkgdesc <- parseDesc fpath oks <- mapM (testLib warnonly (pkgname pkgdesc)) (libdeps pkgdesc) when (and oks) $ do res <- inPkgDir pkgdesc $ do make (makefile pkgdesc) case mergeOptions copts (NoREPL : Verbose 1 : idris_opts pkgdesc) of Left emsg -> do putStrLn emsg exitWith (ExitFailure 1) Right opts -> do auditPackage (AuditIPkg `elem` opts) pkgdesc buildMods opts (modules pkgdesc) when quit $ case res of Nothing -> exitWith (ExitFailure 1) Just res' -> do case errSpan res' of Just _ -> exitWith (ExitFailure 1) _ -> return () -- ------------------------------------------------------------------- [ REPL ] -- | Check a package and start a REPL. -- -- This function only works with packages that have a main module. -- replPkg :: [Opt] -- ^ Command line Options -> FilePath -- ^ Path to ipkg file. -> Idris () replPkg copts fp = do orig <- getIState runIO $ checkPkg copts False False fp pkgdesc <- runIO $ parseDesc fp -- bzzt, repetition! case mergeOptions copts (idris_opts pkgdesc) of Left emsg -> ifail emsg Right opts -> do putIState orig dir <- runIO getCurrentDirectory runIO $ setCurrentDirectory $ dir </> sourcedir pkgdesc runMain opts (idris_main pkgdesc) runIO $ setCurrentDirectory dir where toPath n = foldl1' (</>) $ splitOn "." n runMain opts (Just mod) = do let f = toPath (showCG mod) idrisMain ((Filename f) : opts) runMain _ Nothing = iputStrLn "Can't start REPL: no main module given" -- --------------------------------------------------------------- [ Cleaning ] -- | Clean Package build files cleanPkg :: [Opt] -- ^ Command line options. -> FilePath -- ^ Path to ipkg file. -> IO () cleanPkg copts fp = do pkgdesc <- parseDesc fp dir <- getCurrentDirectory inPkgDir pkgdesc $ do clean (makefile pkgdesc) mapM_ rmIBC (modules pkgdesc) rmIdx (pkgname pkgdesc) case execout pkgdesc of Nothing -> return () Just s -> rmExe $ dir </> s -- ------------------------------------------------------ [ Generate IdrisDoc ] -- | Generate IdrisDoc for package -- TODO: Handle case where module does not contain a matching namespace -- E.g. from prelude.ipkg: IO, Prelude.Chars, Builtins -- -- Issue number #1572 on the issue tracker -- https://github.com/idris-lang/Idris-dev/issues/1572 documentPkg :: [Opt] -- ^ Command line options. -> (Bool,FilePath) -- ^ (Should we install?, Path to ipkg file). -> IO () documentPkg copts (install,fp) = do pkgdesc <- parseDesc fp cd <- getCurrentDirectory let pkgDir = cd </> takeDirectory fp outputDir = cd </> unPkgName (pkgname pkgdesc) ++ "_doc" popts = NoREPL : Verbose 1 : idris_opts pkgdesc mods = modules pkgdesc fs = map (foldl1' (</>) . splitOn "." . showCG) mods setCurrentDirectory $ pkgDir </> sourcedir pkgdesc make (makefile pkgdesc) setCurrentDirectory pkgDir case mergeOptions copts popts of Left emsg -> do putStrLn emsg exitWith (ExitFailure 1) Right opts -> do let run l = runExceptT . execStateT l load [] = return () load (f:fs) = do loadModule f IBC_Building; load fs loader = do idrisMain opts addImportDir (sourcedir pkgdesc) load fs idrisImplementation <- run loader idrisInit setCurrentDirectory cd case idrisImplementation of Left err -> do putStrLn $ pshow idrisInit err exitWith (ExitFailure 1) Right ist -> do iDocDir <- getIdrisDocDir pkgDocDir <- makeAbsolute (iDocDir </> unPkgName (pkgname pkgdesc)) let out_dir = if install then pkgDocDir else outputDir when install $ do putStrLn $ unwords ["Attempting to install IdrisDocs for", show $ pkgname pkgdesc, "in:", out_dir] docRes <- generateDocs ist mods out_dir case docRes of Right _ -> return () Left msg -> do putStrLn msg exitWith (ExitFailure 1) -- ------------------------------------------------------------------- [ Test ] -- | Build a package with a sythesized main function that runs the tests testPkg :: [Opt] -- ^ Command line options. -> FilePath -- ^ Path to ipkg file. -> IO ExitCode testPkg copts fp = do pkgdesc <- parseDesc fp ok <- mapM (testLib True (pkgname pkgdesc)) (libdeps pkgdesc) if and ok then do (m_ist, exitCode) <- inPkgDir pkgdesc $ do make (makefile pkgdesc) -- Get a temporary file to save the tests' source in (tmpn, tmph) <- tempfile ".idr" hPutStrLn tmph $ "module Test_______\n" ++ concat ["import " ++ show m ++ "\n" | m <- modules pkgdesc] ++ "namespace Main\n" ++ " main : IO ()\n" ++ " main = do " ++ concat [ show t ++ "\n " | t <- idris_tests pkgdesc] hClose tmph (tmpn', tmph') <- tempfile "" hClose tmph' let popts = (Filename tmpn : NoREPL : Verbose 1 : Output tmpn' : idris_opts pkgdesc) case mergeOptions copts popts of Left emsg -> do putStrLn emsg exitWith (ExitFailure 1) Right opts -> do m_ist <- idris opts let texe = if isWindows then addExtension tmpn' ".exe" else tmpn' exitCode <- rawSystem texe [] return (m_ist, exitCode) case m_ist of Nothing -> exitWith (ExitFailure 1) Just ist -> do -- Quit with error code if problem building case errSpan ist of Just _ -> exitWith (ExitFailure 1) _ -> return exitCode else return (ExitFailure 1) -- ----------------------------------------------------------- [ Installation ] -- | Install package installPkg :: [String] -- ^ Alternate install location -> PkgDesc -- ^ iPKG file. -> IO () installPkg altdests pkgdesc = inPkgDir pkgdesc $ do d <- getIdrisLibDir let destdir = case altdests of [] -> d (d':_) -> d' case (execout pkgdesc) of Nothing -> do mapM_ (installIBC destdir (pkgname pkgdesc)) (modules pkgdesc) installIdx destdir (pkgname pkgdesc) Just o -> return () -- do nothing, keep executable locally, for noe mapM_ (installObj destdir (pkgname pkgdesc)) (objs pkgdesc) -- ---------------------------------------------------------- [ Helper Methods ] -- Methods for building, testing, installing, and removal of idris -- packages. auditPackage :: Bool -> PkgDesc -> IO () auditPackage False _ = return () auditPackage True ipkg = do cwd <- getCurrentDirectory let ms = map (sourcedir ipkg </>) $ map (toPath . showCG) (modules ipkg) ms' <- mapM makeAbsolute ms ifiles <- getIdrisFiles cwd let ifiles' = map dropExtension ifiles not_listed <- mapM makeRelativeToCurrentDirectory (ifiles' \\ ms') putStrLn $ unlines $ ["Warning: The following modules are not listed in your iPkg file:\n"] ++ map (\m -> unwords ["-", m]) not_listed ++ ["\nModules that are not listed, are not installed."] where toPath n = foldl1' (</>) $ splitOn "." n getIdrisFiles :: FilePath -> IO [FilePath] getIdrisFiles dir = do contents <- getDirectoryContents dir -- [ NOTE ] Directory >= 1.2.5.0 introduced `listDirectory` but later versions of directory appear to be causing problems with ghc 7.10.3 and cabal 1.22 in travis. Let's reintroduce the old ranges for directory to be sure. files <- forM contents (findRest dir) return $ filter (isIdrisFile) (concat files) isIdrisFile :: FilePath -> Bool isIdrisFile fp = takeExtension fp == ".idr" || takeExtension fp == ".lidr" findRest :: FilePath -> FilePath -> IO [FilePath] findRest dir fn = do path <- makeAbsolute (dir </> fn) isDir <- doesDirectoryExist path if isDir then getIdrisFiles path else return [path] buildMods :: [Opt] -> [Name] -> IO (Maybe IState) buildMods opts ns = do let f = map (toPath . showCG) ns idris (map Filename f ++ opts) where toPath n = foldl1' (</>) $ splitOn "." n testLib :: Bool -> PkgName -> String -> IO Bool testLib warn p f = do d <- getIdrisCRTSDir gcc <- getCC (tmpf, tmph) <- tempfile "" hClose tmph let libtest = d </> "libtest.c" e <- rawSystem gcc [libtest, "-l" ++ f, "-o", tmpf] case e of ExitSuccess -> return True _ -> do if warn then do putStrLn $ "Not building " ++ show p ++ " due to missing library " ++ f return False else fail $ "Missing library " ++ f rmIBC :: Name -> IO () rmIBC m = rmFile $ toIBCFile m rmIdx :: PkgName -> IO () rmIdx p = do let f = pkgIndex p ex <- doesFileExist f when ex $ rmFile f rmExe :: String -> IO () rmExe p = do fn <- return $ if isWindows && not (hasExtension p) then addExtension p ".exe" else p rmFile fn toIBCFile (UN n) = str n ++ ".ibc" toIBCFile (NS n ns) = foldl1' (</>) (reverse (toIBCFile n : map str ns)) installIBC :: String -> PkgName -> Name -> IO () installIBC dest p m = do let f = toIBCFile m let destdir = dest </> unPkgName p </> getDest m putStrLn $ "Installing " ++ f ++ " to " ++ destdir createDirectoryIfMissing True destdir copyFile f (destdir </> takeFileName f) return () where getDest (UN n) = "" getDest (NS n ns) = foldl1' (</>) (reverse (getDest n : map str ns)) installIdx :: String -> PkgName -> IO () installIdx dest p = do let f = pkgIndex p let destdir = dest </> unPkgName p putStrLn $ "Installing " ++ f ++ " to " ++ destdir createDirectoryIfMissing True destdir copyFile f (destdir </> takeFileName f) return () installObj :: String -> PkgName -> String -> IO () installObj dest p o = do let destdir = addTrailingPathSeparator (dest </> unPkgName p) putStrLn $ "Installing " ++ o ++ " to " ++ destdir createDirectoryIfMissing True destdir copyFile o (destdir </> takeFileName o) return () #ifdef mingw32_HOST_OS mkDirCmd = "mkdir " #else mkDirCmd = "mkdir -p " #endif inPkgDir :: PkgDesc -> IO a -> IO a inPkgDir pkgdesc action = do dir <- getCurrentDirectory when (sourcedir pkgdesc /= "") $ do putStrLn $ "Entering directory `" ++ ("." </> sourcedir pkgdesc) ++ "'" setCurrentDirectory $ dir </> sourcedir pkgdesc res <- action when (sourcedir pkgdesc /= "") $ do putStrLn $ "Leaving directory `" ++ ("." </> sourcedir pkgdesc) ++ "'" setCurrentDirectory dir return res -- ------------------------------------------------------- [ Makefile Commands ] -- | Invoke a Makefile's target with an enriched system environment makeTarget :: Maybe String -> Maybe String -> IO () makeTarget _ Nothing = return () makeTarget mtgt (Just s) = do incFlags <- intercalate " " <$> getIncFlags libFlags <- intercalate " " <$> getLibFlags newEnv <- (++ [("IDRIS_INCLUDES", incFlags), ("IDRIS_LDFLAGS", libFlags)]) <$> getEnvironment let cmdLine = case mtgt of Nothing -> "make -f " ++ s Just tgt -> "make -f " ++ s ++ " " ++ tgt (_, _, _, r) <- createProcess (shell cmdLine) { env = Just newEnv } waitForProcess r return () -- | Invoke a Makefile's default target. make :: Maybe String -> IO () make = makeTarget Nothing -- | Invoke a Makefile's clean target. clean :: Maybe String -> IO () clean = makeTarget (Just "clean") -- | Merge an option list representing the command line options into -- those specified for a package description. -- -- This is not a complete union between the two options sets. First, -- to prevent important package specified options from being -- overwritten. Second, the semantics for this merge are not fully -- defined. -- -- A discussion for this is on the issue tracker: -- https://github.com/idris-lang/Idris-dev/issues/1448 -- mergeOptions :: [Opt] -- ^ The command line options -> [Opt] -- ^ The package options -> Either String [Opt] mergeOptions copts popts = case partitionEithers (map chkOpt (normaliseOpts copts)) of ([], copts') -> Right $ copts' ++ popts (es, _) -> Left $ genErrMsg es where normaliseOpts :: [Opt] -> [Opt] normaliseOpts = filter filtOpt filtOpt :: Opt -> Bool filtOpt (PkgBuild _) = False filtOpt (PkgInstall _) = False filtOpt (PkgClean _) = False filtOpt (PkgCheck _) = False filtOpt (PkgREPL _) = False filtOpt (PkgDocBuild _) = False filtOpt (PkgDocInstall _) = False filtOpt (PkgTest _) = False filtOpt _ = True chkOpt :: Opt -> Either String Opt chkOpt o@(OLogging _) = Right o chkOpt o@(OLogCats _) = Right o chkOpt o@(DefaultTotal) = Right o chkOpt o@(DefaultPartial) = Right o chkOpt o@(WarnPartial) = Right o chkOpt o@(WarnReach) = Right o chkOpt o@(IBCSubDir _) = Right o chkOpt o@(ImportDir _ ) = Right o chkOpt o@(UseCodegen _) = Right o chkOpt o@(Verbose _) = Right o chkOpt o@(AuditIPkg) = Right o chkOpt o@(DumpHighlights) = Right o chkOpt o = Left (unwords ["\t", show o, "\n"]) genErrMsg :: [String] -> String genErrMsg es = unlines [ "Not all command line options can be used to override package options." , "\nThe only changeable options are:" , "\t--log <lvl>, --total, --warnpartial, --warnreach, --warnipkg" , "\t--ibcsubdir <path>, -i --idrispath <path>" , "\t--logging-categories <cats>" , "\t--highlight" , "\nThe options need removing are:" , unlines es ] -- --------------------------------------------------------------------- [ EOF ]
kojiromike/Idris-dev
src/Idris/Package.hs
bsd-3-clause
18,629
0
26
5,649
5,080
2,472
2,608
387
22
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Control.CP.Herbrand.Prolog ( Prolog , module Control.CP.Herbrand.PrologTerm , PConstraint (..) ) where import Control.Monad (zipWithM) import Control.CP.Solver import Control.CP.Herbrand.Herbrand import Control.CP.Herbrand.PrologTerm -- Prolog Solver newtype Prolog a = Prolog { runProlog :: Herbrand PrologTerm a } deriving Monad instance Solver Prolog where type Constraint Prolog = PConstraint type Label Prolog = Label (Herbrand PrologTerm) add = addProlog mark = Prolog $ mark goto = Prolog . goto run = run . runProlog instance Term Prolog PrologTerm where newvar = Prolog $ newvar type Help Prolog PrologTerm = () help _ _ = () data PConstraint = PrologTerm := PrologTerm | NotFunctor PrologTerm String | PrologTerm :/= PrologTerm addProlog :: PConstraint -> Prolog Bool addProlog (x := y) = Prolog (unify x y) addProlog (x :/= y) = Prolog (diff x y) addProlog (NotFunctor x f) = Prolog (notFunctor x f) notFunctor :: PrologTerm -> String -> Herbrand PrologTerm Bool notFunctor x f = do t <- shallow_normalize x case t of PVar _ -> registerAction t (notFunctor t f) >> success PTerm g _ -> if g == f then failure else success diff :: PrologTerm -> PrologTerm -> Herbrand PrologTerm Bool diff x y = do x' <- shallow_normalize x y' <- shallow_normalize y b <- diff' x' y' case b of DYes -> success DNo -> failure DMaybe vars -> mapM (\v -> registerAction v (diff x y)) vars >> success where diff' x@(PVar v1) (PVar v2) = if v1 == v2 then return $ DNo else return $ DMaybe [x] diff' x@(PVar _) (PTerm _ _) = return $ DMaybe [x] diff' (PTerm _ _) y@(PVar _) = return $ DMaybe [y] diff' (PTerm f xs) (PTerm g ys) | x /= y = return $ DYes | length xs /= length ys = return $ DYes | otherwise = do xs' <- mapM shallow_normalize xs ys' <- mapM shallow_normalize ys bs <- zipWithM diff' xs' ys' return $ foldr dand DYes bs data DiffBool = DYes | DNo | DMaybe [PrologTerm] dand DNo _ = DNo dand _ DNo = DNo dand (DMaybe x) (DMaybe y) = DMaybe (x ++ y) dand DYes x = x dand x DYes = x
neothemachine/monadiccp
src/Control/CP/Herbrand/Prolog.hs
bsd-3-clause
2,783
0
16
1,025
865
445
420
70
7
{-# language OverloadedStrings #-} -- | benchmarking Base.Font.searchGlyphs import qualified Data.Text as T import Data.Initial import Data.Map import Control.Monad.Reader import Control.DeepSeq import Graphics.Qt import Utils import Base import Base.Font import Criterion.Main main = flip runReaderT (savedConfigurationToConfiguration initial) $ withQApplication $ \ qApp -> do pixmaps <- loadApplicationPixmaps let variant = colorVariants (alphaNumericFont pixmaps) ! standardFontColor io $ defaultMain $ bench "searchGlyphsOld" (b (searchGlyphs variant)) : bench "searchGlyphs" (b (searchGlyphs variant)) : [] b :: (T.Text -> [Glyph]) -> Pure b f = nf (fmap f) (replicate 1 "This is an example text") instance NFData Glyph where rnf (Glyph a b) = rnf a `seq` rnf b rnf (ErrorGlyph a) = rnf a
geocurnoff/nikki
src/benchmarks/searchGlyphs.hs
lgpl-3.0
862
1
16
179
275
140
135
25
1
{-| Module : IRTS.Defunctionalise Description : Defunctionalise Idris' IR. Copyright : License : BSD3 Maintainer : The Idris Community. To defunctionalise: 1. Create a data constructor for each function 2. Create a data constructor for each underapplication of a function 3. Convert underapplications to their corresponding constructors 4. Create an EVAL function which calls the appropriate function for data constructors created as part of step 1 5. Create an APPLY function which adds an argument to each underapplication (or calls APPLY again for an exact application) 6. Wrap overapplications in chains of APPLY 7. Wrap unknown applications (i.e. applications of local variables) in chains of APPLY 8. Add explicit EVAL to case, primitives, and foreign calls -} {-# LANGUAGE PatternGuards #-} module IRTS.Defunctionalise(module IRTS.Defunctionalise , module IRTS.Lang ) where import IRTS.Lang import Idris.Core.TT import Idris.Core.CaseTree import Debug.Trace import Data.Maybe import Data.List import Control.Monad import Control.Monad.State data DExp = DV LVar | DApp Bool Name [DExp] -- True = tail call | DLet Name DExp DExp -- name just for pretty printing | DUpdate Name DExp -- eval expression, then update var with it | DProj DExp Int | DC (Maybe LVar) Int Name [DExp] | DCase CaseType DExp [DAlt] | DChkCase DExp [DAlt] -- a case where the type is unknown (for EVAL/APPLY) | DConst Const | DForeign FDesc FDesc [(FDesc, DExp)] | DOp PrimFn [DExp] | DNothing -- erased value, can be compiled to anything since it'll never -- be inspected | DError String deriving Eq data DAlt = DConCase Int Name [Name] DExp | DConstCase Const DExp | DDefaultCase DExp deriving (Show, Eq) data DDecl = DFun Name [Name] DExp -- name, arg names, definition | DConstructor Name Int Int -- constructor name, tag, arity deriving (Show, Eq) type DDefs = Ctxt DDecl defunctionalise :: Int -> LDefs -> DDefs defunctionalise nexttag defs = let all = toAlist defs -- sort newcons so that EVAL and APPLY cons get sequential tags (allD, (enames, anames)) = runState (mapM (addApps defs) all) ([], []) anames' = sort (nub anames) enames' = nub enames newecons = sortBy conord $ concatMap (toCons enames') (getFn all) newacons = sortBy conord $ concatMap (toConsA anames') (getFn all) eval = mkEval newecons app = mkApply newacons app2 = mkApply2 newacons condecls = declare nexttag (newecons ++ newacons) in addAlist (eval : app : app2 : condecls ++ allD) emptyContext where conord (n, _, _) (n', _, _) = compare n n' getFn :: [(Name, LDecl)] -> [(Name, Int)] getFn xs = mapMaybe fnData xs where fnData (n, LFun _ _ args _) = Just (n, length args) fnData _ = Nothing addApps :: LDefs -> (Name, LDecl) -> State ([Name], [(Name, Int)]) (Name, DDecl) addApps defs o@(n, LConstructor _ t a) = return (n, DConstructor n t a) addApps defs (n, LFun _ _ args e) = do e' <- aa args e return (n, DFun n args e') where aa :: [Name] -> LExp -> State ([Name], [(Name, Int)]) DExp aa env (LV (Glob n)) | n `elem` env = return $ DV (Glob n) | otherwise = aa env (LApp False (LV (Glob n)) []) aa env (LApp tc (LV (Glob n)) args) = do args' <- mapM (aa env) args case lookupCtxtExact n defs of Just (LConstructor _ i ar) -> return $ DApp tc n args' Just (LFun _ _ as _) -> let arity = length as in fixApply tc n args' arity Nothing -> return $ chainAPPLY (DV (Glob n)) args' aa env (LLazyApp n args) = do args' <- mapM (aa env) args case lookupCtxtExact n defs of Just (LConstructor _ i ar) -> return $ DApp False n args' Just (LFun _ _ as _) -> let arity = length as in fixLazyApply n args' arity Nothing -> return $ chainAPPLY (DV (Glob n)) args' aa env (LForce (LLazyApp n args)) = aa env (LApp False (LV (Glob n)) args) aa env (LForce e) = liftM eEVAL (aa env e) aa env (LLet n v sc) = liftM2 (DLet n) (aa env v) (aa (n : env) sc) aa env (LCon loc i n args) = liftM (DC loc i n) (mapM (aa env) args) aa env (LProj t@(LV (Glob n)) i) | n `elem` env = do t' <- aa env t return $ DProj (DUpdate n t') i aa env (LProj t i) = do t' <- aa env t return $ DProj t' i aa env (LCase up e alts) = do e' <- aa env e alts' <- mapM (aaAlt env) alts return $ DCase up e' alts' aa env (LConst c) = return $ DConst c aa env (LForeign t n args) = do args' <- mapM (aaF env) args return $ DForeign t n args' aa env (LOp LFork args) = liftM (DOp LFork) (mapM (aa env) args) aa env (LOp f args) = do args' <- mapM (aa env) args return $ DOp f args' aa env LNothing = return DNothing aa env (LError e) = return $ DError e aaF env (t, e) = do e' <- aa env e return (t, e') aaAlt env (LConCase i n args e) = liftM (DConCase i n args) (aa (args ++ env) e) aaAlt env (LConstCase c e) = liftM (DConstCase c) (aa env e) aaAlt env (LDefaultCase e) = liftM DDefaultCase (aa env e) fixApply tc n args ar | length args == ar = return $ DApp tc n args | length args < ar = do (ens, ans) <- get let alln = map (\x -> (n, x)) [length args .. ar] put (ens, alln ++ ans) return $ DApp tc (mkUnderCon n (ar - length args)) args | length args > ar = return $ chainAPPLY (DApp tc n (take ar args)) (drop ar args) fixLazyApply n args ar | length args == ar = do (ens, ans) <- get put (n : ens, ans) return $ DApp False (mkFnCon n) args | length args < ar = do (ens, ans) <- get let alln = map (\x -> (n, x)) [length args .. ar] put (ens, alln ++ ans) return $ DApp False (mkUnderCon n (ar - length args)) args | length args > ar = return $ chainAPPLY (DApp False n (take ar args)) (drop ar args) chainAPPLY f [] = f -- chainAPPLY f (a : b : as) -- = chainAPPLY (DApp False (sMN 0 "APPLY2") [f, a, b]) as chainAPPLY f (a : as) = chainAPPLY (DApp False (sMN 0 "APPLY") [f, a]) as -- if anything in the DExp is projected from, we'll need to evaluate it, -- but we only want to do it once, rather than every time we project. preEval [] t = t preEval (x : xs) t | needsEval x t = DLet x (DV (Glob x)) (preEval xs t) | otherwise = preEval xs t needsEval x (DApp _ _ args) = any (needsEval x) args needsEval x (DC _ _ _ args) = any (needsEval x) args needsEval x (DCase up e alts) = needsEval x e || any nec alts where nec (DConCase _ _ _ e) = needsEval x e nec (DConstCase _ e) = needsEval x e nec (DDefaultCase e) = needsEval x e needsEval x (DChkCase e alts) = needsEval x e || any nec alts where nec (DConCase _ _ _ e) = needsEval x e nec (DConstCase _ e) = needsEval x e nec (DDefaultCase e) = needsEval x e needsEval x (DLet n v e) | x == n = needsEval x v | otherwise = needsEval x v || needsEval x e needsEval x (DForeign _ _ args) = any (needsEval x) (map snd args) needsEval x (DOp op args) = any (needsEval x) args needsEval x (DProj (DV (Glob x')) _) = x == x' needsEval x _ = False eEVAL x = DApp False (sMN 0 "EVAL") [x] data EvalApply a = EvalCase (Name -> a) | ApplyCase a | Apply2Case a -- For a function name, generate a list of -- data constuctors, and whether to handle them in EVAL or APPLY toCons :: [Name] -> (Name, Int) -> [(Name, Int, EvalApply DAlt)] toCons ns (n, i) | n `elem` ns = (mkFnCon n, i, EvalCase (\tlarg -> (DConCase (-1) (mkFnCon n) (take i (genArgs 0)) (dupdate tlarg (DApp False n (map (DV . Glob) (take i (genArgs 0)))))))) : [] -- mkApplyCase n 0 i | otherwise = [] where dupdate tlarg x = DUpdate tlarg x toConsA :: [(Name, Int)] -> (Name, Int) -> [(Name, Int, EvalApply DAlt)] toConsA ns (n, i) | Just ar <- lookup n ns -- = (mkFnCon n, i, -- EvalCase (\tlarg -> -- (DConCase (-1) (mkFnCon n) (take i (genArgs 0)) -- (dupdate tlarg -- (DApp False n (map (DV . Glob) (take i (genArgs 0)))))))) = mkApplyCase n ar i | otherwise = [] where dupdate tlarg x = x mkApplyCase fname n ar | n == ar = [] mkApplyCase fname n ar = let nm = mkUnderCon fname (ar - n) in (nm, n, ApplyCase (DConCase (-1) nm (take n (genArgs 0)) (DApp False (mkUnderCon fname (ar - (n + 1))) (map (DV . Glob) (take n (genArgs 0) ++ [sMN 0 "arg"]))))) : if (ar - (n + 2) >=0 ) then (nm, n, Apply2Case (DConCase (-1) nm (take n (genArgs 0)) (DApp False (mkUnderCon fname (ar - (n + 2))) (map (DV . Glob) (take n (genArgs 0) ++ [sMN 0 "arg0", sMN 0 "arg1"]))))) : mkApplyCase fname (n + 1) ar else mkApplyCase fname (n + 1) ar mkEval :: [(Name, Int, EvalApply DAlt)] -> (Name, DDecl) mkEval xs = (sMN 0 "EVAL", DFun (sMN 0 "EVAL") [sMN 0 "arg"] (mkBigCase (sMN 0 "EVAL") 256 (DV (Glob (sMN 0 "arg"))) (mapMaybe evalCase xs ++ [DDefaultCase (DV (Glob (sMN 0 "arg")))]))) where evalCase (n, t, EvalCase x) = Just (x (sMN 0 "arg")) evalCase _ = Nothing mkApply :: [(Name, Int, EvalApply DAlt)] -> (Name, DDecl) mkApply xs = (sMN 0 "APPLY", DFun (sMN 0 "APPLY") [sMN 0 "fn", sMN 0 "arg"] (case mapMaybe applyCase xs of [] -> DNothing cases -> mkBigCase (sMN 0 "APPLY") 256 (DV (Glob (sMN 0 "fn"))) (cases ++ [DDefaultCase DNothing]))) where applyCase (n, t, ApplyCase x) = Just x applyCase _ = Nothing mkApply2 :: [(Name, Int, EvalApply DAlt)] -> (Name, DDecl) mkApply2 xs = (sMN 0 "APPLY2", DFun (sMN 0 "APPLY2") [sMN 0 "fn", sMN 0 "arg0", sMN 0 "arg1"] (case mapMaybe applyCase xs of [] -> DNothing cases -> mkBigCase (sMN 0 "APPLY") 256 (DV (Glob (sMN 0 "fn"))) (cases ++ [DDefaultCase (DApp False (sMN 0 "APPLY") [DApp False (sMN 0 "APPLY") [DV (Glob (sMN 0 "fn")), DV (Glob (sMN 0 "arg0"))], DV (Glob (sMN 0 "arg1"))]) ]))) where applyCase (n, t, Apply2Case x) = Just x applyCase _ = Nothing declare :: Int -> [(Name, Int, EvalApply DAlt)] -> [(Name, DDecl)] declare t xs = dec' t xs [] where dec' t [] acc = reverse acc dec' t ((n, ar, _) : xs) acc = dec' (t + 1) xs ((n, DConstructor n t ar) : acc) genArgs i = sMN i "P_c" : genArgs (i + 1) mkFnCon n = sMN 0 ("P_" ++ show n) mkUnderCon n 0 = n mkUnderCon n missing = sMN missing ("U_" ++ show n) instance Show DExp where show e = show' [] e where show' env (DV (Loc i)) = "var " ++ env!!i show' env (DV (Glob n)) = "GLOB " ++ show n show' env (DApp _ e args) = show e ++ "(" ++ showSep ", " (map (show' env) args) ++")" show' env (DLet n v e) = "let " ++ show n ++ " = " ++ show' env v ++ " in " ++ show' (env ++ [show n]) e show' env (DUpdate n e) = "!update " ++ show n ++ "(" ++ show' env e ++ ")" show' env (DC loc i n args) = atloc loc ++ "CON " ++ show n ++ "(" ++ showSep ", " (map (show' env) args) ++ ")" where atloc Nothing = "" atloc (Just l) = "@" ++ show (LV l) ++ ":" show' env (DProj t i) = show t ++ "!" ++ show i show' env (DCase up e alts) = "case" ++ update ++ show' env e ++ " of {\n\t" ++ showSep "\n\t| " (map (showAlt env) alts) where update = case up of Shared -> " " Updatable -> "! " show' env (DChkCase e alts) = "case' " ++ show' env e ++ " of {\n\t" ++ showSep "\n\t| " (map (showAlt env) alts) show' env (DConst c) = show c show' env (DForeign ty n args) = "foreign " ++ show n ++ "(" ++ showSep ", " (map (show' env) (map snd args)) ++ ")" show' env (DOp f args) = show f ++ "(" ++ showSep ", " (map (show' env) args) ++ ")" show' env (DError str) = "error " ++ show str show' env DNothing = "____" showAlt env (DConCase _ n args e) = show n ++ "(" ++ showSep ", " (map show args) ++ ") => " ++ show' env e showAlt env (DConstCase c e) = show c ++ " => " ++ show' env e showAlt env (DDefaultCase e) = "_ => " ++ show' env e -- | Divide up a large case expression so that each has a maximum of -- 'max' branches mkBigCase cn max arg branches | length branches <= max = DChkCase arg branches | otherwise = -- DChkCase arg branches -- until I think of something... -- divide the branches into groups of at most max (by tag), -- generate a new case and shrink, recursively let bs = sortBy tagOrd branches (all, def) = case (last bs) of DDefaultCase t -> (init all, Just (DDefaultCase t)) _ -> (all, Nothing) bss = groupsOf max all cs = map mkCase bss in DChkCase arg branches where mkCase bs = DChkCase arg bs tagOrd (DConCase t _ _ _) (DConCase t' _ _ _) = compare t t' tagOrd (DConstCase c _) (DConstCase c' _) = compare c c' tagOrd (DDefaultCase _) (DDefaultCase _) = EQ tagOrd (DConCase _ _ _ _) (DDefaultCase _) = LT tagOrd (DConCase _ _ _ _) (DConstCase _ _) = LT tagOrd (DConstCase _ _) (DDefaultCase _) = LT tagOrd (DDefaultCase _) (DConCase _ _ _ _) = GT tagOrd (DConstCase _ _) (DConCase _ _ _ _) = GT tagOrd (DDefaultCase _) (DConstCase _ _) = GT groupsOf :: Int -> [DAlt] -> [[DAlt]] groupsOf x [] = [] groupsOf x xs = let (batch, rest) = span (tagLT (x + tagHead xs)) xs in batch : groupsOf x rest where tagHead (DConstCase (I i) _ : _) = i tagHead (DConCase t _ _ _ : _) = t tagHead (DDefaultCase _ : _) = -1 -- must be the end tagLT i (DConstCase (I j) _) = i < j tagLT i (DConCase j _ _ _) = i < j tagLT i (DDefaultCase _) = False dumpDefuns :: DDefs -> String dumpDefuns ds = showSep "\n" $ map showDef (toAlist ds) where showDef (x, DFun fn args exp) = show fn ++ "(" ++ showSep ", " (map show args) ++ ") = \n\t" ++ show exp ++ "\n" showDef (x, DConstructor n t a) = "Constructor " ++ show n ++ " " ++ show t
tpsinnem/Idris-dev
src/IRTS/Defunctionalise.hs
bsd-3-clause
16,192
0
25
6,053
6,209
3,126
3,083
292
36
-- !!! Testing the Word Enum instances. module Main(main) where import Control.Exception import Data.Word import Data.Int main = do putStrLn "Testing Enum Word8:" testEnumWord8 putStrLn "Testing Enum Word16:" testEnumWord16 putStrLn "Testing Enum Word32:" testEnumWord32 putStrLn "Testing Enum Word64:" testEnumWord64 testEnumWord8 :: IO () testEnumWord8 = do -- succ printTest ((succ (0::Word8))) printTest ((succ (minBound::Word8))) mayBomb (printTest ((succ (maxBound::Word8)))) -- pred printTest (pred (1::Word8)) printTest (pred (maxBound::Word8)) mayBomb (printTest (pred (minBound::Word8))) -- toEnum printTest ((map (toEnum::Int->Word8) [1, fromIntegral (minBound::Word8)::Int, fromIntegral (maxBound::Word8)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word8)) -- fromEnum printTest ((map fromEnum [(1::Word8),minBound,maxBound])) -- [x..] aka enumFrom printTest ((take 7 [(1::Word8)..])) printTest ((take 7 [((maxBound::Word8)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word8),2..])) printTest ((take 7 [(1::Word8),7..])) printTest ((take 7 [(1::Word8),1..])) printTest ((take 7 [(1::Word8),0..])) printTest ((take 7 [(5::Word8),2..])) let x = (minBound::Word8) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word8) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word8) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word8) .. 5]))) printTest ((take 4 ([(1::Word8) .. 1]))) printTest ((take 7 ([(1::Word8) .. 0]))) printTest ((take 7 ([(5::Word8) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word8)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word8)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word8),4..1])) printTest ((take 7 [(5::Word8),3..1])) printTest ((take 7 [(5::Word8),3..2])) printTest ((take 7 [(1::Word8),2..1])) printTest ((take 7 [(2::Word8),1..2])) printTest ((take 7 [(2::Word8),1..1])) printTest ((take 7 [(2::Word8),3..1])) let x = (maxBound::Word8) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word8) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord16 :: IO () testEnumWord16 = do -- succ printTest ((succ (0::Word16))) printTest ((succ (minBound::Word16))) mayBomb (printTest ((succ (maxBound::Word16)))) -- pred printTest (pred (1::Word16)) printTest (pred (maxBound::Word16)) mayBomb (printTest (pred (minBound::Word16))) -- toEnum printTest ((map (toEnum::Int->Word16) [1, fromIntegral (minBound::Word16)::Int, fromIntegral (maxBound::Word16)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word16)) -- fromEnum printTest ((map fromEnum [(1::Word16),minBound,maxBound])) -- [x..] aka enumFrom printTest ((take 7 [(1::Word16)..])) printTest ((take 7 [((maxBound::Word16)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word16),2..])) printTest ((take 7 [(1::Word16),7..])) printTest ((take 7 [(1::Word16),1..])) printTest ((take 7 [(1::Word16),0..])) printTest ((take 7 [(5::Word16),2..])) let x = (minBound::Word16) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word16) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word16) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word16) .. 5]))) printTest ((take 4 ([(1::Word16) .. 1]))) printTest ((take 7 ([(1::Word16) .. 0]))) printTest ((take 7 ([(5::Word16) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word16)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word16)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word16),4..1])) printTest ((take 7 [(5::Word16),3..1])) printTest ((take 7 [(5::Word16),3..2])) printTest ((take 7 [(1::Word16),2..1])) printTest ((take 7 [(2::Word16),1..2])) printTest ((take 7 [(2::Word16),1..1])) printTest ((take 7 [(2::Word16),3..1])) let x = (maxBound::Word16) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word16) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord32 :: IO () testEnumWord32 = do -- succ printTest ((succ (0::Word32))) printTest ((succ (minBound::Word32))) mayBomb (printTest ((succ (maxBound::Word32)))) -- pred printTest (pred (1::Word32)) printTest (pred (maxBound::Word32)) mayBomb (printTest (pred (minBound::Word32))) -- toEnum printTest ((map (toEnum::Int->Word32) [1, fromIntegral (minBound::Word32)::Int, fromIntegral (maxBound::Int32)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word32)) -- fromEnum printTest ((map fromEnum [(1::Word32),minBound,fromIntegral (maxBound::Int)])) mayBomb (printTest (fromEnum (maxBound::Word32))) -- [x..] aka enumFrom printTest ((take 7 [(1::Word32)..])) printTest ((take 7 [((maxBound::Word32)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word32),2..])) printTest ((take 7 [(1::Word32),7..])) printTest ((take 7 [(1::Word32),1..])) printTest ((take 7 [(1::Word32),0..])) printTest ((take 7 [(5::Word32),2..])) let x = (minBound::Word32) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word32) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word32) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word32) .. 5]))) printTest ((take 4 ([(1::Word32) .. 1]))) printTest ((take 7 ([(1::Word32) .. 0]))) printTest ((take 7 ([(5::Word32) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word32)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word32)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word32),4..1])) printTest ((take 7 [(5::Word32),3..1])) printTest ((take 7 [(5::Word32),3..2])) printTest ((take 7 [(1::Word32),2..1])) printTest ((take 7 [(2::Word32),1..2])) printTest ((take 7 [(2::Word32),1..1])) printTest ((take 7 [(2::Word32),3..1])) let x = (maxBound::Word32) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word32) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord64 :: IO () testEnumWord64 = do -- succ printTest ((succ (0::Word64))) printTest ((succ (minBound::Word64))) mayBomb (printTest ((succ (maxBound::Word64)))) -- pred printTest (pred (1::Word64)) printTest (pred (maxBound::Word64)) mayBomb (printTest (pred (minBound::Word64))) -- toEnum mayBomb (printTest ((map (toEnum::Int->Word64) [1, fromIntegral (minBound::Word64)::Int, maxBound::Int]))) mayBomb (printTest ((toEnum (maxBound::Int))::Word64)) -- fromEnum printTest ((map fromEnum [(1::Word64),minBound,fromIntegral (maxBound::Int)])) mayBomb (printTest (fromEnum (maxBound::Word64))) -- [x..] aka enumFrom printTest ((take 7 [(1::Word64)..])) printTest ((take 7 [((maxBound::Word64)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word64),2..])) printTest ((take 7 [(1::Word64),7..])) printTest ((take 7 [(1::Word64),1..])) printTest ((take 7 [(1::Word64),0..])) printTest ((take 7 [(5::Word64),2..])) let x = (minBound::Word64) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word64) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word64) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word64) .. 5]))) printTest ((take 4 ([(1::Word64) .. 1]))) printTest ((take 7 ([(1::Word64) .. 0]))) printTest ((take 7 ([(5::Word64) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word64)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word64)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word64),4..1])) printTest ((take 7 [(5::Word64),3..1])) printTest ((take 7 [(5::Word64),3..2])) printTest ((take 7 [(1::Word64),2..1])) printTest ((take 7 [(2::Word64),1..2])) printTest ((take 7 [(2::Word64),1..1])) printTest ((take 7 [(2::Word64),3..1])) let x = (maxBound::Word64) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word64) + 5 printTest ((take 7 [x,(x-1)..minBound])) -- -- -- Utils -- -- mayBomb x = catch x (\(ErrorCall e) -> putStrLn ("error " ++ show e)) `catch` (\e -> putStrLn ("Fail: " ++ show (e :: SomeException)))
sdiehl/ghc
libraries/base/tests/enum03.hs
bsd-3-clause
8,689
0
15
1,559
4,799
2,623
2,176
181
1
module GuardsIn1 where merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a] merge cmp xs [] = xs merge cmp [] ys = ys merge cmp (x:xs) (y:ys) = case x `cmp` y of GT -> y : merge cmp (x:xs) ys _ -> x : merge cmp xs (y:ys) {- mergeIt xs ys = merge compare xs ys -} mergeIt :: (a -> a -> Ordering) -> [a] -> [a] -> [a] mergeIt xs [] = xs mergeIt [] ys = ys mergeIt (x:xs) (y:ys) | x `compare` y == GT = y : merge compare (x:xs) ys | otherwise = x : merge compare xs (y:ys) {- select first occurrence of merge cmp (x:xs) ys to replace it with mergeIt (x:xs) ys -}
mpickering/HaRe
old/testing/generativeFold/GuardsIn1.hs
bsd-3-clause
611
0
11
182
301
160
141
14
2
module Main where -- import Data.Default.Class (def) import qualified Network.IRC as IRC import qualified Data.Text.Encoding as TE import qualified Data.Text as T import qualified Network.TLS as TLS import BasePrelude hiding (handle) import Utils host :: HostName host = "irc.feelings.blackfriday" port :: PortNumber port = 6697 setup :: Context -> IO () setup context = do let s m = do { print (encode m); (TLS.sendData context . encode) m } s (IRC.Message Nothing "CAP" ["REQ", "multi-prefix", "sasl"]) s (IRC.Message Nothing "PASS" ["whiskme"]) s (IRC.nick "thomashauk") s (IRC.user "thomashauk" "localhost" "*" "Thomas Hauk") s (IRC.Message Nothing "CAP" ["LS"]) main :: IO () main = do context <- makeContext host port -- TLS.contextHookSetLogging context (ioLogging . packetLogging $ def) TLS.handshake context forkIO $ setup context forever (receive context) where receive context = do datum <- TLS.recvData context (putStrLn . T.unpack . TE.decodeUtf8) datum
hlian/thomas-hauk
src/Main.hs
mit
1,015
0
16
189
341
176
165
28
1
{- OPTIONS_GHC -funbox-strict-fields -} module Crypto.PubKey.OpenSsh.Types where import Data.ByteString (ByteString) import qualified Crypto.Types.PubKey.DSA as DSA import qualified Crypto.Types.PubKey.RSA as RSA data OpenSshPrivateKey = OpenSshPrivateKeyRsa !RSA.PrivateKey | OpenSshPrivateKeyDsa !DSA.PrivateKey !DSA.PublicNumber deriving (Eq, Show) -- | Public key contains `RSA` or `DSA` key and OpenSSH key description data OpenSshPublicKey = OpenSshPublicKeyRsa !RSA.PublicKey !ByteString | OpenSshPublicKeyDsa !DSA.PublicKey !ByteString deriving (Eq, Show) data OpenSshKeyType = OpenSshKeyTypeRsa | OpenSshKeyTypeDsa deriving (Eq, Show)
knsd/crypto-pubkey-openssh
src/Crypto/PubKey/OpenSsh/Types.hs
mit
727
0
8
150
134
78
56
27
0
{-# Language DeriveFunctor #-} {-# Language DeriveTraversable #-} {-# Language DeriveFoldable #-} module Unison.Parser where import Control.Applicative import Control.Monad import Data.Char (isSpace) import Data.List hiding (takeWhile) import Data.Maybe import Prelude hiding (takeWhile) import qualified Data.Char as Char import qualified Prelude import Debug.Trace data Env s = Env { overallInput :: String , offset :: !Int , state :: !s , currentInput :: String } -- always just `drop offset overallInput` newtype Parser s a = Parser { run' :: Env s -> Result s a } root :: Parser s a -> Parser s a root p = ignored *> (p <* (optional semicolon <* eof)) semicolon :: Parser s () semicolon = void $ token (char ';') semicolon2 :: Parser s () semicolon2 = semicolon *> semicolon eof :: Parser s () eof = Parser $ \env -> case (currentInput env) of [] -> Succeed () (state env) 0 _ -> Fail [Prelude.takeWhile (/= '\n') (currentInput env), "expected eof"] False attempt :: Parser s a -> Parser s a attempt p = Parser $ \s -> case run' p s of Fail stack _ -> Fail stack False succeed -> succeed run :: Parser s a -> String -> s -> Result s a run p s s0 = run' p (Env s 0 s0 s) unsafeRun :: Parser s a -> String -> s -> a unsafeRun p s s0 = case toEither $ run p s s0 of Right a -> a Left e -> error ("Parse error:\n" ++ e) unsafeGetSucceed :: Result s a -> a unsafeGetSucceed r = case r of Succeed a _ _ -> a Fail e _ -> error (unlines ("Parse error:":e)) string :: String -> Parser s String string s = Parser $ \env -> if s `isPrefixOf` (currentInput env) then Succeed s (state env) (length s) else Fail ["expected " ++ s ++ ", got " ++ takeLine (currentInput env)] False takeLine :: String -> String takeLine = Prelude.takeWhile (/= '\n') char :: Char -> Parser s Char char c = Parser $ \env -> if listToMaybe (currentInput env) == Just c then Succeed c (state env) 1 else Fail ["expected " ++ show c ++ ", got " ++ takeLine (currentInput env)] False one :: (Char -> Bool) -> Parser s Char one f = Parser $ \env -> case (currentInput env) of (h:_) | f h -> Succeed h (state env) 1 _ -> Fail [] False base64string' :: String -> Parser s String base64string' alphabet = concat <$> many base64group where base64group :: Parser s String base64group = do chars <- some $ one (`elem` alphabet) padding <- sequenceA (replicate (padCount $ length chars) (char '=')) return $ chars ++ padding padCount :: Int -> Int padCount len = case len `mod` 4 of 0 -> 0; n -> 4 - n base64urlstring :: Parser s String base64urlstring = base64string' $ ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9'] ++ "-_" notReservedChar :: Char -> Bool notReservedChar = (`notElem` "\".,`[]{}:;()") identifier :: [String -> Bool] -> Parser s String identifier = identifier' [not . isSpace, notReservedChar] identifier' :: [Char -> Bool] -> [String -> Bool] -> Parser s String identifier' charTests stringTests = do i <- takeWhile1 "identifier" (\c -> all ($ c) charTests) guard (all ($ i) stringTests) pure i -- a wordyId isn't all digits, isn't all symbols, and isn't a symbolyId wordyId :: [String] -> Parser s String wordyId keywords = do op <- (False <$ symbolyId keywords) <|> pure True guard op token $ f <$> sepBy1 dot id where dot = char '.' id = identifier [any (not . Char.isDigit), any Char.isAlphaNum, (`notElem` keywords)] f segs = intercalate "." segs -- a symbolyId is all symbols symbolyId :: [String] -> Parser s String symbolyId keywords = scope "operator" . token $ do op <- identifier' [notReservedChar, (/= '_'), not . Char.isSpace, \c -> Char.isSymbol c || Char.isPunctuation c] [(`notElem` keywords)] qual <- optional (char '_' *> wordyId keywords) pure $ maybe op (\qual -> qual ++ "." ++ op) qual token :: Parser s a -> Parser s a token p = p <* ignored haskellLineComment :: Parser s () haskellLineComment = void $ string "--" *> takeWhile "-- comment" (/= '\n') lineErrorUnless :: String -> Parser s a -> Parser s a lineErrorUnless s = commit . scope s currentLine' :: Env s -> String currentLine' (Env overall i s cur) = before ++ restOfLine where -- this grabs the current line up to current offset, i before = reverse . Prelude.takeWhile (/= '\n') . reverse . take i $ overall restOfLine = Prelude.takeWhile (/= '\n') cur currentLine :: Parser s String currentLine = Parser $ \env -> Succeed (currentLine' env) (state env) 0 parenthesized :: Parser s a -> Parser s a parenthesized p = lp *> body <* rp where lp = token (char '(') body = p rp = lineErrorUnless "missing )" $ token (char ')') takeWhile :: String -> (Char -> Bool) -> Parser s String takeWhile msg f = scope msg . Parser $ \(Env _ _ s cur) -> let hd = Prelude.takeWhile f cur in Succeed hd s (length hd) takeWhile1 :: String -> (Char -> Bool) -> Parser s String takeWhile1 msg f = scope msg . Parser $ \(Env _ _ s cur) -> let hd = Prelude.takeWhile f cur in if null hd then Fail [] False else Succeed hd s (length hd) whitespace :: Parser s () whitespace = void $ takeWhile "whitespace" Char.isSpace whitespace1 :: Parser s () whitespace1 = void $ takeWhile1 "whitespace1" Char.isSpace nonempty :: Parser s a -> Parser s a nonempty p = Parser $ \s -> case run' p s of Succeed _ _ 0 -> Fail [] False ok -> ok scope :: String -> Parser s a -> Parser s a scope s p = Parser $ \env -> case run' p env of Fail e b -> Fail (currentLine' env : s:e) b ok -> ok commit :: Parser s a -> Parser s a commit p = Parser $ \input -> case run' p input of Fail e _ -> Fail e True Succeed a s n -> Succeed a s n sepBy :: Parser s a -> Parser s b -> Parser s [b] sepBy sep pb = f <$> optional (sepBy1 sep pb) where f Nothing = [] f (Just l) = l sepBy1 :: Parser s a -> Parser s b -> Parser s [b] sepBy1 sep pb = (:) <$> pb <*> many (sep *> pb) ignored :: Parser s () ignored = void $ many (whitespace1 <|> haskellLineComment) toEither :: Result s a -> Either String a toEither (Fail e _) = Left (intercalate "\n" e) toEither (Succeed a _ _) = Right a data Result s a = Fail [String] !Bool | Succeed a s !Int deriving (Show,Functor,Foldable,Traversable) get :: Parser s s get = Parser (\env -> Succeed (state env) (state env) 0) set :: s -> Parser s () set s = Parser (\env -> Succeed () s 0) instance Functor (Parser s) where fmap = liftM instance Applicative (Parser s) where pure = return (<*>) = ap instance Alternative (Parser s) where empty = mzero (<|>) = mplus instance Monad (Parser s) where return a = Parser $ \env -> Succeed a (state env) 0 Parser p >>= f = Parser $ \env@(Env overall i s cur) -> case p env of Succeed a s n -> case run' (f a) (Env overall (i+n) s (drop n cur)) of Succeed b s m -> Succeed b s (n+m) Fail e b -> Fail e b Fail e b -> Fail e b fail msg = Parser $ const (Fail [msg] False) instance MonadPlus (Parser s) where mzero = Parser $ \_ -> Fail [] False mplus p1 p2 = Parser $ \env -> case run' p1 env of Fail _ False -> run' p2 env ok -> ok
nightscape/platform
shared/src/Unison/Parser.hs
mit
7,106
0
16
1,633
3,132
1,591
1,541
183
2
{-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Prelude hiding (catch) import CV.Image import System.Environment import Data.IORef import GHC.Exts (unsafeCoerce#) import System.Directory import System.FilePath import Control.Exception import Control.Applicative import qualified GHC as GHC import qualified MonadUtils as GHC import qualified GHC.Paths as GHC import qualified Bag as GHC import qualified Outputable as GHC import qualified ErrUtils as GHC import qualified HscTypes as GHC import qualified DynFlags as GHC import ProtectHandlers main = do [target] <- getArgs Just i <- loadImage "/tmp/res/monalisa.jpg" (msgs,f) <- compile "/space/heatolsa/projects/jyu.cvw3/src/f.hs" mapM_ putStrLn msgs let res = f <*> Just i case res of Just x -> saveImage ("/tmp/res/"++target) x Nothing -> putStrLn "Hmpf!" type Func = Image GrayScale D32 -> Image GrayScale D32 type CompileResult = ([String], Maybe Func) {-| Compile the module in the given file name, and return the named value with the given type. If the type passed in doesn't match the way the result is used, the server process will likely segfault. -} compile :: FilePath -> IO CompileResult compile fn = doWithErrors $ do dflags <- GHC.getSessionDynFlags let dflags1 = dflags { GHC.ghcMode = GHC.CompManager, GHC.ghcLink = GHC.LinkInMemory, GHC.hscTarget = GHC.HscInterpreted -- GHC.safeHaskell = GHC.Sf_Safe, -- GHC.packageFlags = [GHC.TrustPackage "CV", -- GHC.TrustPackage "base"] } let dflags2 = GHC.xopt_unset dflags1 GHC.Opt_MonomorphismRestriction let dflags3 = GHC.xopt_set dflags2 GHC.Opt_MonoLocalBinds -- let dflags4 = GHC.dopt_set dflags3 GHC.Opt_PackageTrust GHC.setSessionDynFlags dflags3 target <- GHC.guessTarget fn Nothing GHC.setTargets [target] r <- fmap GHC.succeeded (GHC.load GHC.LoadAllTargets) case r of True -> do mods <- GHC.getModuleGraph let mainMod = GHC.ms_mod (head mods) GHC.setContext [ GHC.IIModule mainMod ] v <- GHC.compileExpr expr return (Just (unsafeCoerce# v)) False -> return Nothing where expr = "f :: Image GrayScale D32 -> Image GrayScale D32" {-| Runs an action in the 'Ghc' monad, and automatically collects error messages. There are multiple ways error messages get reported, and it's a bit of tricky trial-and-error to handle them all uniformly, so this function abstracts that. -} doWithErrors :: GHC.Ghc (Maybe Func) -> IO CompileResult doWithErrors action = do codeErrors <- newIORef [] protectHandlers $ catch (wrapper codeErrors) $ \ (e :: SomeException) -> do errs <- readIORef codeErrors return (errs, Nothing) where wrapper codeErrors = fixupErrors codeErrors =<< do GHC.defaultErrorHandler (logAction codeErrors) $ GHC.runGhc (Just GHC.libdir) $ GHC.handleSourceError (handle codeErrors) $ do dflags <- GHC.getSessionDynFlags GHC.setSessionDynFlags dflags { GHC.log_action = logAction codeErrors } action logAction errs _ span style msg = let niceError = GHC.showSDoc $ GHC.withPprStyle style $ GHC.mkLocMessage span msg in writeErr errs niceError writeErr ref err = modifyIORef ref (++ [ err ]) handle ref se = do let errs = GHC.bagToList (GHC.srcErrorMessages se) cleaned = map (GHC.showSDoc . GHC.errMsgShortDoc) errs GHC.liftIO $ modifyIORef ref (++ cleaned) return Nothing fixupErrors errs (Just x) = fmap (, Just x) (readIORef errs) fixupErrors errs Nothing = fmap (, Nothing) (readIORef errs) qualifiedImportDecl m a = (GHC.simpleImportDecl (GHC.mkModuleName m)) { GHC.ideclQualified = True, GHC.ideclAs = Just (GHC.mkModuleName a) }
deggis/CV-web
src/tester.hs
mit
4,186
0
18
1,099
1,000
511
489
87
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} module Control.Eff.Log ( Log(Log, logLine) , Logger , logE , filterLog , filterLog' , runLogPure , runLogStdout , runLogStderr , runLogFile , runLogWithLoggerSet , runLog -- | reexports from fast-logger , ToLogStr(toLogStr) , LogStr ) where import Control.Applicative ((<$>), (<*)) import Control.Eff ((:>), Eff, Member, SetMember, VE (..), admin, handleRelay, inj, interpose, send) import Control.Eff.Lift (Lift, lift) import Data.Monoid ((<>)) import Data.Typeable (Typeable, Typeable1) import System.Log.FastLogger (LogStr, LoggerSet, ToLogStr, defaultBufSize, flushLogStr, fromLogStr, newFileLoggerSet, newStderrLoggerSet, newStdoutLoggerSet, pushLogStr, toLogStr) import qualified Data.ByteString.Char8 as B8 data Log a v = Log { logLine :: a , logNext :: v } deriving (Typeable, Functor) -- | a monadic action that does the real logging type Logger m l = forall v. Log l v -> m () -- | Log something. logE :: (Typeable l, Member (Log l) r) => l -> Eff r () logE line = send $ \next -> inj (Log line (next ())) -- | Collect log messages in a list. runLogPure :: (Typeable l) => Eff (Log l :> r) a -> Eff r (a, [l]) runLogPure = go . admin where go (Val v) = return (v, []) go (E req) = handleRelay req go performLog performLog l = fmap (prefixLogWith l) (go (logNext l)) prefixLogWith log' (v, l) = (v, logLine log' : l) -- | Run the 'Logger' action in the base monad for every log line. runLog :: (Typeable l, Typeable1 m, SetMember Lift (Lift m) r) => Logger m l -> Eff (Log l :> r) a -> Eff r a runLog logger = go . admin where go (Val v) = return v go (E req) = handleRelay req go performLog performLog l = lift (logger l) >> go (logNext l) -- | Filter Log entries with a predicate. -- -- Note that, most of the time an explicit type signature for the predicate -- will be required. filterLog :: (Typeable l, Member (Log l) r) => (l -> Bool) -> Eff r a -> Eff r a filterLog f = go . admin where go (Val v) = return v go (E req) = interpose req go filter' where filter' (Log l v) = if f l then send (<$> req) >>= go else go v -- | Filter Log entries with a predicate and a proxy. -- -- This is the same as 'filterLog' but with a proxy l for type inference. filterLog' :: (Typeable l, Member (Log l) r) => (l -> Bool) -> proxy l -> Eff r a -> Eff r a filterLog' predicate _ = filterLog predicate -- | Log to stdout. runLogStdout :: (Typeable l, ToLogStr l, SetMember Lift (Lift IO) r) => proxy l -> Eff (Log l :> r) a -> Eff r a runLogStdout proxy eff = do s <- lift $ newStdoutLoggerSet defaultBufSize runLogWithLoggerSet s proxy eff <* lift (flushLogStr s) -- | Log to stderr. runLogStderr :: (Typeable l, ToLogStr l, SetMember Lift (Lift IO) r) => proxy l -> Eff (Log l :> r) a -> Eff r a runLogStderr proxy eff = do s <- lift $ newStderrLoggerSet defaultBufSize runLogWithLoggerSet s proxy eff <* lift (flushLogStr s) -- | Log to file. runLogFile :: (Typeable l, ToLogStr l, SetMember Lift (Lift IO) r) => FilePath -> proxy l -> Eff (Log l :> r) a -> Eff r a runLogFile f proxy eff = do s <- lift $ newFileLoggerSet defaultBufSize f runLogWithLoggerSet s proxy eff <* lift (flushLogStr s) -- | Log to a file using a 'LoggerSet'. -- -- Note, that you will still have to call 'flushLogStr' on the 'LoggerSet' -- at one point. -- -- With that function you can combine a logger in a surrounding IO action -- with a logger in the 'Eff' effect. -- -- >data Proxy a = Proxy -- > -- > main :: IO () -- > main = do -- > loggerSet <- newStderrLoggerSet defaultBufSize -- > pushLogStr loggerSet "logging from outer space^WIO\n" -- > runLift $ runLogWithLoggerSet loggerSet (Proxy :: Proxy String) $ -- > logE ("logging from within Eff" :: String) -- > flushLogStr loggerSet runLogWithLoggerSet :: (Typeable l, ToLogStr l, SetMember Lift (Lift IO) r) => LoggerSet -> proxy l -> Eff (Log l :> r) a -> Eff r a runLogWithLoggerSet s _ = runLog (loggerSetLogger s) loggerSetLogger :: ToLogStr l => LoggerSet -> Logger IO l loggerSetLogger loggerSet = pushLogStr loggerSet . (<> "\n") . toLogStr . logLine
ibotty/log-effect
src/Control/Eff/Log.hs
mit
4,653
0
12
1,192
1,406
755
651
89
3
{-# LANGUAGE TypeFamilies #-} -- | Defines types used generally in the program module Types ( Trans (..) , Turn (..) , Point (..) , BVect (..) ) where -------------------------------------------------------------------------------- ------------------------------------ Header ------------------------------------ -------------------------------------------------------------------------------- -- Imports import Data.AdditiveGroup import Data.AffineSpace import Data.VectorSpace -------------------------------------------------------------------------------- ------------------------------------ Types ------------------------------------- -------------------------------------------------------------------------------- -- | A translation move data Trans = E -- ^ east | W -- ^ west | SE -- ^ southeast | SW -- ^ southwest deriving (Eq, Show, Read) -- | A turn move data Turn = CW -- ^ clockwise | ACW -- ^ anticlockwise deriving (Eq, Show, Read) -- | A point in 2D space -- We derive 'Ord' because 'Point's are used as keys in 'Data.Map's. -- The ordering is lexicographic. data Point = Point { getX :: Int , getY :: Int } deriving (Eq, Ord, Show, Read) -- | An integer-valued vector with an east-southwest basis. -- These represent directions on the board. data BVect = BVect { getE :: Int , getSW :: Int } deriving (Eq, Show, Read) -- | A move can either be a translation or a rotation data Move = Shift Trans -- ^ Translation | Rotate Turn -- ^ Rotation deriving (Eq, Show, Read) -------------------------------------------------------------------------------- ---------------------------------- Instances ----------------------------------- -------------------------------------------------------------------------------- -- | 'BVect's can be added and subtracted and have an identity (@BVect 0 0@). instance AdditiveGroup BVect where zeroV = BVect 0 0 BVect x1 y1 ^+^ BVect x2 y2 = BVect (x1+x2) (y1+y2) negateV (BVect x1 y1) = BVect (-x1) (-y1) -- | 'BVect's can be scaled by an integer scalar. instance VectorSpace BVect where type Scalar BVect = Int c *^ BVect x y = BVect (c*x) (c*y) -- | 'Point's can be added with 'BVect's and can be subtracted. instance AffineSpace Point where type Diff Point = BVect Point x y .+^ BVect e sw = Point x' y' where y' = y + sw x' = x + e - sw + case (odd y, odd y') of (False, True) -> 0 _ -> 1 Point x' y' .-. Point x y = BVect e sw where sw = y' - y e = x' - x + sw - case (odd y, odd y') of (False, True) -> 0 _ -> 1
sebmathguy/icfp-2015
library/Types.hs
mit
2,885
0
12
795
575
323
252
44
0
module CFDI.Types.Suburb where import CFDI.Types.Type import Control.Error.Safe (justErr) import Text.Read (readMaybe) newtype Suburb = Suburb Int deriving (Eq, Read, Show) instance Type Suburb where parseExpr c = justErr NotInCatalog maybeSuburb where maybeSuburb = Suburb <$> (readMaybe c >>= isValid) isValid x | x > 0 && x < 10000 = Just x | otherwise = Nothing render (Suburb x) = replicate (4 - length xStr) '0' ++ xStr where xStr = show x
yusent/cfdis
src/CFDI/Types/Suburb.hs
mit
505
0
13
132
180
94
86
13
0
module Cis194Bench (benchmarks) where import Cis194 import Criterion benchmarks :: [Benchmark] benchmarks = [ bench "main" (nfIO main) ]
tylerjl/cis194
benchmark/Cis194Bench.hs
mit
148
0
8
30
42
25
17
6
1
main = do putStrLn "Enter a string with brackets in it: " input <- getLine putStrLn ("Your input was: " ++ input) putStrLn ("Brackets" ++ (describeBool $ bracketMatch input) ++ " matched!") bracketMatch :: String -> Bool bracketMatch [] = True bracketMatch [x] = False bracketMatch xs | -1 `elem` scan = False -- At any point a right bracket appears first | last scan /= 0 = False -- Not all left brackets have been closed | otherwise = True where scan = countBrackets xs countBrackets :: String -> [Int] countBrackets xs = scanl (\acc x -> if x == '(' then acc + 1 else if x == ')' then acc - 1 else acc) 0 xs describeBool :: Bool -> String describeBool b | b == True = " are" | otherwise = " are not"
supermitch/learn-haskell
sandbox/brackets.hs
mit
747
3
13
183
255
128
127
19
3
{-# LANGUAGE TemplateHaskell #-} module Examples where import Database.HLINQ.Info import Database.HLINQ.Utilities import Control.Monad import Language.Haskell.TH import Language.Haskell.TH.Syntax import Data.Hashable createDB "test.db" "test" --main = do -- -- checkDBConsistency -- x <- checkDBConsistency' -- case x of -- (Right _) -> do -- let results = fromTest [||$$differencesT||] -- print results -- (Left err) -> do error err range'' lb ub = [|do person <- people guard $ lb <= (age person) && (age person) < ub return $ (name person)|] range' lb ub = fromTestUntyped [|do person <- people guard $ lb <= (age person) && (age person) < ub return $ (name person)|] range = [|\lb ub -> do person <- people guard $ lb <= (age person) && (age person) < ub return $ (name person)|] rangeT :: Q (TExp (Int -> Int -> [String])) rangeT = [||\lb ub -> do person <- people test guard $ lb <= (age person) && (age person) < ub return $ (name person)||] range1 = [|\lb ub -> do person <- people return $ (name person)|] getAge = [|\name' -> do person <- people guard $ (name person) == name' return $ (age person)|] getAgeT :: Q (TExp (String -> [Int])) getAgeT = [||\name' -> do person <- people test guard $ (name person) == name' return $ (age person)||] getAge1 = [|\name' -> do person <- people return $ (age person)|] getAge' name' = fromTestUntyped [|do person <- people guard $ (name person) == name' return $ (age person)|] getAge'' = [|\name' -> do person <- people guard $ (name person) == name' return $ (age person)|] compose = [|\name1 name2 -> do age1 <- $(getAge) name1 age2 <- $(getAge) name2 $(range) age1 age2|] composeT = [||\name1 name2 -> do age1 <- $$(getAgeT) name1 age2 <- $$(getAgeT) name2 $$(rangeT) age1 age2||] differences = [|do c <- couples m <- people w <- people guard $ ((her c) == (name w)) && ((him c) == (name m)) && ((age w) > (age m)) return $ ((name w), (age w) - (age m))|] differencesT = [||do c <- couples test m <- people test w <- people test guard $ ((her c) == (name w)) && ((him c) == (name m)) && ((age w) > (age m)) return $ ((name w), (age w) - (age m))||] satisfies = [|\p -> do person <- people; guard $ (p (age person)); return $ (name person)|] satisfiesT = [||\p -> do person <- people test guard $ (p (age person)) return $ (name person)||] pre = [|(\x -> 30 < x && x <= 40)|] preT :: Q(TExp (Int->Bool)) preT = [||(\x -> 30 < x && x <= 40)||] preT2 = [||(\x -> x !! 1)||] data Predicate = Above Int | Below Int | And Predicate Predicate | Or Predicate Predicate | Not Predicate deriving (Eq, Show) p :: Predicate -> Q(TExp (Int -> Bool)) p (Above n) = [||\x -> n <= x||] p (Below n) = [||\x -> n > x||] p (And n t) = [||\x -> $$(p n) x && $$(p t) x||] p (Or n t) = [||\x -> $$(p n) x || $$(p t) x||] p (Not n) = [||\x -> not ($$(p n) x)||] t0 = And (Above 30) (Below 40) satisfiesTD = [||$$satisfiesT $$(p t0)||] a:: Int a = 30 b:: Int b = 40 rangeTT b = [||$$rangeT ($$((unsafeTExpCoerce $ lift a))) b||] rangeTT2 = [||$$rangeT $$(liftLinq a) $$(liftLinq b)||] rangeTTT a b = [||$$rangeT a b||] data NameAge = NameAge String Int deriving (Eq, Show) data Name' = Name' String deriving (Eq, Show)
juventietis/HLINQ
examples/Examples.hs
mit
3,271
27
12
722
499
362
137
-1
-1
module Ch08 where import Data.List import Data.Char import qualified Data.Map as Map import Control.Monad -- main = do -- _ <- putStrLn "Hello, what's your name?" -- name <- getLine -- putStrLn $ "Hey " ++ name ++ ", you rock!" -- main = do -- putStrLn "What's ur first name?" -- firstName <- getLine -- putStrLn "What's ur last name?" -- lastName <- getLine -- let -- bigFirstName = map toUpper firstName -- bigLastName = map toUpper lastName -- putStrLn $ "hey " ++ bigFirstName ++ " " -- ++ bigLastName ++ ", how r u?" -- main = do -- return () -- return "HAHAHA" -- line <- getLine -- return "BLAH BLAH BLAH" -- return 4 -- putStrLn $ line ++ "!" -- main = do -- a <- return "hell" -- b <- return "yeah!" -- putStrLn $ a ++ " " ++ b -- main = do -- let -- a = "hell" -- b = "yeah!" -- putStrLn $ a ++ " " ++ b -- useful IO function -- main = do -- putStr "Hey, " -- putStr "I'm " -- putStrLn "Andy!" -- putChar 't' -- putChar 'e' -- putChar 'c' -- putChar 'h' -- putStrLn "" -- main = do -- print True -- print 2 -- print "haha" -- print 3.2 -- print [3,4,3] -- putStrLn "" -- putStrLn $ show True -- putStrLn $ show 2 -- putStrLn $ show "haha" -- putStrLn $ show 3.2 -- putStrLn $ show [3,4,3] -- main = do -- input <- getLine -- when (input == "test") $ do -- putStrLn input -- input' <- getLine -- if(input' == "huk") -- then putStrLn input' -- else return () -- main = do -- a <- getLine -- b <- getLine -- c <- getLine -- print [a,b,c] -- main = do -- rs <- sequence [getLine, getLine, getLine] -- print rs -- ss <- sequence $ map print [1,2,3,4,5] -- return () -- main = do -- mapM print [1,2,3] -- main = do -- mapM_ print [4,5,6] -- main = forever $ do -- putStr "Give me some input: " -- l <- getLine -- putStrLn $ map toUpper l -- main = do -- colors <- forM [1,2,3,4] (\a-> do -- putStrLn $ "Which color do you associate with the number " -- ++ show a ++ "?" -- color <- getLine -- return color) -- putStrLn "The colors that you associate with 1,2,3 and 4 are: " -- mapM putStrLn colors -- main = do -- colors <- forM [1,2,3,4] (\a-> do -- putStrLn $ "Which color do you associate with the number " -- ++ show a ++ "?" -- getLine) -- putStrLn "The colors that you associate with 1,2,3 and 4 are: " -- mapM putStrLn colors main = do colors <- mapM (\a-> do putStrLn $ "Which color do you associate with the number " ++ show a ++ "?" color <- getLine return color) [1,2,3,4] putStrLn "The colors that you associate with 1,2,3 and 4 are: " mapM putStrLn colors
sol2man2/Learn-You-A-Haskell-For-Great-Good
src/Ch08.hs
mit
2,714
0
15
756
202
150
52
13
1
{-# htermination (properFraction :: Ratio MyInt -> Tup2 MyInt (Ratio MyInt)) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Tup2 a b = Tup2 a b ; data Integer = Integer MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ratio a = CnPc a a; fst :: Tup2 a b -> a; fst (Tup2 x _) = x; snd :: Tup2 a b -> b; snd (Tup2 _ y) = y; properFraction :: Ratio MyInt -> Tup2 MyInt (Ratio MyInt); properFraction (CnPc x y) = Tup2 (qProperFraction x y) (CnPc (rProperFraction x y) y); qProperFraction :: MyInt -> MyInt -> MyInt; qProperFraction x y = fst (quotRemMyInt x y); rProperFraction :: MyInt -> MyInt -> MyInt; rProperFraction x y = snd (quotRemMyInt x y); stop :: MyBool -> a; stop MyFalse = stop MyFalse; error :: a; error = stop MyTrue; primMinusNatS :: Nat -> Nat -> Nat; primMinusNatS (Succ x) (Succ y) = primMinusNatS x y; primMinusNatS Zero (Succ y) = Zero; primMinusNatS x Zero = x; primDivNatS0 x y MyTrue = Succ (primDivNatS (primMinusNatS x y) (Succ y)); primDivNatS0 x y MyFalse = Zero; primGEqNatS :: Nat -> Nat -> MyBool; primGEqNatS (Succ x) Zero = MyTrue; primGEqNatS (Succ x) (Succ y) = primGEqNatS x y; primGEqNatS Zero (Succ x) = MyFalse; primGEqNatS Zero Zero = MyTrue; primDivNatS :: Nat -> Nat -> Nat; primDivNatS Zero Zero = error; primDivNatS (Succ x) Zero = error; primDivNatS (Succ x) (Succ y) = primDivNatS0 x y (primGEqNatS x y); primDivNatS Zero (Succ x) = Zero; primQuotInt :: MyInt -> MyInt -> MyInt; primQuotInt (Pos x) (Pos (Succ y)) = Pos (primDivNatS x (Succ y)); primQuotInt (Pos x) (Neg (Succ y)) = Neg (primDivNatS x (Succ y)); primQuotInt (Neg x) (Pos (Succ y)) = Neg (primDivNatS x (Succ y)); primQuotInt (Neg x) (Neg (Succ y)) = Pos (primDivNatS x (Succ y)); primQuotInt vx vy = error; primModNatS0 x y MyTrue = primModNatS (primMinusNatS x (Succ y)) (Succ (Succ y)); primModNatS0 x y MyFalse = Succ x; primModNatS :: Nat -> Nat -> Nat; primModNatS Zero Zero = error; primModNatS Zero (Succ x) = Zero; primModNatS (Succ x) Zero = error; primModNatS (Succ x) (Succ Zero) = Zero; primModNatS (Succ x) (Succ (Succ y)) = primModNatS0 x y (primGEqNatS x (Succ y)); primRemInt :: MyInt -> MyInt -> MyInt; primRemInt (Pos x) (Pos (Succ y)) = Pos (primModNatS x (Succ y)); primRemInt (Pos x) (Neg (Succ y)) = Pos (primModNatS x (Succ y)); primRemInt (Neg x) (Pos (Succ y)) = Neg (primModNatS x (Succ y)); primRemInt (Neg x) (Neg (Succ y)) = Neg (primModNatS x (Succ y)); primRemInt vv vw = error; primQrmInt :: MyInt -> MyInt -> Tup2 MyInt MyInt; primQrmInt x y = Tup2 (primQuotInt x y) (primRemInt x y); quotRemMyInt :: MyInt -> MyInt -> Tup2 MyInt MyInt; quotRemMyInt = primQrmInt;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/properFraction_1.hs
mit
2,763
28
9
572
1,463
712
751
62
1
module Main where import Prelude hiding (map) greet :: String -> String greet "xxx" = "who is xxx?" greet name = "Hello " ++ name ++ " !@@@" mini :: Int -> Int -> Int mini 0 0 = 0 mini x y | x > y && x == y = x | otherwise = y mio :: String -> IO String mio s = do x <- getLine abc <- getLine return $ s ++ x ++ abc main :: IO () main = do putStrLn "Haskell Programming From First Principles" putStrLn $ greet "Michael"
Numberartificial/workflow
haskell-first-principles/haskell-programming-from-first-principles-master/src/Main.hs
mit
493
0
10
170
186
92
94
16
1
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} module CSPMTypeChecker.TCExpr () where import CSPMDataStructures import CSPMTypeChecker.TCCommon import {-# SOURCE #-} CSPMTypeChecker.TCDecl import CSPMTypeChecker.TCDependencies import CSPMTypeChecker.TCPat import CSPMTypeChecker.TCMonad import CSPMTypeChecker.TCUnification import Util instance TypeCheckable PExp Type where errorConstructor = ErrorWithExp -- Important: we use the typeCheck' version after removing the annotation -- so the error message contains this node typeCheck' (Annotated srcloc typ inner) = do t' <- typeCheck' inner setPType typ t' return t' instance TypeCheckable Exp Type where errorConstructor = error "Error: expression error constructor called." typeCheck' (App f args) = do tFunc <- typeCheck f tr <- freshTypeVar tArgs <- replicateM (length args) freshTypeVar unify (TFunction tArgs tr) tFunc tArgs' <- mapM typeCheck args errorIfFalse (length tArgs == length tArgs') (IncorrectNumberOfArguments f (length tArgs)) unifiedTArgs <- zipWithM unify tArgs tArgs' return tr typeCheck' (BooleanBinaryOp op e1 e2) = do t1 <- typeCheck e1 t2 <- typeCheck e2 t <- unify t1 t2 case op of And -> ensureIsBool t Or -> ensureIsBool t Equals -> ensureHasConstraint Eq t NotEquals -> ensureHasConstraint Eq t LessThan -> ensureHasConstraint Ord t LessThanEq -> ensureHasConstraint Ord t GreaterThan -> ensureHasConstraint Ord t GreaterThanEq -> ensureHasConstraint Ord t return TBool typeCheck' (BooleanUnaryOp op e1) = do t1 <- typeCheck e1 ensureIsBool t1 return TBool typeCheck' (Concat e1 e2) = do t1 <- typeCheck e1 t2 <- typeCheck e2 ensureIsList t1 ensureIsList t2 unify t1 t2 typeCheck' (DotApp e1 e2) = do t1 <- typeCheck e1 t2 <- typeCheck e2 argt <- freshTypeVar rt <- freshTypeVar unify t1 (TDotable argt rt) unify t2 argt return rt typeCheck' (If e1 e2 e3) = do t1 <- typeCheck e1 ensureIsBool t1 t2 <- typeCheck e2 t3 <- typeCheck e3 unify t2 t3 typeCheck' (Lambda p exp) = do fvs <- freeVars p local fvs ( do tr <- typeCheck exp targ <- typeCheck p return $ TFunction [targ] tr) typeCheck' (Let decls exp) = local [] ( -- Add a new scope: typeCheckDecl will add vars into it do typeCheckDecls decls typeCheck exp) typeCheck' (Lit lit) = typeCheck lit typeCheck' (List es) = do ts <- mapM typeCheck es t <- unifyAll ts return $ TSeq t typeCheck' (ListComp es stmts) = do fvs <- concatMapM freeVars stmts errorIfFalse (noDups fvs) (DuplicatedDefinitions fvs) local fvs ( do stmts <- mapM (typeCheckStmt TSeq) stmts ts <- mapM typeCheck es t <- unifyAll ts return $ TSeq t) typeCheck' (ListEnumFrom lb) = do t1 <- typeCheck lb ensureIsInt t1 return $ TSeq TInt typeCheck' (ListEnumFromTo lb ub) = do t1 <- typeCheck lb ensureIsInt t1 t2 <- typeCheck ub ensureIsInt t1 return $ TSeq TInt typeCheck' (ListLength e) = do t1 <- typeCheck e ensureIsList t1 return $ TInt typeCheck' (MathsBinaryOp op e1 e2) = do t1 <- typeCheck e1 t2 <- typeCheck e2 ensureIsInt t1 ensureIsInt t2 return TInt typeCheck' (NegApp e1) = do t1 <- typeCheck e1 ensureIsInt t1 return TInt typeCheck' (Paren e) = typeCheck e typeCheck' (Set es) = do ts <- mapM typeCheck es t <- unifyAll ts ensureHasConstraint Eq t return $ TSet t typeCheck' (SetComp es stmts) = do fvs <- concatMapM freeVars stmts errorIfFalse (noDups fvs) (DuplicatedDefinitions fvs) local fvs ( do stmts <- mapM (typeCheckStmt TSet) stmts ts <- mapM typeCheck es t <- unifyAll ts ensureHasConstraint Eq t return $ TSet t) typeCheck' (SetEnum es) = do ts <- mapM typeCheck es mapM ensureIsChannel ts return $ TSet (TChannel TListEnd) typeCheck' (SetEnumComp es stmts) = do fvs <- concatMapM freeVars stmts errorIfFalse (noDups fvs) (DuplicatedDefinitions fvs) local fvs ( do stmts <- mapM (typeCheckStmt TSet) stmts ts <- mapM typeCheck es mapM ensureIsChannel ts return $ TSet (TChannel TListEnd)) typeCheck' (SetEnumFrom lb) = do t1 <- typeCheck lb ensureIsInt t1 -- No need to check for Eq - Ints always are return $ TSet TInt typeCheck' (SetEnumFromTo lb ub) = do t1 <- typeCheck lb ensureIsInt t1 t2 <- typeCheck ub ensureIsInt t2 -- No need to check for Eq - Ints always are return $ TSet TInt typeCheck' (Tuple es) = do ts <- mapM typeCheck es return $ TTuple ts typeCheck' (ReplicatedUserOperator n es stmts) = do fvs <- concatMapM freeVars stmts errorIfFalse (noDups fvs) (DuplicatedDefinitions fvs) local fvs ( do stmts <- mapM (typeCheckStmt TSet) stmts ts <- mapM typeCheck es opMap <- getUserOperators let opTypes = apply opMap n zipWithM unify ts opTypes return TProc) typeCheck' (UserOperator n es) = do -- TODO: possible ( I think) that some user functions -- may actually be applications ts <- mapM typeCheck es opMap <- getUserOperators let opTypes = apply opMap n zipWithM unify ts opTypes return TProc typeCheck' (Var (UnQual n)) = do t <- getType n instantiate t typeCheckStmt :: (Type -> Type) -> PStmt -> TypeCheckMonad Type typeCheckStmt typc = typeCheckStmt' typc . removeAnnotation typeCheckStmt' typc (Qualifier e) = do t <- typeCheck e ensureIsBool t typeCheckStmt' typc (Generator p exp) = do tpat <- typeCheck p texp <- typeCheck exp unify (typc tpat) texp
tomgr/tyger
src/CSPMTypeChecker/TCExpr.hs
mit
5,750
98
15
1,440
2,089
933
1,156
214
1
import qualified Data.Char as Char toDigits :: Integer -> [Integer] toDigits i | i <= 0 = [] | otherwise = f $ show i where f (x:[]) = (toInteger $ Char.digitToInt x) : [] f (x:xs) = (toInteger $ Char.digitToInt x) : f xs toDigitsRev :: Integer -> [Integer] toDigitsRev i = reverse $ toDigits i doubleEveryOther :: [Integer] -> [Integer] doubleEveryOther x = reverse [ if snd x == True then fst x * 2 else fst x | x <- zip (reverse x) (take (length x) $ cycle [False, True])] sumDigits :: [Integer] -> Integer sumDigits x = sum $ map (sum . toDigits) x validate :: Integer -> Bool validate x = f $ (sumDigits . doubleEveryOther . toDigits) x `mod` 10 where f y = if y == 0 then True else False type Peg = String type Move = (Peg, Peg) hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi 0 _ _ _ = [] hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a
samidarko/cis194
01-intro/01-intro.hs
mit
902
3
14
218
509
253
256
21
2
-- | This is a library for creating AWS CloudFormation templates. -- -- CloudFormation is a system that creates AWS resources from declarative -- templates. One common criticism of CloudFormation is its use of JSON as the -- template specification language. Once you have a large number of templates, -- possibly including cross-references among themselves, raw JSON templates -- become unwieldy, and it becomes harder to confidently modify them. -- Stratosphere alleviates this issue by providing an Embedded Domain Specific -- Language (EDSL) to construct templates. module Stratosphere ( -- * Introduction -- $intro -- * Usage -- $usage module Stratosphere.Outputs , module Stratosphere.Parameters , module Stratosphere.Resources , module Stratosphere.Template , module Stratosphere.Values , module Stratosphere.Types , module Stratosphere.Check , module Control.Lens ) where import Control.Lens import Stratosphere.Outputs import Stratosphere.Parameters import Stratosphere.Resources import Stratosphere.Template import Stratosphere.Values import Stratosphere.Types import Stratosphere.Check {-# ANN module "HLint: ignore Use import/export shortcut" #-} -- $intro -- -- The core datatype of stratosphere is the 'Template', which corresponds to a -- single CloudFormation template document. Users construct a template in a -- type-safe way using simple data types. The following example creates a -- template containing a single EC2 instance with a key pair passed in as a -- parameter: -- -- @ -- instanceTemplate :: Template -- instanceTemplate = -- template -- [ resource "EC2Instance" ( -- EC2InstanceProperties $ -- ec2Instance -- "ami-22111148" -- & eciKeyName ?~ (Ref "KeyName") -- ) -- & deletionPolicy ?~ Retain -- ] -- & description ?~ "Sample template" -- & parameters ?~ -- [ parameter \"KeyName\" \"AWS::EC2::KeyPair::KeyName\" -- & description ?~ "Name of an existing EC2 KeyPair to enable SSH access to the instance" -- & constraintDescription ?~ "Must be the name of an existing EC2 KeyPair." -- ] -- @ -- $usage -- -- The types in stratosphere attempt to map exactly to CloudFormation template -- components. For example, a template requires a set of 'Resources', and -- optionally accepts a Description, 'Parameters', etc. For each component of a -- template, there is usually a set of required arguments, and a (usually -- large) number of optional arguments. Each record type has a corresponding -- constructor function that has the required parameters as arguments. -- -- For example, since a 'Template' requires a set of Resources, the 'template' -- constructor has 'Resources' as an argument. Then, you can fill in the -- 'Maybe' parameters using lenses like '&' and '?~'. -- -- Once a 'Template' is created, you can either use Aeson's encode function, or -- use our 'encodeTemplate' function (based on aeson-pretty) to produce a JSON -- ByteString. From there, you can use your favorite tool to interact with -- CloudFormation using the template.
frontrowed/stratosphere
library/Stratosphere.hs
mit
3,136
0
5
610
152
118
34
19
0
{- | Module : $Header$ Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Printer for N-triples -} module RDF.Print where import Common.AS_Annotation import Common.Doc hiding (sepBySemis, sepByCommas) import Common.DocUtils hiding (ppWithCommas) import OWL2.AS import OWL2.Print () import RDF.AS import RDF.Symbols import RDF.Sign import qualified Data.Set as Set sepBySemis :: [Doc] -> Doc sepBySemis = vcat . punctuate (text " ;") ppWithSemis :: Pretty a => [a] -> Doc ppWithSemis = sepBySemis . map pretty sepByCommas :: [Doc] -> Doc sepByCommas = vcat . punctuate (text " ,") ppWithCommas :: Pretty a => [a] -> Doc ppWithCommas = sepByCommas . map pretty instance Pretty Predicate where pretty = printPredicate printPredicate :: Predicate -> Doc printPredicate (Predicate iri) = pretty iri instance Pretty RDFLiteral where pretty lit = case lit of RDFLiteral b lexi ty -> (if not b then text ('"' : lexi ++ "\"") else text ("\"\"\"" ++ lexi ++ "\"\"\"")) <> case ty of Typed u -> keyword cTypeS <> pretty u Untyped tag -> if tag == Nothing then empty else let Just tag2 = tag in text "@" <> text tag2 RDFNumberLit f -> text (show f) instance Pretty PredicateObjectList where pretty = printPredObjList printPredObjList :: PredicateObjectList -> Doc printPredObjList (PredicateObjectList p ol) = pretty p <+> ppWithCommas ol instance Pretty Subject where pretty = printSubject printSubject :: Subject -> Doc printSubject subj = case subj of Subject iri -> pretty iri SubjectList ls -> brackets $ ppWithSemis ls SubjectCollection c -> parens $ (hsep . map pretty) c instance Pretty Object where pretty = printObject printObject :: Object -> Doc printObject obj = case obj of Object s -> pretty s ObjectLiteral l -> pretty l instance Pretty Triples where pretty = printTriples printTriples :: Triples -> Doc printTriples (Triples s ls) = pretty s <+> ppWithSemis ls <+> dot instance Pretty Statement where pretty = printStatement printStatement :: Statement -> Doc printStatement s = case s of Statement t -> pretty t PrefixStatement (Prefix p iri) -> text "@prefix" <+> pretty p <> colon <+> pretty iri <+> dot BaseStatement (Base iri) -> text "@base" <+> pretty iri <+> dot instance Pretty TurtleDocument where pretty = printDocument printDocument :: TurtleDocument -> Doc printDocument doc = (vcat . map pretty) (statements doc) printExpandedIRI :: IRI -> Doc printExpandedIRI iri = if iriType iri == NodeID then text $ showQU iri else text "<" <> text (expandedIRI iri) <> text ">" instance Pretty Term where pretty = printTerm printTerm :: Term -> Doc printTerm t = case t of SubjectTerm iri -> printExpandedIRI iri PredicateTerm iri -> printExpandedIRI iri ObjectTerm obj -> case obj of Right lit -> pretty lit Left iri -> printExpandedIRI iri instance Pretty Axiom where pretty = printAxiom printAxiom :: Axiom -> Doc printAxiom (Axiom sub pre obj) = pretty sub <+> pretty pre <+> pretty obj <+> text "." printAxioms :: [Axiom] -> Doc printAxioms al = (vcat . map pretty) al -- | RDF signature printing printRDFBasicTheory :: (Sign, [Named Axiom]) -> Doc printRDFBasicTheory (_, l) = vsep (map (pretty . sentence) l) instance Pretty Sign where pretty = printSign printNodes :: String -> Set.Set Term -> Doc printNodes s terms = text "#" <+> text s $+$ vcat (map ((text "#\t\t" <+>) . pretty) (Set.toList terms)) printSign :: Sign -> Doc printSign s = printNodes "subjects:" (subjects s) $+$ printNodes "predicates:" (predicates s) $+$ printNodes "objects:" (objects s) -- | Symbols printing instance Pretty RDFEntityType where pretty ety = text $ show ety instance Pretty RDFEntity where pretty (RDFEntity ty ent) = pretty ty <+> pretty ent instance Pretty SymbItems where pretty (SymbItems m us) = pretty m <+> ppWithCommas us instance Pretty SymbMapItems where pretty (SymbMapItems m us) = pretty m <+> sepByCommas (map (\ (s, ms) -> sep [ pretty s , case ms of Nothing -> empty Just t -> mapsto <+> pretty t]) us) instance Pretty RawSymb where pretty rs = case rs of ASymbol e -> pretty e AnUri u -> pretty u
nevrenato/Hets_Fork
RDF/Print.hs
gpl-2.0
4,654
0
18
1,200
1,496
745
751
112
4
module CCTK.RainbowTable ( Table(), build, build1, build', crack, shape, effectiveness, load, save, unsafeMerge ) where import Control.Parallel.Strategies import Control.Monad.Random import Data.List (foldl', tails, unfoldr) import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (listToMaybe) import Data.Serialize import Data.ByteString.Lazy as LBS (readFile, writeFile) import System.Random -- |- A Rainbow table for attacking a hash function of type `h -> c` data Table h c = Table { hash :: c -> h, reduce :: [h -> c], table :: !(Map h c) } chain :: (c -> h) -> [h -> c] -> c -> c chain h = flip (foldl' (flip (.h))) attack :: (c -> h) -> [h -> c] -> h -> h attack h = flip (foldl' (flip (h.))) -- |- Check the shape of the table (colors, length) shape :: Table a b -> (Int,Int) shape (Table _ rs t) = (length rs + 1, M.size t) -- |- Attempt to crack a hash using the precomputed table crack :: Ord h => Table h c -> h -> Maybe c crack (Table h rs t) x = listToMaybe [ c' | (i,rs') <- zip [0..] (tails rs) , let y = (attack h rs') x , Just c <- [M.lookup y t] , let c' = chain h (take i rs) c , h c' == x ] -- |- Deterministically build a table for a given hash function. -- Takes a hash function to attack, a list of reducers, and a list of chain seeds. -- -- If the list of reducers is empty, the table is equivalent to a full dictionary. build' :: Ord h => (c -> h) -> [h -> c] -> [c] -> Table h c build' h rs = Table h rs . M.fromList . parMap (evalTuple2 rseq rseq) (\c -> (chain' c, c)) where chain' = h . chain h rs -- |- Iteratively build a table from a single seed. The first reducer is used to generate chains. build1 :: Ord h => (c -> h) -> [h -> c] -> Int -> c -> Table h c build1 h (r:rs) rows = Table h rs . M.fromList . take rows . unfoldr step where step c = let y = (h . chain h rs) c in Just ((y,c), r y) -- |- Build a table of the desired size, using the standard RNG build :: (RandomGen g, Ord h, Random c) => (c -> h) -> [h -> c] -> Int -> g -> Table h c build h rs rows = build' h rs . take rows . randoms effectiveness :: (Ord h, Random c) => Table h c -> IO Int effectiveness t = measure 100 0 where measure 0 n = return n measure k n = do x <- getRandom case crack t (hash t x) of Just _ -> measure (k-1) (n+1) _ -> measure (k-1) n save :: (Serialize h, Ord h, Serialize c) => FilePath -> Table h c -> IO () save path = LBS.writeFile path . encodeLazy . table load :: (Serialize h, Ord h, Serialize c) => (c -> h) -> [h -> c] -> FilePath -> IO (Either String (Table h c)) load h rs file = load' . decodeLazy <$> LBS.readFile file where load' (Left e) = Left $ "Cannot decode: " ++ e load' (Right t) = case M.lookupMin t of Nothing -> Left "Loaded an empty table" Just (y, c) | y == (h . chain h rs) c -> Right $ Table h rs t | otherwise -> Left "Incorrect algorithms for table" unsafeMerge :: Ord h => Table h c -> Table h c -> Table h c unsafeMerge t1 t2 = Table (hash t1) (reduce t1) (table t1 `M.union` table t2)
maugier/cctk
src/CCTK/RainbowTable.hs
gpl-3.0
3,252
0
17
924
1,367
709
658
71
3
{-# LANGUAGE TemplateHaskell, ViewPatterns #-} {-# OPTIONS -Wall #-} module ExampleTriangulations where import Blender.Types import Control.Exception import Data.Vect.Double import EdgeCentered import THUtil import TriangulationCxtObject import Data.SumType import Util import PreRenderable import Numeric.AD.Vector import Data.VectorSpace import HomogenousTuples import Text.PrettyPrint.ANSI.Leijen(text) tr_aroundEdge :: Word -> Triangulation tr_aroundEdge n = mkTriangulation n [ (tindex i ./ tABD, tindex (mod (i+1) n) ./ oABC) | i <- [0..n-1] ] tr_octahedron :: Triangulation tr_octahedron = tr_aroundEdge 4 tr_aroundEdge_topVertex, tr_aroundEdge_bottomVertex :: Word -> TVertex tr_aroundEdge_bottomVertex n = pMap (tr_aroundEdge n) (0 ./ vB) tr_aroundEdge_topVertex n = pMap (tr_aroundEdge n) (0 ./ vA) tr_aroundEdge_centralEdge_preimage :: OIEdge tr_aroundEdge_centralEdge_preimage = 0 ./ oedge (vB,vA) tr_aroundEdge_centralEdge :: Word -> T OIEdge tr_aroundEdge_centralEdge n = pMap (tr_aroundEdge n) tr_aroundEdge_centralEdge_preimage tr_octahedronWithGluing :: Triangulation tr_octahedronWithGluing = fromRight $ addGluings tr_octahedron [ oiTriangleGluing (0 ./ oCDA) (0 ./ oCDB) ] spqwc_aroundEdge :: Word -> SPQWithCoords EdgeNeighborhoodVertex spqwc_aroundEdge n = makeEdgeNeighborhood (tr_aroundEdge n) tr_aroundEdge_centralEdge_preimage show octahedronCam1 :: Cam octahedronCam1 = Cam (Vec3 0.217 (-3.091) 2.071) (eulerAnglesXYZ 1.0077831745147705 0 0.06999944895505905) defaultFOV tr_oneTet :: Triangulation tr_oneTet = mkTriangulation 1 [] tr_twoTets :: Triangulation tr_twoTets = mkTriangulation 2 [gluing (0./tABC) (1./oABC)] spqwc_oneTet :: SPQWithCoords Vertex spqwc_oneTet = oneTetWithDefaultCoords tr_oneTet show spqwc_twoTets :: SPQWithCoords TVertex spqwc_twoTets = spqwc_twoTetBipyramid tr_twoTets (0./tABC) show spqwc_l31 :: SPQWithCoords TVertex spqwc_l31 = spqwc_twoTetBipyramid tr_l31 (0./tABC) (\(ngDom -> (viewI -> I i tri)) -> assert (i==0) $ case tri of _ | tri == tABD -> "F" | tri == tACD -> "G" | tri == tBCD -> "J" | otherwise -> assert False undefined) twoTetCam' :: Cam twoTetCam' = Cam (uncurry3 Vec3 (-0.23205919563770294, -3.6175613403320312, 0.15333208441734314)) (uncurry3 eulerAnglesXYZ (1.4570116996765137, -8.902474064598209e-07, -0.0009973797714337707)) defaultFOV twoTetCam :: Cam twoTetCam = (readCam "(Vector((0.7618550062179565, -2.899303436279297, 1.0126327276229858)), Euler((1.152092695236206, 3.3568921935511753e-06, 0.37574928998947144), 'XYZ'), 0.8575560591178853)") oneTetCam :: Cam oneTetCam = Cam (uncurry3 Vec3 (-0.23205919563770294+0.2, -3.6175613403320312, 0.15333208441734314+0.28)) (uncurry3 eulerAnglesXYZ (1.4570116996765137, -8.902474064598209e-07, -0.0009973797714337707)) defaultFOV l41 :: SPQWithCoords Vertex l41 = oneTetWithDefaultCoords (mkTriangulation 1 [(0./tBCD,0./oCDA),(0./tABD,0./oBCA)]) (\gl@(ngDom -> forgetTIndex -> t) -> case () of _ | t==tBCD -> "F" | t==tABD -> "G" | otherwise -> error ("l41 "++ $(showExps 'gl)) ) torus3 :: SPQWithCoords EdgeNeighborhoodVertex torus3 = makeEdgeNeighborhood tr oiedge show where oiedge = 0 ./ oedge (vA,vB) :: OIEdge -- modified (oriented?) version of tr_184' tr = mkTriangulation 6 [(0 ./ tBCD, 1 ./ oCBD), (0 ./ tACD, 2 ./ oCDB), (0 ./ tABD, 3 ./ oDCB), (0 ./ tABC, 4 ./ oCDB), (1 ./ tBCD, 0 ./ oCBD), (1 ./ tACD, 2 ./ oDCA), (1 ./ tABD, 3 ./ oCDA), (1 ./ tABC, 5 ./ oCDB), (2 ./ tBCD, 0 ./ oDAC), (2 ./ tACD, 1 ./ oDCA), (2 ./ tABD, 4 ./ oCDA), (2 ./ tABC, 5 ./ oDCA), (3 ./ tBCD, 0 ./ oDBA), (3 ./ tACD, 1 ./ oDAB), (3 ./ tABD, 5 ./ oBCA), (3 ./ tABC, 4 ./ oCBA), (4 ./ tBCD, 0 ./ oCAB), (4 ./ tACD, 2 ./ oDAB), (4 ./ tABD, 5 ./ oADB), (4 ./ tABC, 3 ./ oCBA), (5 ./ tBCD, 1 ./ oCAB), (5 ./ tACD, 2 ./ oCBA), (5 ./ tABD, 4 ./ oADB), (5 ./ tABC, 3 ./ oDAB)] -- | Equals tr_184 in ClosedOrCensus6 tr_184' :: LabelledTriangulation tr_184' = ("T x S1 : #1", mkTriangulation 6 [(0 ./ tBCD, 1 ./ oCBD), (0 ./ tACD, 2 ./ oCDB), (0 ./ tABD, 3 ./ oCDB), (0 ./ tABC, 4 ./ oDCB), (1 ./ tBCD, 0 ./ oCBD), (1 ./ tACD, 2 ./ oDCA), (1 ./ tABD, 3 ./ oDCA), (1 ./ tABC, 5 ./ oDCB), (2 ./ tBCD, 0 ./ oDAC), (2 ./ tACD, 1 ./ oDCA), (2 ./ tABD, 4 ./ oDCA), (2 ./ tABC, 5 ./ oCDA), (3 ./ tBCD, 0 ./ oDAB), (3 ./ tACD, 1 ./ oDBA), (3 ./ tABD, 4 ./ oDBA), (3 ./ tABC, 5 ./ oBDA), (4 ./ tBCD, 0 ./ oCBA), (4 ./ tACD, 2 ./ oDBA), (4 ./ tABD, 3 ./ oDBA), (4 ./ tABC, 5 ./ oACB), (5 ./ tBCD, 1 ./ oCBA), (5 ./ tACD, 2 ./ oCAB), (5 ./ tABD, 3 ./ oCAB), (5 ./ tABC, 4 ./ oACB)]) lensSpace :: Word -> Word -> SPQWithCoords EdgeNeighborhoodVertex lensSpace p (tindex -> q) = makeEdgeNeighborhood tr (0 ./ oedge(vB,vA)) (\gl -> '#':if (ngDomTet gl, ngCodTet gl) == (0,tindex p-1) then show (p-1) else (show . ngDomTet) gl) where tr = mkTriangulation p (verticals ++ _outer) add i j = mod (i+j) (tindex p) verticals = [ gluing (i ./ tABD) (add i 1 ./ oABC) | i <- [0..tindex p-1] ] _outer = [ gluing (i ./ tACD) (add i q ./ oBCD) | i <- [0..tindex p-1] ] defaultTetImmersion :: GeneralTetImmersion defaultTetImmersion = GTetE (text "defaultTetImmersion") 10 ((\(Tup4 xs) -> sumV (zipWith (\x v -> x *^ liftVec3 (vertexDefaultCoords v)) (toList4 xs) allVertices) ) . unitToStd3)
DanielSchuessler/hstri
ExampleTriangulations.hs
gpl-3.0
5,805
0
18
1,418
2,158
1,193
965
-1
-1
{-# LANGUAGE OverloadedStrings,PatternGuards #-} module Lang.PrettyAltErgo where import Text.PrettyPrint import Lang.PolyFOL import Lang.PrettyUtils import Control.Monad type Id a = a -> Doc prime :: Doc -> Doc prime d = "\'" <> d alphabet :: [String] alphabet = do n <- [1..] replicateM n ['a'..'z'] commasep,commasepP :: [Doc] -> Doc commasep = sep . punctuate "," commasepP xs | length xs >= 2 = parens (commasep xs) | otherwise = commasep xs ppClause :: Id a -> Clause a -> Doc ppClause p cls = case cls of SortSig x n -> "type" <+> commasepP (map (prime . text) (take n alphabet)) <+> p x TypeSig x _tvs args res -> hang "logic" 2 (ppTySig p x args res) Clause _ cl _tvs phi -> hang (ppClType cl <+> "_" <+> ":") 2 (ppForm p phi) Comment s -> hang "(*" 2 (vcat (map text (lines s)) <+> "*)") ppClType :: ClType -> Doc ppClType cl = case cl of Axiom -> "axiom" Conjecture -> "goal" ppTySig :: Id a -> a -> [Type a] -> Type a -> Doc ppTySig p x args res = hang (p x <+> ":") 2 (pp_args (ppType p res)) where pp_args = case args of [] -> id _ -> hang (commasep (map (ppType p) args) <+> "->") 2 ppType :: Id a -> Type a -> Doc ppType p = go where go t0 = case t0 of TyCon tc ts -> commasepP (map go ts) <+> p tc TyVar x -> prime (p x) Type -> error "PrettyAltErgo.ppType: Type" ppForm :: Id a -> Formula a -> Doc ppForm p f0 = case f0 of _ | Just (op,fs) <- collectFOp f0 -> inside "(" (ppFOp op) ")" (map (ppForm p) fs) Q q x t f -> hang (ppQ q <+> ppTySig p x [] t <+> ".") 2 (ppForm p f) TOp op t1 t2 -> sep [ppTerm p t1 <+> ppTOp op,ppTerm p t2] Neg f -> "not" <+> parens (ppForm p f) Pred q fs -> p q <> csv (map (ppForm p) fs) FOp{} -> error "PrettyAltErgo.ppForm: FOp" ppQ :: Q -> Doc ppQ q = case q of Forall -> "forall" Exists -> "exists" ppFOp :: FOp -> Doc ppFOp op = case op of And -> " and " Or -> " or " Implies -> " -> " Equiv -> " <-> " ppTOp :: TOp -> Doc ppTOp op = case op of Equal -> "=" Unequal -> "<>" ppTerm :: Id a -> Term a -> Doc ppTerm p = go where go tm0 = case tm0 of Apply f _ts as -> p f <> csv (map go as) Var v -> p v Lit x -> integer x
danr/tfp1
Lang/PrettyAltErgo.hs
gpl-3.0
2,397
0
17
784
1,087
530
557
68
6
{-# 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.S3.PutBucketLifecycleConfiguration -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets lifecycle configuration for your bucket. If a lifecycle -- configuration exists, it replaces it. -- -- /See:/ <http://docs.aws.amazon.com/AmazonS3/latest/API/PutBucketLifecycleConfiguration.html AWS API Reference> for PutBucketLifecycleConfiguration. module Network.AWS.S3.PutBucketLifecycleConfiguration ( -- * Creating a Request putBucketLifecycleConfiguration , PutBucketLifecycleConfiguration -- * Request Lenses , pblcLifecycleConfiguration , pblcBucket -- * Destructuring the Response , putBucketLifecycleConfigurationResponse , PutBucketLifecycleConfigurationResponse ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.S3.Types import Network.AWS.S3.Types.Product -- | /See:/ 'putBucketLifecycleConfiguration' smart constructor. data PutBucketLifecycleConfiguration = PutBucketLifecycleConfiguration' { _pblcLifecycleConfiguration :: !(Maybe BucketLifecycleConfiguration) , _pblcBucket :: !BucketName } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PutBucketLifecycleConfiguration' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pblcLifecycleConfiguration' -- -- * 'pblcBucket' putBucketLifecycleConfiguration :: BucketName -- ^ 'pblcBucket' -> PutBucketLifecycleConfiguration putBucketLifecycleConfiguration pBucket_ = PutBucketLifecycleConfiguration' { _pblcLifecycleConfiguration = Nothing , _pblcBucket = pBucket_ } -- | Undocumented member. pblcLifecycleConfiguration :: Lens' PutBucketLifecycleConfiguration (Maybe BucketLifecycleConfiguration) pblcLifecycleConfiguration = lens _pblcLifecycleConfiguration (\ s a -> s{_pblcLifecycleConfiguration = a}); -- | Undocumented member. pblcBucket :: Lens' PutBucketLifecycleConfiguration BucketName pblcBucket = lens _pblcBucket (\ s a -> s{_pblcBucket = a}); instance AWSRequest PutBucketLifecycleConfiguration where type Rs PutBucketLifecycleConfiguration = PutBucketLifecycleConfigurationResponse request = putXML s3 response = receiveNull PutBucketLifecycleConfigurationResponse' instance ToElement PutBucketLifecycleConfiguration where toElement = mkElement "{http://s3.amazonaws.com/doc/2006-03-01/}LifecycleConfiguration" . _pblcLifecycleConfiguration instance ToHeaders PutBucketLifecycleConfiguration where toHeaders = const mempty instance ToPath PutBucketLifecycleConfiguration where toPath PutBucketLifecycleConfiguration'{..} = mconcat ["/", toBS _pblcBucket] instance ToQuery PutBucketLifecycleConfiguration where toQuery = const (mconcat ["lifecycle"]) -- | /See:/ 'putBucketLifecycleConfigurationResponse' smart constructor. data PutBucketLifecycleConfigurationResponse = PutBucketLifecycleConfigurationResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PutBucketLifecycleConfigurationResponse' with the minimum fields required to make a request. -- putBucketLifecycleConfigurationResponse :: PutBucketLifecycleConfigurationResponse putBucketLifecycleConfigurationResponse = PutBucketLifecycleConfigurationResponse'
olorin/amazonka
amazonka-s3/gen/Network/AWS/S3/PutBucketLifecycleConfiguration.hs
mpl-2.0
4,150
0
11
759
442
264
178
67
1
{- Created : 2014 Jun 05 (Thu) 20:29:15 by Harold Carr. Last Modified : 2014 Jun 08 (Sun) 12:24:53 by Harold Carr. -} module HW04_HC where import qualified Test.HUnit as T import qualified Test.HUnit.Util as U ------------------------------------------------------------------------------ -- Exercise 1 ------------------------- -- 1 fun1 :: [Integer] -> Integer fun1 [] = 1 fun1 (x:xs) | even x = (x - 2) * fun1 xs | otherwise = fun1 xs fun1' :: [Integer] -> Integer fun1' = foldr (\x acc -> (if even x then x - 2 else 1) * acc) 1 fun1'' :: [Integer] -> Integer fun1'' [] = 1 fun1'' xs = product $ map (\x -> x - 2) $ filter even xs e1fun1 :: T.Test e1fun1 = T.TestList [ -- if a 2 is anywhere in the list result is 0 U.teq "fun10" (fun1 [1::Integer, 2 .. 10]) 0 , U.teq "fun1'0" (fun1' [1::Integer, 2 .. 10]) 0 , U.teq "fun11" (fun1 [1::Integer, 3 .. 11]) 1 , U.teq "fun1'1" (fun1' [1::Integer, 3 .. 11]) 1 , U.teq "fun1''1" (fun1'' [1::Integer, 3 .. 11]) 1 , U.teq "fun148" (fun1 [4::Integer, 6, 8]) (2*4*6) , U.teq "fun1'48" (fun1' [4::Integer, 6, 8]) (2*4*6) , U.teq "fun148'" (fun1 [3::Integer, 4 .. 8]) (2*4*6) , U.teq "fun1'48'" (fun1' [3::Integer, 4 .. 8]) (2*4*6) ] ------------------------- -- 2 fun2 :: Integer -> Integer fun2 n | n == 1 = 0 | even n = n + fun2 (n `div` 2) | otherwise = fun2 (3 * n + 1) -- use takeWhile and interate -- iterate :: (a -> a) -> a -> [a] -- iterate f x = x : iterate f (f x) fun2' :: Integer -> Integer fun2' n0 = sum (map fst (takeWhile (\(n,_) -> n /= 1) (iterate (\(_, n) -> if n == 1 then (1, 1) else if even n then (n, n `div` 2) else (0, 3 * n + 1)) (0, n0)))) e1fun2 :: T.Test e1fun2 = T.TestList [ U.teq "fun2" (map fun2 [1::Integer, 2 .. 10]) [0,2,40,6,30,46,234,14,276,40] , U.teq "fun2'" (map fun2' [1::Integer, 2 .. 10]) [0,2,40,6,30,46,234,14,276,40] , U.teq "fun2eq" (map fun2 [1::Integer, 2 .. 1000]) (map fun2' [1::Integer, 2 .. 1000]) ] ------------------------------------------------------------------------------ -- Exercise 2 -- TODO ------------------------------------------------------------------------------ -- Exercise 3 ------------------------- -- 1 xor :: [Bool] -> Bool xor = odd . foldr (\x acc -> (if x then (+1) else (*1)) acc) (0::Integer) xor' :: [Bool] -> Bool xor' = odd . length. filter id e3xor :: T.Test e3xor = T.TestList [ U.teq "xor0" (xor []) False , U.teq "xor'0" (xor' []) False , U.teq "xor1" (xor [False, True, False]) True , U.teq "xor'1" (xor' [False, True, False]) True , U.teq "xor2" (xor [False, True, False, False, True]) False , U.teq "xor'2" (xor' [False, True, False, False, True]) False ] ------------------------- -- 2 map' :: (a -> b) -> [a] -> [b] map' f = foldr (\x acc -> f x : acc) [] e3map :: T.Test e3map = T.TestList [ U.teq "map0" (map' (*2) [1::Integer ..9]) (map (*2) [1::Integer ..9]) , U.teq "map1" (map' fun2 [1::Integer, 2 .. 10]) (map fun2 [1::Integer, 2 .. 10]) ] ------------------------- -- 3 -- BEGIN for stepping and watching reductions myId :: x -> x myId x = x myFoldr :: (a -> b -> b) -> b -> [a] -> b myFoldr _ z [] = z myFoldr f z (x:xs) = f x (myFoldr f z xs) myPlus :: Integer -> Integer -> Integer myPlus x y = x + y -- END for stepping and watching reductions -- the parens around myFoldr are redundant, -- but helps pointing out it returns a function myFoldl :: (a -> b -> a) -> a -> [b] -> a myFoldl stepL zeroL xs = (myFoldr stepR id xs) zeroL where stepR lastL accR accInitL = accR (stepL accInitL lastL) -- redundant lambda, but helps with intuition foo :: Integer -> (Integer -> t) -> Integer -> t foo = \lastL accR accInitL -> accR (myPlus accInitL lastL) e3foldr :: T.Test e3foldr = T.TestList [ U.teq "fll0" (foldl (++) [] ["foo","bar"]) (myFoldl (++) [] ["foo","bar"]) , U.teq "fll1" (foldl (++) [] [[1::Integer],[2],[3]]) (myFoldl (++) [] [[1::Integer],[2],[3]]) , U.teq "fll1" (foldl myPlus 0 [1::Integer,2,3]) (myFoldl myPlus 0 [1::Integer,2,3]) ] mf :: [T.Test] mf = U.tt "mf" [myFoldl myPlus 0 [1,2] , (myFoldr foo myId [1,2]) 0 ,foo 1 (myFoldr foo myId [2]) 0 ,foo 1 (foo 2 (myFoldr foo myId [])) 0 ,foo 1 (foo 2 myId) 0 ,foo 1 ((\lastL accR accInitL -> accR (myPlus accInitL lastL)) 2 myId) 0 ,foo 1 (\accInitL -> myId (myPlus accInitL 2)) 0 ,(\lastL accR accInitL -> accR (myPlus accInitL lastL)) 1 (\accInitL' -> myId (myPlus accInitL' 2)) 0 , (\accR accInitL -> accR (myPlus accInitL 1)) (\accInitL' -> myId (myPlus accInitL' 2)) 0 , (\accInitL -> (\accInitL' -> myId (myPlus accInitL' 2)) (myPlus accInitL 1)) 0 , (\accInitL' -> myId (myPlus accInitL' 2)) (myPlus 0 1) , myId (myPlus (myPlus 0 1) 2) , myId 3 ] 3 ------------------------------------------------------------------------------ -- Exercise 4 cartProd :: [a] -> [b] -> [(a, b)] cartProd xs ys = [(x,y) | x <- xs, y <- ys] sieveSundaram :: Integer -> [Integer] sieveSundaram n0 = let ns = [1::Integer .. n0] cp = cartProd ns ns ft = filter (\n -> all (\(i, j) -> i + j + (2*i*j) /= n) cp) ns in map (\x -> 2*x + 1) ft e4 :: T.Test e4 = T.TestList [ U.teq "cp" (cartProd [1::Integer,2] ['a','b']) [(1,'a'),(1,'b'),(2,'a'),(2,'b')] , U.teq "si" (sieveSundaram 100) [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199] ] ------------------------------------------------------------------------------ hw04 :: IO T.Counts hw04 = do _ <- T.runTestTT e1fun1 _ <- T.runTestTT e1fun2 _ <- T.runTestTT e3xor _ <- T.runTestTT e3map _ <- T.runTestTT e3foldr _ <- T.runTestTT $ T.TestList $ mf T.runTestTT e4 -- End of file.
haroldcarr/learn-haskell-coq-ml-etc
haskell/course/2014-06-upenn/cis194/src/HW04_HC.hs
unlicense
7,521
0
19
2,955
2,830
1,580
1,250
126
3
module Git.Command.Bundle (run) where run :: [String] -> IO () run args = return ()
wereHamster/yag
Git/Command/Bundle.hs
unlicense
84
0
7
15
42
23
19
3
1
-- Run-length encoding of a list. Consecutive duplicates of elements are encoded -- as lists (N E) where N is the number of duplicates of the element E. module Problem10 where import Data.List rle :: (Eq a) => [a] -> [(Int,a)] rle = map (\xs -> (length xs, head xs)) . group
jstolarek/sandbox
haskell/99.problems/Problem10.hs
unlicense
282
0
10
59
73
43
30
4
1
-- Copyright 2021 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- https://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Solution where import Internal (codelab) import Prelude hiding (map, filter, foldr, foldl) -- CODELAB 04: Abstractions -- -- Have you noticed that we keep using the same pattern? If the list is -- empty we return a specific value. If it is not, we call a function to -- combine the element with the result of the recursive calls. -- -- This is Haskell: if there is a pattern, it can (must) be abstracted! -- Fortunately, some useful functions are here for us. -- -- To understand the difference between foldr and foldl, remember that the -- last letter indicates if the "reduction" function is left associative or -- right associative: foldr goes from right to left, foldl goes from left -- to right. -- -- foldl :: (a -> x -> a) -> a -> [x] -> a -- foldr :: (x -> a -> a) -> a -> [x] -> a -- foldl (-) 0 [1,2,3,4] == (((0 - 1) - 2) - 3) - 4 == -10 -- foldr (-) 0 [1,2,3,4] == 1 - (2 - (3 - (4 - 0))) == -2 -- You probably remember this one? Nothing extraordinary here. map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (a:as) = f a : map f as -- Same thing here for filter, except that we use it to introduce a new -- syntax: those | are called "guards". They let you specify different -- implementations of your function depending on some Boolean -- value. "otherwise" is not a keyword but simply a constant whose value is -- True! Try to evaluate "otherwise" in GHCI. -- -- Simple example of guard usage: -- abs :: Int -> Int -- abs x -- | x < 0 = -x -- | otherwise = x filter :: (a -> Bool) -> [a] -> [a] filter _ [] = [] filter f (x:xs) | f x = x : filter f xs | otherwise = filter f xs -- foldl -- foldl (-) 0 [1,2,3,4] == (((0 - 1) - 2) - 3) - 4 == -10 foldl :: (a -> x -> a) -> a -> [x] -> a foldl _ a [] = a foldl f a (x:xs) = foldl f (f a x) xs -- foldr -- foldr (-) 0 [1,2,3,4] == 1 - (2 - (3 - (4 - 0))) == -2 foldr :: (x -> a -> a) -> a -> [x] -> a foldr _ a [] = a foldr f a (x:xs) = f x (foldr f a xs) -- ##################################################################### -- BONUS STAGE! -- -- For fun, you can try reimplementing the functions in previous codelab with -- foldr or foldl! For length, remember that the syntax for a lambda function -- is (\arg1 arg2 -> value). -- -- You can replace your previous implementation if you want. Otherwise, you can -- add new functions (such as andF, orF), and test them by loading your file in -- GHCI. -- -- To go a bit further, you can also try QuickCheck: -- -- > import Test.QuickCheck -- > quickCheck $ \anyList -> and anyList == andF anyList -- -- QuickCheck automatically generates tests based on the types expected -- (here, list of boolean values). -- -- It is also worth noting that there is a special syntax for list -- comprehension in Haskell, which is at a first glance quite similar to -- the syntax of Python's list comprehension -- -- Python: [transform(value) for value in container if test(value)] -- Haskell: [transform value | value <- container , test value ] -- -- This allows you to succinctly write your map / filters.
google/haskell-trainings
haskell_101/codelab/04_abstractions/src/Solution.hs
apache-2.0
3,876
0
8
834
424
260
164
21
1
module Crypto ( module Crypto.FrequencyAnalysis, module Crypto.FrequencyAnalysis.English, module Crypto.FrequencyAnalysis.BreakXorCipher ) where import Crypto.FrequencyAnalysis import Crypto.FrequencyAnalysis.English import Crypto.FrequencyAnalysis.BreakXorCiper
stallmanifold/matasano-crypto-challenges
src/Crypto.hs
apache-2.0
300
0
5
54
43
29
14
8
0
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} module Experiment.Bench.CSV ( aggregateCSV ) where import Laborantin.DSL import Laborantin.Types import Laborantin.Implementation (EnvIO) import Data.Monoid ((<>)) import Control.Applicative ((<$>)) import Data.Text.Lazy.Encoding (decodeUtf8) import Data.Text.Encoding (encodeUtf8) import Data.Text.Lazy (toStrict) import qualified Data.Map as M import qualified Data.Vector as V import qualified Data.Set as S import Data.Text (Text) import Data.Csv (ToNamedRecord (..), toField, namedRecord, namedField, (.=), encodeByName) instance ToNamedRecord ParameterSet where toNamedRecord prms = let pairs = M.toList prms validPairs = filter (isRecord . snd) pairs in namedRecord $ map toBSpair validPairs -- map toRecordPair . filter _ prms where isRecord (NumberParam _) = True isRecord (StringParam _) = True isRecord _ = False toBSpair (k, StringParam v) = namedField (encodeUtf8 k) v toBSpair (k, NumberParam v) = let v' = fromRational v :: Double in namedField (encodeUtf8 k) v' paramNames = S.fromList . concatMap (\e -> M.keys $ eParamSet e) headerNames extras = fmap encodeUtf8 . V.fromList . S.toList . S.union (S.fromList extras) . paramNames aggregateCSV :: (ToNamedRecord a) => String -> String -> (Text -> a) -> [Text] -> Step EnvIO () aggregateCSV res srcRes parser keys = do b <- backend ancestors <- eAncestors <$> self let header = headerNames ("scenario.path":keys) ancestors dump header =<< map transform <$> mapM (extract b) ancestors where extract b exec = do out <- pRead =<< (bResult b exec srcRes) let path = ePath exec let prms = eParamSet exec let parsed = parser out return (path, prms, parsed) transform (path, prms, parsed) = let pathRecord = namedRecord ["scenario.path" .= path] in pathRecord <> toNamedRecord prms <> toNamedRecord parsed dump header = writeResult res . toStrict . decodeUtf8 . encodeByName header
lucasdicioccio/laborantin-bench-web
Experiment/Bench/CSV.hs
apache-2.0
2,240
0
13
572
693
366
327
52
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Haddock.Backends.Hyperlinker.Renderer (render) where import Haddock.Backends.Hyperlinker.Types import Haddock.Backends.Hyperlinker.Utils import qualified Data.ByteString as BS import GHC.Iface.Ext.Types import GHC.Iface.Ext.Utils ( isEvidenceContext , emptyNodeInfo ) import GHC.Unit.Module ( ModuleName, moduleNameString ) import GHC.Types.Name ( getOccString, isInternalName, Name, nameModule, nameUnique ) import GHC.Types.SrcLoc import GHC.Types.Unique ( getKey ) import GHC.Utils.Encoding ( utf8DecodeByteString ) import System.FilePath.Posix ((</>)) import qualified Data.Map as Map import qualified Data.Set as Set import Text.XHtml (Html, HtmlAttr, (!)) import qualified Text.XHtml as Html type StyleClass = String -- | Produce the HTML corresponding to a hyperlinked Haskell source render :: Maybe FilePath -- ^ path to the CSS file -> Maybe FilePath -- ^ path to the JS file -> SrcMaps -- ^ Paths to sources -> HieAST PrintedType -- ^ ASTs from @.hie@ files -> [Token] -- ^ tokens to render -> Html render mcss mjs srcs ast tokens = header mcss mjs <> body srcs ast tokens body :: SrcMaps -> HieAST PrintedType -> [Token] -> Html body srcs ast tokens = Html.body . Html.pre $ hypsrc where hypsrc = renderWithAst srcs ast tokens header :: Maybe FilePath -> Maybe FilePath -> Html header Nothing Nothing = Html.noHtml header mcss mjs = Html.header $ css mcss <> js mjs where css Nothing = Html.noHtml css (Just cssFile) = Html.thelink Html.noHtml ! [ Html.rel "stylesheet" , Html.thetype "text/css" , Html.href cssFile ] js Nothing = Html.noHtml js (Just scriptFile) = Html.script Html.noHtml ! [ Html.thetype "text/javascript" , Html.src scriptFile ] splitTokens :: HieAST PrintedType -> [Token] -> ([Token],[Token],[Token]) splitTokens ast toks = (before,during,after) where (before,rest) = span leftOf toks (during,after) = span inAst rest leftOf t = realSrcSpanEnd (tkSpan t) <= realSrcSpanStart nodeSp inAst t = nodeSp `containsSpan` tkSpan t nodeSp = nodeSpan ast -- | Turn a list of tokens into hyperlinked sources, threading in relevant link -- information from the 'HieAST'. renderWithAst :: SrcMaps -> HieAST PrintedType -> [Token] -> Html renderWithAst srcs Node{..} toks = anchored $ case toks of [tok] | nodeSpan == tkSpan tok -> richToken srcs nodeInfo tok -- NB: the GHC lexer lexes backquoted identifiers and parenthesized operators -- as multiple tokens. -- -- * @a `elem` b@ turns into @[a, `, elem, `, b]@ (excluding space tokens) -- * @(+) 1 2@ turns into @[(, +, ), 1, 2]@ (excluding space tokens) -- -- However, the HIE ast considers @`elem`@ and @(+)@ to be single nodes. In -- order to make sure these get hyperlinked properly, we intercept these -- special sequences of tokens and merge them into just one identifier or -- operator token. [BacktickTok s1, tok@Token{ tkType = TkIdentifier }, BacktickTok s2] | realSrcSpanStart s1 == realSrcSpanStart nodeSpan , realSrcSpanEnd s2 == realSrcSpanEnd nodeSpan -> richToken srcs nodeInfo (Token{ tkValue = "`" <> tkValue tok <> "`" , tkType = TkOperator , tkSpan = nodeSpan }) [OpenParenTok s1, tok@Token{ tkType = TkOperator }, CloseParenTok s2] | realSrcSpanStart s1 == realSrcSpanStart nodeSpan , realSrcSpanEnd s2 == realSrcSpanEnd nodeSpan -> richToken srcs nodeInfo (Token{ tkValue = "(" <> tkValue tok <> ")" , tkType = TkOperator , tkSpan = nodeSpan }) _ -> go nodeChildren toks where nodeInfo = maybe emptyNodeInfo id (Map.lookup SourceInfo $ getSourcedNodeInfo sourcedNodeInfo) go _ [] = mempty go [] xs = foldMap renderToken xs go (cur:rest) xs = foldMap renderToken before <> renderWithAst srcs cur during <> go rest after where (before,during,after) = splitTokens cur xs anchored c = Map.foldrWithKey anchorOne c (nodeIdentifiers nodeInfo) anchorOne n dets c = externalAnchor n d $ internalAnchor n d c where d = identInfo dets renderToken :: Token -> Html renderToken Token{..} | BS.null tkValue = mempty | tkType == TkSpace = renderSpace (srcSpanStartLine tkSpan) tkValue' | otherwise = tokenSpan ! [ multiclass style ] where tkValue' = filterCRLF $ utf8DecodeByteString tkValue style = tokenStyle tkType tokenSpan = Html.thespan (Html.toHtml tkValue') -- | Given information about the source position of definitions, render a token richToken :: SrcMaps -> NodeInfo PrintedType -> Token -> Html richToken srcs details Token{..} | tkType == TkSpace = renderSpace (srcSpanStartLine tkSpan) tkValue' | otherwise = annotate details $ linked content where tkValue' = filterCRLF $ utf8DecodeByteString tkValue content = tokenSpan ! [ multiclass style ] tokenSpan = Html.thespan (Html.toHtml tkValue') style = tokenStyle tkType ++ concatMap (richTokenStyle (null (nodeType details))) contexts contexts = concatMap (Set.elems . identInfo) . Map.elems . nodeIdentifiers $ details -- pick an arbitary non-evidence identifier to hyperlink with identDet = Map.lookupMin $ Map.filter notEvidence $ nodeIdentifiers $ details notEvidence = not . any isEvidenceContext . identInfo -- If we have name information, we can make links linked = case identDet of Just (n,_) -> hyperlink srcs n Nothing -> id -- | Remove CRLFs from source filterCRLF :: String -> String filterCRLF ('\r':'\n':cs) = '\n' : filterCRLF cs filterCRLF (c:cs) = c : filterCRLF cs filterCRLF [] = [] annotate :: NodeInfo PrintedType -> Html -> Html annotate ni content = Html.thespan (annot <> content) ! [ Html.theclass "annot" ] where annot | not (null annotation) = Html.thespan (Html.toHtml annotation) ! [ Html.theclass "annottext" ] | otherwise = mempty annotation = typ ++ identTyps typ = unlines (nodeType ni) typedIdents = [ (n,t) | (n, c@(identType -> Just t)) <- Map.toList $ nodeIdentifiers ni , not (any isEvidenceContext $ identInfo c) ] identTyps | length typedIdents > 1 || null (nodeType ni) = concatMap (\(n,t) -> printName n ++ " :: " ++ t ++ "\n") typedIdents | otherwise = "" printName :: Either ModuleName Name -> String printName = either moduleNameString getOccString richTokenStyle :: Bool -- ^ are we lacking a type annotation? -> ContextInfo -- ^ in what context did this token show up? -> [StyleClass] richTokenStyle True Use = ["hs-type"] richTokenStyle False Use = ["hs-var"] richTokenStyle _ RecField{} = ["hs-var"] richTokenStyle _ PatternBind{} = ["hs-var"] richTokenStyle _ MatchBind{} = ["hs-var"] richTokenStyle _ TyVarBind{} = ["hs-type"] richTokenStyle _ ValBind{} = ["hs-var"] richTokenStyle _ TyDecl = ["hs-type"] richTokenStyle _ ClassTyDecl{} = ["hs-type"] richTokenStyle _ Decl{} = ["hs-var"] richTokenStyle _ IEThing{} = [] -- could be either a value or type richTokenStyle _ EvidenceVarBind{} = [] richTokenStyle _ EvidenceVarUse{} = [] tokenStyle :: TokenType -> [StyleClass] tokenStyle TkIdentifier = ["hs-identifier"] tokenStyle TkKeyword = ["hs-keyword"] tokenStyle TkString = ["hs-string"] tokenStyle TkChar = ["hs-char"] tokenStyle TkNumber = ["hs-number"] tokenStyle TkOperator = ["hs-operator"] tokenStyle TkGlyph = ["hs-glyph"] tokenStyle TkSpecial = ["hs-special"] tokenStyle TkSpace = [] tokenStyle TkComment = ["hs-comment"] tokenStyle TkCpp = ["hs-cpp"] tokenStyle TkPragma = ["hs-pragma"] tokenStyle TkUnknown = [] multiclass :: [StyleClass] -> HtmlAttr multiclass = Html.theclass . unwords externalAnchor :: Identifier -> Set.Set ContextInfo -> Html -> Html externalAnchor (Right name) contexts content | not (isInternalName name) , any isBinding contexts = Html.thespan content ! [ Html.identifier $ externalAnchorIdent name ] externalAnchor _ _ content = content isBinding :: ContextInfo -> Bool isBinding (ValBind RegularBind _ _) = True isBinding PatternBind{} = True isBinding Decl{} = True isBinding (RecField RecFieldDecl _) = True isBinding TyVarBind{} = True isBinding ClassTyDecl{} = True isBinding _ = False internalAnchor :: Identifier -> Set.Set ContextInfo -> Html -> Html internalAnchor (Right name) contexts content | isInternalName name , any isBinding contexts = Html.thespan content ! [ Html.identifier $ internalAnchorIdent name ] internalAnchor _ _ content = content externalAnchorIdent :: Name -> String externalAnchorIdent = hypSrcNameUrl internalAnchorIdent :: Name -> String internalAnchorIdent = ("local-" ++) . show . getKey . nameUnique -- | Generate the HTML hyperlink for an identifier hyperlink :: SrcMaps -> Identifier -> Html -> Html hyperlink (srcs, srcs') ident = case ident of Right name | isInternalName name -> internalHyperlink name | otherwise -> externalNameHyperlink name Left name -> externalModHyperlink name where internalHyperlink name content = Html.anchor content ! [ Html.href $ "#" ++ internalAnchorIdent name ] externalNameHyperlink name content = case Map.lookup mdl srcs of Just SrcLocal -> Html.anchor content ! [ Html.href $ hypSrcModuleNameUrl mdl name ] Just (SrcExternal path) -> Html.anchor content ! [ Html.href $ spliceURL Nothing (Just mdl) (Just name) Nothing (".." </> path) ] Nothing -> content where mdl = nameModule name externalModHyperlink moduleName content = case Map.lookup moduleName srcs' of Just SrcLocal -> Html.anchor content ! [ Html.href $ hypSrcModuleUrl' moduleName ] Just (SrcExternal path) -> Html.anchor content ! [ Html.href $ spliceURL' Nothing (Just moduleName) Nothing Nothing (".." </> path) ] Nothing -> content renderSpace :: Int -> String -> Html renderSpace !_ "" = Html.noHtml renderSpace !line ('\n':rest) = mconcat [ Html.thespan (Html.toHtml '\n') , lineAnchor (line + 1) , renderSpace (line + 1) rest ] renderSpace line space = let (hspace, rest) = span (/= '\n') space in (Html.thespan . Html.toHtml) hspace <> renderSpace line rest lineAnchor :: Int -> Html lineAnchor line = Html.thespan Html.noHtml ! [ Html.identifier $ hypSrcLineUrl line ]
haskell/haddock
haddock-api/src/Haddock/Backends/Hyperlinker/Renderer.hs
bsd-2-clause
10,899
0
16
2,542
3,164
1,632
1,532
211
6
module Web.RedisSession ( setSession , setSessionExpiring , getSession , newKey , Redis ) where import Control.Monad (void) import Control.Monad.Trans (liftIO) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BC import qualified Data.List as L import Database.Redis import System.Random setSessionExpiring :: Connection -> ByteString -> [(ByteString, ByteString)] -> Integer -> IO () setSessionExpiring conn key values timeout = runRedis conn $ do void $ del [key] void $ hmset key values void $ expire key timeout return () setSession :: Connection -> ByteString -> [(ByteString, ByteString)] -- ^ if this is ever empty then the expiration is removed -> IO () setSession conn key values = runRedis conn $ do oldsess <- liftIO $ getSession conn key let todelete = case oldsess of Just old -> let oldfields = fst <$> old newfields = fst <$> values in oldfields L.\\ newfields -- only delete fields that aren't in the new values Nothing -> [] void $ hmset key values -- overwrites keys that exist already void $ hdel key todelete return () getSession :: Connection -> ByteString -> IO (Maybe [(ByteString, ByteString)]) getSession conn key = runRedis conn $ do result <- hgetall key return $ case result of Right b -> Just b Left _ -> Nothing newKey :: IO ByteString newKey = do gen <- newStdGen let n = 30 chars = ['0'..'9']++['a'..'z']++['A'..'B'] numbers = randomRs (0, length chars - 1) gen return $ BC.pack $ take n $ map (chars!!) numbers
ollieh/yesod-session-redis
Web/RedisSession.hs
bsd-2-clause
1,870
0
18
640
542
278
264
52
2
module FractalFlame.Generator ( module FractalFlame.Generator , module FractalFlame.Generator.Types.Generator ) where import Control.Monad.State import Data.Bits import Data.List import Data.Random.Normal import System.Random import Test.QuickCheck.Gen import FractalFlame.Flam3.Types.Xform import FractalFlame.Generator.Types.Generator import FractalFlame.Point.Types.CartesianPoint import FractalFlame.Point.Types.Point import FractalFlame.Types.Base -- | Generate a random value in the subrange of a Gaussian distribution: -- [mean - stdev * clipDevs, mean + stdev * clipDevs] boundedGaussian pt@(mean, stdev, clipDevs) s = let res@(v, s') = normal' (mean, stdev) s min = mean - clipDevs * stdev max = mean + clipDevs * stdev in -- sample until we find a value within clipDevs standard deviations of the mean -- DANGER: runtime could grow large for a relatively flat distribution and small clipDevs if min <= v && v <= max then res else boundedGaussian pt s' -- | Given an ordered list, superimpose a bell curve over it with the mean in the middle of the list and choose an item -- with probability proportional to the height of the curve at that item's position in the list. gaussianChoose :: (RealFrac a, Floating a, Random a, Ord a) => (a, a, a) -> [b] -> Generator b gaussianChoose pt@(mean, stdev, clipDevs) vs s = let (i, s') = boundedGaussian (mean, stdev, clipDevs) s -- mean 0, stdev 1. let's clip it @ 4 standard deviations halfRange = stdev * clipDevs gRange = 2 * halfRange i' = i + halfRange i'' = i' / gRange ix = (round $ i'' * (fromIntegral (length vs))) - 1 v = vs !! ix in (v, s') -- | Generate a random flame symmetry parameter based on a Gaussian distribution symmetryGenGaussian :: Generator Int symmetryGenGaussian s = let -- first, specify a nicely shaped Gaussian bell curve mean = 0 :: Coord -- why isn't some floating-point type inferred? because there are multiple concrete types that satisfy the class constraints? stdev = 1 :: Coord clipDevs = 4 :: Coord -- next, set up a set of symmetry values from which to choose. items in the middle are most likely to be chosen, -- items at either end least likely -- symmetry none | reflective, rotational | rotational | none (extra 1 so -1 and 2 are equally likely) syms = [1, 1] ++ [-25..(-1)] ++ [2..25] ++ [1, 1, 1] in gaussianChoose (mean, stdev, clipDevs) syms s -- | Generate a random flame symmetry parameter with behavior equivalent to Scott Draves' flam3-render symmetryGenDraves :: Generator Int symmetryGenDraves s = let baseDistribution = [ (-4), (-3) , (-2), (-2), (-2) , (-1), (-1), (-1) , 2 , 2 , 2 , 3 , 3 , 4 , 4 ] baseLookup ix = baseDistribution !! (ix `mod` (length baseDistribution)) -- idk why, but he chooses a fresh random number if r1 is odd ([r1, r2, r3], s') = generatorSequence (replicate 3 $ randomR (minBound, maxBound)) s :: ([Int], StdGen) sym = if (r1 .&. 1) /= 0 then -- half the time (8/16 probability total) baseLookup r2 -- choose one of baseDistribution else if (r2 .&. 31) /= 0 then -- if not base, 1/8 of the time (1/16 probability total) r3 `mod` 13 - 6 -- -6 to 6 inclusive else -- if not base, 7/8 of the time (7/16 probability total) r3 `mod` 51 - 25 -- -25 to 25 inclusive in (sym, s') loopGen :: Gen a -> Generator a loopGen g = (\s -> let (s', s'') = split s in (unGen g s' 1, s'')) loopSampler :: [a] -> Generator a loopSampler items = let gens = map return items in loopGen $ oneof gens weightedLoopSampler :: [(Coord, a)] -> Generator a weightedLoopSampler freqItems = -- no need to normalize, frequency does it for us. multiply to get some resolution before rounding. let freqGens = map (\(freq, item) -> ((round $ freq * 10000), return item)) freqItems in loopGen $ frequency freqGens -- returns a function that samples a list of BaseTransforms based on their weights xformSampler :: [Xform] -> Generator Xform xformSampler = weightedLoopSampler . map (\xform@(Xform {weight}) -> (weight, xform)) -- random variables for initialization genFirstPoint :: Generator CartesianPoint genFirstPoint s = let (x, s') = randomR (-1, 1) s :: (Coord, StdGen) -- why won't it infer this? (y, s'') = randomR (-1, 1) s' :: (Coord, StdGen) in (Point x y, s'') genFirstColorIx :: Generator Coord genFirstColorIx = randomR (0, 1) -- | infinite list of new seeds seeds :: StdGen -> [StdGen] seeds s = let (s', s'') = split s in (s':seeds s'') -- would (s':seeds s') also be correct? -- | random number [0,pi] psi :: Generator Coord psi = randomR (0, pi) -- | random number 0 or pi omega :: Generator Coord omega = loopGen $ oneof [return 0, return pi] -- | random number -1 or 1 lambda :: Generator Coord lambda = loopGen $ oneof [return (-1), return 1] -- | get the results for a list of Generators sequentially, passing the seed returned by each Generator to the next generatorSequence :: [Generator a] -> StdGen -> ([a], StdGen) generatorSequence fs seed = (flip runState) seed $ do results <- mapM runGen fs return results where runGen f = do seed' <- get let (res, seed'') = f seed' put seed'' return res
anthezium/fractal_flame_renderer_haskell
FractalFlame/Generator.hs
bsd-2-clause
5,483
0
15
1,343
1,430
802
628
-1
-1
{-# LANGUAGE RecordWildCards #-} -- | A tree representation of a feature structure. module NLP.FeatureStructure.Tree ( -- * Types AV , FT (..) , FN (..) , FF , ID -- ** Core combinators , empty , atom , label , name -- * Conversion , runConT , runCon , fromFN , fromFT , fromAV -- * Utility , showFN , showFT ) where import Control.Applicative ((<$>)) import Control.Monad (forM, forM_) import qualified Control.Monad.State.Strict as S import Control.Monad.Identity (Identity, runIdentity) import Data.List (intercalate) import qualified Data.Set as Set import qualified Data.Map.Strict as M -- import qualified Data.Traversable as T import Data.String (IsString (..)) import NLP.FeatureStructure.Core import qualified NLP.FeatureStructure.Graph as G import qualified NLP.FeatureStructure.Join as J -------------------------------------------------------------------- -- Types -------------------------------------------------------------------- -- | An attribute-value map. -- * 'i' -- type of identifier -- * 'f' -- type of a feature (attribute) -- * 'a' -- type of an atomic (leaf) feature value type AV i f a = M.Map f (FN i f a) -- | A feature tree is either an atomic 'Atom a' value or a -- sub-attribute-value map. data FT i f a = Subs (AV i f a) | Atom a deriving (Show, Eq, Ord) -- | A named feature tree, i.e. with an optional identifier. data FN i f a = FN { -- | Optional identifier. ide :: Maybe i -- | The actual value. , val :: FT i f a } deriving (Show, Eq, Ord) -- | A feature forest. type FF i f a = [FN i f a] -- | If the string starts with '?', it represents a `label`. -- Otherwise, it represents an `atom`. instance (IsString i, IsString a) => IsString (FN i f a) where fromString xs = case xs of ('?':_) -> label $ fromString xs _ -> atom $ fromString xs -- fromString xs = case xs of -- [] -> empty -- ('?':_) -> label $ fromString xs -- _ -> atom $ fromString xs -- -- | If the string is empty, it represents an `empty` tree. -- -- If the string starts with '?', it represents a `label`. -- -- Otherwise, it represents a `atom`. showFN :: (Show i, Show f, Show a) => FN i f a -> String showFN FN{..} = let showIde Nothing = "" -- showIde (Just i) = "(" ++ show i ++ ")" showIde (Just i) = show i in showIde ide ++ showFT val showFT :: (Show i, Show f, Show a) => FT i f a -> String showFT (Atom x) = show x showFT (Subs m) = let showFeat (x, fn) = show x ++ "=" ++ showFN fn body = intercalate ", " $ map showFeat $ M.toList m in "[" ++ body ++ "]" -------------------------------------------------------------------- -- Core combinators -------------------------------------------------------------------- -- | An empty tree. It can be unified with both -- complex structures and atomic values. empty :: FN i f a empty = FN Nothing $ Subs M.empty -- | An atomic `FN`. atom :: a -> FN i f a atom = FN Nothing . Atom -- | A lone identifier. label :: i -> FN i f a label = flip name empty -- | Assign a name to an `FN`. name :: i -> FN i f a -> FN i f a name i fn = fn { ide = Just i } -------------------------------------------------------------------- -- Conversion -------------------------------------------------------------------- -- | A state of the conversion monad. data ConS i f a = ConS { -- | A counter for producing new identifiers. conC :: Int -- | A mapping from old to new identifiers. , conI :: M.Map i (Set.Set ID) -- | A mapping from atomic values to IDs. Ensures that there -- are no frontier duplicates in the conversion result. , conA :: M.Map a ID } -- | Initial value of the state. initConS :: ConS i f a initConS = ConS { conC = 1 , conI = M.empty , conA = M.empty } -- | A conversion transformer. type ConT i f a m b = S.StateT (ConS i f a) (J.JoinT ID f a m) b -- | A conversion monad. type Con i f a b = ConT i f a Identity b -- | Run the conversion transformer. runConT :: (Functor m, Monad m, Ord i, Ord f, Eq a) => ConT i f a m b -> m (Maybe (b, J.Res ID ID f a)) runConT con = flip J.runJoinT G.empty $ do -- First we need to convert a tree to a trivial feature graph -- (tree stored as `conC`) and identify nodes which need to be -- joined. (r0, st) <- S.runStateT con initConS -- The second step is to join all nodes which have to be -- merged based on the identifiers specified by the user. forM_ (M.elems $ conI st) $ \ks -> do forM_ (adja $ Set.toList ks) $ \(i, j) -> do J.join i j return r0 -- | Run the conversion monad. runCon :: (Ord i, Ord f, Eq a) => Con i f a b -> Maybe (b, J.Res ID ID f a) runCon = runIdentity . runConT -- -- | Convert the given traversable structure of named feature trees -- -- to a trivial feature graph. -- fromTravFN -- :: (Monad m, T.Traversable t, Ord i, Ord f, Eq a) -- => t (FN i f a) -> ConT i f a m (t ID) -- fromTravFN = T.mapM fromFN -- | Convert the given named feature tree to a feature graph. fromFN :: (Functor m, Monad m, Ord i, Ord f, Ord a) => FN i f a -> ConT i f a m ID fromFN FN{..} = do x <- fromFT val justM ide $ register x return x -- | Convert the given feature tree to a trivial feature graph. fromFT :: (Functor m, Monad m, Ord i, Ord f, Ord a) => FT i f a -> ConT i f a m ID fromFT (Subs x) = fromAV x fromFT (Atom x) = atomID x >>= \mi -> case mi of Just i -> return i Nothing -> do i <- newID addNode i $ G.Frontier x saveAtomID x i return i -- | Convert the given tree to a trivial feature graph. -- The result (`conI` and `conC`) will be represented -- within the state of the monad. fromAV :: (Functor m, Monad m, Ord i, Ord f, Ord a) => AV i f a -> ConT i f a m ID fromAV fs = do i <- newID xs <- forM (M.toList fs) (secondM fromFN) addNode i $ G.Interior $ M.fromList xs return i -- | Register the relation between the new and the old identifier. register :: (Monad m, Ord i, Ord f, Eq a) => ID -> i -> ConT i f a m () register i j = S.modify $ \st@ConS{..} -> let conI' = M.alter (addKey i) j conI in st { conI = conI' } where addKey x Nothing = Just $ Set.singleton x addKey x (Just s) = Just $ Set.insert x s -- | Rertieve ID for the given atom. atomID :: (Functor m, Monad m, Ord a) => a -> ConT i f a m (Maybe ID) atomID x = M.lookup x <$> S.gets conA -- | Save info about ID of the given atom. saveAtomID :: (Monad m, Ord a) => a -> ID -> ConT i f a m () saveAtomID x i = S.modify $ \st -> st {conA = M.insert x i $ conA st} -- | New identifier. newID :: Monad m => ConT i f a m ID newID = S.state $ \st@ConS{..} -> (conC, st {conC=conC+1}) -- | Add node. addNode :: Monad m => ID -> G.Node ID f a -> ConT i f a m () addNode i = S.lift . J.setNode i -- -- | Compile a named feature tree to a graph representation. -- compile :: (Ord i, Eq a, Ord f) => FN i f a -> Maybe (ID, G.Graph f a) -- compile x = flip J.runJoin G.empty $ do -- -- First we need to convert a tree to a trivial feature graph -- -- (tree stored as `conC`) and identify nodes which need to be -- -- joined. -- (r0, st) <- S.runStateT (fromFN x) initConS -- -- The second step is to join all nodes which have to be -- -- merged based on the identifiers specified by the user. -- forM_ (M.elems $ conI st) $ \ks -> do -- forM_ (adja $ Set.toList ks) $ \(i, j) -> do -- J.join i j -- J.liftGraph $ G.getRepr r0 -- -- | Compile a traversable structure of named feature trees -- -- to a graph representation. The resulting traversable data -- -- structure will be returned with identifiers in place of -- -- named feature trees. -- compiles -- :: (Ord i, Eq a, Ord f, T.Traversable t) -- => t (FN i f a) -> Maybe (t ID, G.Graph f a) -- compiles t0 = flip J.runJoin G.empty $ do -- -- First we need to convert a traversable to a trivial feature -- -- graph (`conC`) and identify nodes which need to be joined. -- (t1, st) <- S.runStateT (fromTravFN t0) initConS -- -- The second step is to join all nodes which have to be -- -- merged based on the identifiers specified by the user. -- forM_ (M.elems $ conI st) $ \ks -> do -- forM_ (adja $ Set.toList ks) $ \(i, j) -> do -- J.join i j -- T.mapM (J.liftGraph . G.getRepr) t1 -------------------------------------------------------------------- -- Misc -------------------------------------------------------------------- -- | Run a monadic action on a `Just` value. justM :: Monad m => Maybe a -> (a -> m ()) -> m () justM (Just x) f = f x justM Nothing _ = return () -- | Run a monadic action on a second element of a pair. secondM :: Monad m => (b -> m c) -> (a, b) -> m (a, c) secondM f (x, y) = do z <- f y return (x, z) -- | Pairs of adjacent elements in a list. adja :: [a] -> [(a, a)] adja xs = zip xs (drop 1 xs)
kawu/feature-structure
src/NLP/FeatureStructure/Tree.hs
bsd-2-clause
9,141
0
17
2,402
2,316
1,255
1,061
143
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module HERMIT.Dictionary.WorkerWrapper.Common ( externals , WWAssumptionTag(..) , WWAssumption(..) , assumptionAClauseT , assumptionBClauseT , assumptionCClauseT , split1BetaR , split2BetaR , workLabel ) where import Control.Arrow import Control.Monad.IO.Class import Data.String (fromString) import Data.Typeable import HERMIT.Context import HERMIT.Core import HERMIT.External import HERMIT.GHC import HERMIT.Kure import HERMIT.Lemma import HERMIT.Monad import HERMIT.ParserCore import HERMIT.Dictionary.Common import HERMIT.Dictionary.Function hiding (externals) import HERMIT.Dictionary.Reasoning hiding (externals) import HERMIT.Name -------------------------------------------------------------------------------------------------- -- | New Worker/Wrapper-related externals. externals :: [External] externals = map (.+ Proof) [ external "intro-ww-assumption-A" (\nm absC repC -> do q <- parse2BeforeT assumptionAClauseT absC repC insertLemmaT nm $ Lemma q NotProven NotUsed :: TransformH LCore ()) [ "Introduce a lemma for worker/wrapper assumption A" , "using given abs and rep functions." ] , external "intro-ww-assumption-B" (\nm absC repC bodyC -> do q <- parse3BeforeT assumptionBClauseT absC repC bodyC insertLemmaT nm $ Lemma q NotProven NotUsed :: TransformH LCore ()) [ "Introduce a lemma for worker/wrapper assumption B" , "using given abs, rep, and body functions." ] , external "intro-ww-assumption-C" (\nm absC repC bodyC -> do q <- parse3BeforeT assumptionCClauseT absC repC bodyC insertLemmaT nm $ Lemma q NotProven NotUsed :: TransformH LCore ()) [ "Introduce a lemma for worker/wrapper assumption C" , "using given abs, rep, and body functions." ] , external "split-1-beta" (\ nm absC -> promoteExprR . parse2BeforeT (split1BetaR Obligation nm) absC :: CoreString -> RewriteH LCore) [ "split-1-beta <name> <abs expression> <rep expression>" , "Perform worker/wrapper split with condition 1-beta." , "Given lemma name argument is used as prefix to two introduced lemmas." , " <name>-assumption: unproven lemma for w/w assumption C." , " <name>-fusion: assumed lemma for w/w fusion." ] , external "split-2-beta" (\ nm absC -> promoteExprR . parse2BeforeT (split2BetaR Obligation nm) absC :: CoreString -> RewriteH LCore) [ "split-2-beta <name> <abs expression> <rep expression>" , "Perform worker/wrapper split with condition 2-beta." , "Given lemma name argument is used as prefix to two introduced lemmas." , " <name>-assumption: unproven lemma for w/w assumption C." , " <name>-fusion: assumed lemma for w/w fusion." ] ] -------------------------------------------------------------------------------------------------- data WWAssumptionTag = A | B | C deriving (Eq,Ord,Show,Read,Typeable) instance Extern WWAssumptionTag where type Box WWAssumptionTag = WWAssumptionTag box i = i unbox i = i data WWAssumption = WWAssumption WWAssumptionTag (RewriteH CoreExpr) deriving Typeable -------------------------------------------------------------------------------------------------- -- Note: The current approach to WW Fusion is a hack. -- I'm not sure what the best way to approach this is though. -- An alternative would be to have a generate command that adds ww-fusion to the dictionary, all preconditions verified in advance. -- That would have to exist at the Shell level though. -- This isn't entirely safe, as a malicious the user could define a label with this name. workLabel :: LemmaName workLabel = fromString "recursive-definition-of-work-for-use-by-ww-fusion" -------------------------------------------------------------------------------------------------- -- Given abs and rep expressions, build "abs . rep = id" assumptionAClauseT :: ( BoundVars c, HasHermitMEnv m, LiftCoreM m, MonadCatch m, MonadIO m, MonadThings m ) => CoreExpr -> CoreExpr -> Transform c m x Clause assumptionAClauseT absE repE = prefixFailMsg "Building assumption A failed: " $ do comp <- buildCompositionT absE repE let (_,compBody) = collectTyBinders comp (tvs, xTy, _) <- splitFunTypeM (exprType comp) idE <- buildIdT xTy return $ mkForall tvs (Equiv compBody idE) -- Given abs, rep, and f expressions, build "abs . rep . f = f" assumptionBClauseT :: ( BoundVars c, HasHermitMEnv m, LiftCoreM m, MonadCatch m, MonadIO m, MonadThings m) => CoreExpr -> CoreExpr -> CoreExpr -> Transform c m x Clause assumptionBClauseT absE repE fE = prefixFailMsg "Building assumption B failed: " $ do repAfterF <- buildCompositionT repE fE comp <- buildCompositionT absE repAfterF let (tvs,lhs) = collectTyBinders comp rhs <- appArgM 5 lhs >>= appArgM 5 -- get f with proper tvs applied return $ mkForall tvs (Equiv lhs rhs) -- Given abs, rep, and f expressions, build "fix (abs . rep . f) = fix f" assumptionCClauseT :: (BoundVars c, HasHermitMEnv m, LiftCoreM m, MonadCatch m, MonadIO m, MonadThings m) => CoreExpr -> CoreExpr -> CoreExpr -> Transform c m x Clause assumptionCClauseT absE repE fE = prefixFailMsg "Building assumption C failed: " $ do (vs, Equiv lhs rhs) <- collectQs ^<< assumptionBClauseT absE repE fE lhs' <- buildFixT lhs rhs' <- buildFixT rhs return $ mkForall vs (Equiv lhs' rhs') -- Given abs, rep, and 'fix g' expressions, build "rep (abs (fix g)) = fix g" wwFusionClauseT :: MonadCatch m => CoreExpr -> CoreExpr -> CoreExpr -> Transform c m x Clause wwFusionClauseT absE repE fixgE = prefixFailMsg "Building worker/wrapper fusion lemma failed: " $ do protoLhs <- buildAppM repE =<< buildAppM absE fixgE let (tvs, lhs) = collectTyBinders protoLhs -- This way, the rhs is applied to the proper type variables. rhs <- case lhs of (App _ (App _ rhs)) -> return rhs _ -> fail "lhs malformed" return $ mkForall tvs (Equiv lhs rhs) -- Perform the worker/wrapper split using condition 1-beta, introducing -- an unproven lemma for assumption C, and an appropriate w/w fusion lemma. split1BetaR :: ( AddBindings c, ExtendPath c Crumb, HasCoreRules c, LemmaContext c, ReadBindings c, ReadPath c Crumb , HasHermitMEnv m, LiftCoreM m, HasLemmas m, MonadCatch m, MonadIO m, MonadThings m , MonadUnique m ) => Used -> LemmaName -> CoreExpr -> CoreExpr -> Rewrite c m CoreExpr split1BetaR u nm absE repE = do (_fixId, [_tyA, f]) <- callNameT $ fromString "Data.Function.fix" g <- prefixFailMsg "building (rep . f . abs) failed: " $ buildCompositionT repE =<< buildCompositionT f absE gId <- constT $ newIdH "g" $ exprType g workRhs <- buildFixT $ varToCoreExpr gId workId <- constT $ newIdH "worker" $ exprType workRhs newRhs <- prefixFailMsg "building (abs work) failed: " $ buildAppM absE (varToCoreExpr workId) assumptionQ <- assumptionCClauseT absE repE f verifyOrCreateT u (fromString (show nm ++ "-assumption")) assumptionQ wwFusionQ <- wwFusionClauseT absE repE workRhs insertLemmaT (fromString (show nm ++ "-fusion")) $ Lemma wwFusionQ BuiltIn NotUsed return $ mkCoreLets [NonRec gId g, NonRec workId workRhs] newRhs split2BetaR :: ( AddBindings c, ExtendPath c Crumb, HasCoreRules c, LemmaContext c, ReadBindings c, ReadPath c Crumb , HasHermitMEnv m, LiftCoreM m, HasLemmas m, MonadCatch m, MonadIO m, MonadThings m , MonadUnique m ) => Used -> LemmaName -> CoreExpr -> CoreExpr -> Rewrite c m CoreExpr split2BetaR u nm absE repE = do (_fixId, [_tyA, f]) <- callNameT $ fromString "Data.Function.fix" fixfE <- idR repFixFE <- buildAppM repE fixfE workId <- constT $ newIdH "worker" $ exprType repFixFE newRhs <- buildAppM absE (varToCoreExpr workId) assumptionQ <- assumptionCClauseT absE repE f verifyOrCreateT u (fromString (show nm ++ "-assumption")) assumptionQ wwFusionQ <- wwFusionClauseT absE repE (varToCoreExpr workId) insertLemmaT (fromString (show nm ++ "-fusion")) $ Lemma wwFusionQ BuiltIn NotUsed return $ mkCoreLets [NonRec workId repFixFE] newRhs
beni55/hermit
src/HERMIT/Dictionary/WorkerWrapper/Common.hs
bsd-2-clause
8,499
0
15
1,835
1,968
990
978
133
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Script.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:14 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Script ( module Qtc.ClassTypes.Script , module Qtc.Classes.Script ) where import Qtc.ClassTypes.Script import Qtc.Classes.Script
uduki/hsQt
Qtc/Script.hs
bsd-2-clause
559
0
5
98
38
27
11
6
0
import Obsidian.GCDObsidian import qualified Obsidian.GCDObsidian.CodeGen.CUDA as CUDA import Prelude hiding (zipWith,splitAt) import Data.Word import Data.Bits import Data.List hiding (zipWith,splitAt) -- for Library? (or wherever composeS is defined ?) --compose :: (Scalar a) => [Array (Exp a) -> Array (Exp a)] -> Array (Exp a) -> Kernel (Array (Exp a)) compose = composeS . map pure --composeP :: (Scalar a) => [Array (Exp a) -> ArrayP (Exp a)] -> Array (Exp a) -> Kernel (Array (Exp a)) composeP :: Syncable a b => [Array b -> (a b)] -> Array b -> Kernel (Array b) composeP = composeS . map pure -- first, bitonic merge bmerge :: Int -> [Array IntE -> Array IntE] bmerge n = [stage (n-i) | i <- [1..n]] where stage i = ilv1 i min max -- I showed this call in the paper runm k = putStrLn$ CUDA.genKernel "bitonicMerge" (compose (bmerge k)) (namedArray "inp" (2^k)) -- Here is a general version rungen k s f = putStrLn$ CUDA.genKernel s (compose (f k)) (namedArray "inp" (2^k)) -- Next, replace the first ilv by a vee to get a merger that sorts two concatenated sorted lists (tmerge) -- ilv1 and vee1 are in Library.hs tmerge :: Int -> [Array IntE -> Array IntE] tmerge n = vstage (n-1) : [ istage (n-i) | i <- [2..n]] where vstage i = vee1 i min max istage i = ilv1 i min max -- runt k = rungen k "tMerge" (tmerge k) printtmerge k = putStrLn $ CUDA.genKernel "tmerge1" (composeP (tmerge k)) (namedArray "inp" (2^k)) -- Because tmerge sorts two half-length sorted lists, it is easy to compose a tree of them to make a sorter (tsort1) tsort1 :: Int -> [Array IntE -> Array IntE] tsort1 n = concat [tmerge i | i <- [1..n]] writegen k s f = writeFile (s ++ ".cu") $ CUDA.genKernel s (compose (f k)) (namedArray "inp" (2^k)) runs1 k = writegen k "tsort1" tsort1 printtsort1 k = putStrLn $ CUDA.genKernel "tsort1" (compose (tsort1 k)) (namedArray "inp" (2^k)) -- Next step is to play with push arrays. Need to reimplement ilv1 and vee1. -- See ilv2 and vee2 in Library.hs tmerge2 :: Int -> [Array IntE -> ArrayP IntE] tmerge2 n = vee2 (n-1) min max : [(ilv2 (n-i) min max)| i <- [2..n]] printtmerge2 k = putStrLn $ CUDA.genKernel "tmerge2" (composeP (tmerge2 k)) (namedArray "inp" (2^k)) tsort2 :: Int -> [Array IntE -> ArrayP IntE] tsort2 n = concat [tmerge2 i | i <- [1..n]] -- Unfortunately, now I have to use composeP. writes2 k = writeFile "tsort2.cu" $ CUDA.genKernel "tsort2" (composeP (tsort2 k)) (namedArray "inp" (2^k)) printtsort2 k = putStrLn $ CUDA.genKernel "tsort2" (composeP (tsort2 k)) (namedArray "inp" (2^k)) -- Next balanced bitonic merger bpmerge2 :: Int -> [Array IntE -> ArrayP IntE] bpmerge2 n = [vee2 (n-i) min max | i <- [1..n]] runbp = putStrLn$ CUDA.genKernel "bpMerge" (composeP (bpmerge2 5)) (namedArray "inp" 32) -- Now to vsort -- ilvVee1 (without Push arrays) and ilvVee2 (with) are in Library.hs vsort1 :: Int -> Array IntE -> Kernel (Array IntE) vsort1 n = compose [ istage(n-i) (i-j) | i <- [1..n], j <- [1..i]] where istage i j = ilvVee1 i j min max writevsort1 k = writeFile "vsort1.cu" $ CUDA.genKernel "vsort1" (vsort1 k) (namedArray "apa" (2^k)) printvsort1 k = putStrLn $ CUDA.genKernel "vsort1" (vsort1 k) (namedArray "apa" (2^k)) -- This is the fastest kernel vsort :: Int -> Array IntE -> Kernel (Array IntE) vsort n = composeS . map pure $ [ istage (n-i) (i-j) | i <- [1..n], j <- [1..i]] where istage i j = ilvVee2 i j min max writevsort k = writeFile "vsort.cu" $ CUDA.genKernel "vsort" (vsort k) (namedArray "inp" (2^k)) printvsort k = putStrLn$ CUDA.genKernel "vsort" (vsort k) (namedArray "inp" (2^k)) halve' arr = splitAt ((len arr) `div` 2) arr ---------------------------------------------------------------------------- -- Key/value pair versions tmerge2p :: Int -> [Array (IntE,IntE) -> ArrayP (IntE,IntE)] tmerge2p n = vee2 (n-1) min2 max2 : [(ilv2 (n-i) min2 max2)| i <- [2..n]] where min2 (k1,v1) (k2,v2) = ifThenElse (k1 <* k2) (k1,v1) (k2,v2) max2 (k1,v1) (k2,v2) = ifThenElse (k1 >* k2) (k1,v1) (k2,v2) printtmerge2p k = putStrLn $ CUDA.genKernel "tmerge2" (composeP (tmerge2p k)) (zipp (namedArray "keys" (2^k), namedArray "values" (2^k))) tsort2p :: Int -> [Array (IntE,IntE) -> ArrayP (IntE,IntE)] tsort2p n = concat [tmerge2p i | i <- [1..n]] -- Unfortunately, now I have to use composeP. --writetsort2p k = writeFile "tsort2.cu" $ CUDA.genKernel "tsort2" (composeP (tsort2 k)) (namedArray "inp" (2^k)) --printtsort2p k = putStrLn $ CUDA.genKernel "tsort2" (composeP (tsort2 k)) (namedArray "inp" (2^k))
svenssonjoel/GCDObsidian
DAMP2012/Paper.hs
bsd-3-clause
4,753
21
12
1,041
1,877
931
946
56
1
module Hear.Trainer where import Text.Printf import Text.Read import System.Exit import System.IO import System.Console.ANSI import Control.Exception import Data.Maybe import Hear.RandomTones import Hear.Music import Euterpea clearFromLine :: Int -> IO() clearFromLine n = do setCursorPosition n 0 clearFromCursorToScreenEnd playInterval :: Interval -> IO() playInterval (x, y) = play . line $ map (note (1/2)) [pitch x, pitch y] withEcho :: Bool -> IO a -> IO a withEcho echo action = do old <- hGetEcho stdin bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action printAns :: Interval -> IO() printAns (x, y) = do let diff = y - x putStrLn "" printf "Midi Numbers : " print (x, y) printf "Notes : " print (pitch x, pitch y) printf "Interval in Semitones : %d, %s\n" diff (intervalName diff) freePractise :: IO() freePractise = do clearFromLine 0 putStrLn helpstring tns <- randTones 1 (60, 70) [] go $ head tns where helpstring = "p play tones s sing the tones between the interval a show answer q quit" go :: Interval -> IO() go tnl = do tmp <- withEcho False getChar case tmp of 'p' -> playInterval tnl 'n' -> do xs <- randTones 1 (40, 80) [] go $ head xs 'a' -> printAns tnl 's' -> play $ (toMusic . tonePath) tnl 'q' -> exitSuccess _ -> putStrLn "press h for available commands" go tnl intervalTest :: Int -> [Int] -> IO() intervalTest x intervals = do clearFromLine 0 putStrLn helpstring tns <- randTones x (40, 80) intervals result <- mapM (`go` Nothing) tns let rightAns = length $ filter (== True) result printf "Score : %d / %d\n" rightAns x where helpstring ="p play tones a give answer q quit" go :: Interval -> Maybe Int -> IO Bool go tnl ans | isNothing ans = do clearFromLine 1 tmp <- withEcho False getChar case tmp of 'p' -> do playInterval tnl go tnl Nothing 'a' -> do new_ans <- takeAns go tnl new_ans 'q' -> exitSuccess _ -> go tnl Nothing | otherwise = do result <- checkAns $ fromJust ans putStrLn "any key for next question" _ <- withEcho False getChar return result where checkAns :: AbsPitch -> IO Bool checkAns answer | answer == correct_ans = do putStrLn "Correct!" printAns tnl return True | otherwise = do putStrLn "Nope!" printAns tnl return False correct_ans = snd tnl - fst tnl takeAns :: IO (Maybe Int) takeAns = do putStr "Answer:" tmp <- getLine return (readMaybe tmp :: Maybe Int) trainer :: IO() trainer = do clearFromLine 0 hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering putStrLn "t Test Mode, f Free Practise" mode <- withEcho False getChar case mode of 't' -> do putStrLn "q Quick (10 questions), m Medium (25), l Long (50)" len <- takeLen putStrLn "e Easy, m Medium, h Hard" difficulty <- takeDiff intervalTest len difficulty 'f' -> freePractise _ -> trainer where takeLen :: IO Int takeLen = do hFlush stdout len <- withEcho False getChar case len of 'q' -> return 10 'm' -> return 25 'l' -> return 50 _ -> takeLen takeDiff :: IO [Int] takeDiff = do hFlush stdout diff <- withEcho False getChar case diff of 'e' -> return [3, 4, 7, 12, -3, -4, -7, -12] 'm' -> return [1, 2, 3, 4, 6, 7, 10, 11, 12, -1, -2, -3, -4, -6, -7, -10, -11, -12] 'h' -> return [] _ -> takeDiff
no-scope/hear
src/Hear/Trainer.hs
bsd-3-clause
4,060
0
16
1,495
1,325
628
697
127
9
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# OPTIONS_HADDOCK show-extensions #-} {-| Module : $Header$ Copyright : (c) 2016 Deakin Software & Technology Innovation Lab License : BSD3 Maintainer : Rhys Adams <[email protected]> Stability : unstable Portability : portable API executable entry point. -} module Main (main) where import Eclogues.Prelude import Eclogues.API (AbsoluteURI (..)) import Eclogues.AppConfig (AppConfig (AppConfig)) import qualified Eclogues.AppConfig as Config import qualified Eclogues.Job as Job import qualified Eclogues.Persist as Persist import qualified Eclogues.State.Monad as ES import Eclogues.State.Types (AppState) import Eclogues.Threads.Schedule (processCommands) import Eclogues.Threads.Update (loadSchedulerState) import Eclogues.Threads.Server (serve) import Control.Concurrent (threadDelay) import qualified Control.Concurrent.AdvSTM as STM import Control.Concurrent.AdvSTM.TChan (newTChanIO, writeTChan) import Control.Concurrent.AdvSTM.TVar (newTVarIO) import Control.Concurrent.Async (Concurrently (..), runConcurrently) import Control.Monad.Trans (lift) import Data.Aeson (FromJSON (..), ToJSON (..), eitherDecode, withScientific, withText) import Data.Aeson.TH (deriveFromJSON) import Data.ByteString.Lazy (readFile) import Data.Default.Generics (def) import Data.List.NonEmpty (NonEmpty ((:|))) import Data.Scientific.Suspicious (isInteger, toSustific) import qualified Data.Text as T import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Word (Word16) import Network.HTTP.Client (newManager, defaultManagerSettings) import Path (mkRelDir, parseAbsDir) import Path.IO (createDirIfMissing) import Prelude hiding (readFile) import Say (sayErrString) import Servant.Client (BaseUrl, parseBaseUrl, showBaseUrl) import System.Environment (getArgs) import System.Random (mkStdGen, setStdGen) import System.Exit (die) import Units.Micro (exp10Factor, of') import Units.Micro.SI (Byte (..), Mega (..), Micro (..), Second (..)) newtype DataMB = DataMB { _getData :: Job.Data } deriving (Show, Eq) instance FromJSON DataMB where parseJSON = withScientific "data value" check where check d | dv >= 0 && isInteger dv = pure . DataMB $ dv `of'` Mega Byte | otherwise = fail "must be natural number of megabytes" where dv = toSustific d newtype JsonBaseUrl = JsonBaseUrl { getBaseUrl :: BaseUrl } instance FromJSON JsonBaseUrl where parseJSON = withText "base url" (either (fail . show) (pure . JsonBaseUrl) . parseBaseUrl . T.unpack) instance ToJSON JsonBaseUrl where toJSON = toJSON . showBaseUrl . getBaseUrl newtype AbsDir = AbsDir { getDir :: Path Abs Dir } instance FromJSON AbsDir where parseJSON = withText "absolute dir" $ toP . parseAbsDir . T.unpack where toP = either (fail . show) (pure . AbsDir) -- NB: Also documented in README. Please keep it up to date. -- | User-supplied API configuration. data ApiConfig = ApiConfig { stateDir :: AbsDir , bindAddress :: String , bindPort :: Word16 , reservedMemMB :: DataMB , nomadUrl :: JsonBaseUrl , advertiseUrl :: AbsoluteURI } $(deriveFromJSON defaultOptions ''ApiConfig) main :: IO () main = do seedStdGen confPath <- getArgs >>= \case [p] -> pure p _ -> error "Usage: eclogues-api CONFIG-FILE" apiConf@ApiConfig{..} <- either (die . show) pure =<< readJSON confPath withConfig apiConf where readJSON = fmap eitherDecode . readFile withConfig :: ApiConfig -> IO a withConfig apiConf = do let stdir = getDir $ stateDir apiConf absContainerDir = stdir </> $(mkRelDir "containers") schedV <- newTChanIO -- Scheduler action channel createDirIfMissing False stdir createDirIfMissing False absContainerDir Persist.withPersistDir stdir $ \pctx' -> do let conf = AppConfig schedV pctx' (getBaseUrl $ nomadUrl apiConf) (advertiseUrl apiConf) absContainerDir lift $ withPersist apiConf conf withPersist :: ApiConfig -> AppConfig -> IO a withPersist apiConf conf = do st <- loadFromDB conf stateV <- newTVarIO st clusterV <- newTVarIO Nothing http <- newManager defaultManagerSettings let web = serve (pure ()) host port conf stateV clusterV updater = forever $ do loadSchedulerState http conf stateV threadDelay $ 10 ^ exp10Factor @Second @(Micro Second) -- TODO: catch run error and reschedule enacter = processCommands http conf stateV threads = Concurrently (const (error "web failed") <$> web) :| Concurrently updater : [Concurrently enacter] sayErrString $ "Starting server on " ++ host ++ ':':show port runConcurrently $ foldl1' (<|>) threads where host = bindAddress apiConf port = fromIntegral $ bindPort apiConf foldl1' :: (a -> a -> a) -> NonEmpty a -> a foldl1' f (h :| t) = foldl' f h t loadFromDB :: AppConfig -> IO AppState loadFromDB conf = fmap ((^. ES.appState) . snd) . ES.runStateTS def $ do (es, cmds, cnts) <- Persist.atomically (Config.pctx conf) $ (,,) <$> Persist.allEntities <*> Persist.allIntents <*> Persist.allContainers ES.loadEntities es ES.loadContainers cnts lift . STM.atomically $ mapM_ (writeTChan $ Config.schedChan conf) cmds -- | Seed the PRNG with the current time. seedStdGen :: IO () seedStdGen = do curTime <- getPOSIXTime -- Unlikely to start twice within a millisecond let pico = floor (curTime * 1e3) :: Int setStdGen $ mkStdGen pico
rimmington/eclogues
eclogues-impl/app/api/Main.hs
bsd-3-clause
5,917
0
17
1,338
1,562
857
705
122
2
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE BangPatterns #-} module Main (main) where import Criterion.Main import Data.Hourglass import System.Hourglass import TimeDB import Data.List (intercalate) import qualified Data.Time.Calendar as T import qualified Data.Time.Clock as T import qualified Data.Time.Clock.POSIX as T import qualified System.Locale as T timeToTuple :: T.UTCTime -> (Int, Int, Int, Int, Int, Int) timeToTuple utcTime = (fromIntegral y, m, d, h, mi, sec) where (!y,!m,!d) = T.toGregorian (T.utctDay utcTime) !daytime = floor $ T.utctDayTime utcTime (!dt, !sec) = daytime `divMod` 60 (!h , !mi) = dt `divMod` 60 timeToTupleDate :: T.UTCTime -> (Int, Int, Int) timeToTupleDate utcTime = (fromIntegral y, m, d) where (!y,!m,!d) = T.toGregorian (T.utctDay utcTime) elapsedToPosixTime :: Elapsed -> T.POSIXTime elapsedToPosixTime (Elapsed (Seconds s)) = fromIntegral s timePosixDict :: [ (Elapsed, T.POSIXTime) ] timePosixDict = [-- (Elapsed 0, 0) --, (Elapsed 1000000, 1000000) --, (Elapsed 9000099, 9000099) {-,-} (Elapsed 1398232846, 1398232846) -- currentish time (at the time of writing) --, (Elapsed 5134000099, 5134000099) --, (Elapsed 10000000000000, 10000000000000) -- year 318857 .. ] dateDict :: [ (Int, Int, Int, Int, Int, Int) ] dateDict = [{- (1970, 1, 1, 1, 1, 1) , -}(2014, 5, 5, 5, 5, 5) --, (2114, 11, 5, 5, 5, 5) ] main :: IO () main = defaultMain [ bgroup "highlevel" $ concatMap toHighLevel timePosixDict , bgroup "to-dateTime" $ concatMap toCalendar timePosixDict , bgroup "to-date" $ concatMap toCalendarDate timePosixDict , bgroup "utc-to-date" $ concatMap toCalendarUTC timePosixDict , bgroup "to-posix" $ concatMap toPosix dateDict , bgroup "system" fromSystem ] where toHighLevel (posixHourglass, posixTime) = [ bench (showH posixHourglass) $ nf timeGetDateTimeOfDay posixHourglass , bench (showT posixTime) $ nf T.posixSecondsToUTCTime posixTime ] toCalendar (posixHourglass, posixTime) = [ bench (showH posixHourglass) $ nf timeGetDateTimeOfDay posixHourglass , bench (showT posixTime) $ nf (timeToTuple . T.posixSecondsToUTCTime) posixTime ] toCalendarDate (posixHourglass, posixTime) = [ bench (showH posixHourglass) $ nf timeGetDate posixHourglass , bench (showT posixTime) $ nf (timeToTupleDate . T.posixSecondsToUTCTime) posixTime ] toCalendarUTC (posixHourglass, posixTime) = [ bench (showH posixHourglass) $ nf timeGetDateTimeOfDay posixHourglass , bench (showT utcTime) $ nf timeToTuple utcTime ] where !utcTime = T.posixSecondsToUTCTime posixTime toPosix v = [ bench ("hourglass/" ++ n v) $ nf hourglass v , bench ("time/" ++ n v) $ nf time v ] where n (y,m,d,h,mi,s) = (intercalate "-" $ map show [y,m,d]) ++ " " ++ (intercalate ":" $ map show [h,mi,s]) hourglass (y,m,d,h,mi,s) = timeGetElapsed $ DateTime (Date y (toEnum (m-1)) d) (TimeOfDay (fromIntegral h) (fromIntegral mi) (fromIntegral s) 0) time (y,m,d,h,mi,s) = let day = T.fromGregorian (fromIntegral y) m d diffTime = T.secondsToDiffTime $ fromIntegral (h * 3600 + mi * 60 + s) in T.utcTimeToPOSIXSeconds (T.UTCTime day diffTime) fromSystem = [ bench ("hourglass/p") $ nfIO timeCurrent , bench ("hourglass/ns") $ nfIO timeCurrentP , bench ("time/posixTime") $ nfIO T.getPOSIXTime , bench ("time/utcTime") $ nfIO T.getCurrentTime ] showH :: Show a => a -> String showH a = "hourglass/" ++ show a showT :: Show a => a -> String showT a = "time/" ++ show a
ppelleti/hs-hourglass
tests/Bench.hs
bsd-3-clause
3,963
0
19
1,086
1,249
671
578
69
1
module Util.File ( recurseDirs , allDirs , allFiles , mkdir_p , mkdir ) where import Control.Monad import System.Directory import System.FilePath ((</>)) recurseDirs :: FilePath -> IO [FilePath] recurseDirs baseDir = do contents <- getDirectoryContents baseDir let contentChildren = filter (`notElem` [".", ".."]) contents paths <- forM contentChildren $ returnOrRecurse baseDir return $ concat paths where returnOrRecurse baseDir fileOrDir = do let path = baseDir </> fileOrDir isDir <- doesDirectoryExist path if isDir then recurseDirs path else return [path] allDirs :: FilePath -> IO [FilePath] allDirs dir = do rawDirs <- getDirectoryContents dir >>= filterM doesDirectoryExist let dirs = filter (`notElem` [".", ".."]) rawDirs -- remove ./ and ../ return dirs allFiles :: FilePath -> IO [FilePath] allFiles dir = getDirectoryContents dir >>= filterM doesFileExist mkdir_p :: [FilePath] -> IO FilePath mkdir_p = foldM (\acc i -> mkdir (acc </> i) >> return (acc </> i)) "" mkdir :: FilePath -> IO () mkdir fp = do b <- doesDirectoryExist fp if b then return () else createDirectory fp
phylake/haskell-util
File.hs
bsd-3-clause
1,220
0
12
298
402
205
197
36
2
{-# LANGUAGE OverloadedStrings #-} module Waldo.Script ( Script(..) , PanelSizes, PanelData(..), Panel(..) , ImagePart(..) , TextPart(..) , Pos(..) , loadImagePanels, mkScript, scriptName ) where import Data.List import Control.Monad import qualified Data.Text as T import qualified Data.Aeson as JS import qualified Data.ByteString.Lazy.Char8 as BSL8 import Control.Monad.Trans.Resource (runResourceT) import Data.Conduit (($$)) import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.ImageSize as CI import System.FilePath ((</>), takeFileName, splitExtension) import System.Path.Glob import Data.Digest.Pure.SHA import Control.DeepSeq import Data.Aeson ((.=)) pad :: Int pad = 4 panelRightEdge :: Panel -> Int panelRightEdge p = (pX $ pPos p) + (pWidth p) scriptName :: Script -> T.Text scriptName (s@Script {}) = T.concat $ [sName s, " : "] ++ (intersperse "+" $ map pName (sPanels s)) scriptName (ScriptTo goto) = T.concat ["Goto : ", goto] mkScript :: T.Text -- name -> T.Text -- alt-text -> [PanelData] -- panels! -> Script mkScript nm alt pds = let ps = snd $ mapAccumL (\xstart p -> let newp = panelData2panel xstart p in (panelRightEdge newp, newp)) 0 pds in Script { sAltText = alt , sPanels = ps , sHeight = 2*pad + (maximum $ map pHeight ps) , sWidth = (1+length ps)*pad + (sum $ map pWidth ps) , sName = nm } hashImgNm :: FilePath -> FilePath hashImgNm fn = let (nm, typ) = splitExtension fn in (showDigest $ sha256 (BSL8.pack ("basfd" ++ nm)))++typ loadImagePanels :: Int -- Story -> Int -- Panel -> Int -- Choice -> IO PanelSizes loadImagePanels s p c = do fns <- glob ("panels" </> ("a1_"++show s++"p"++show p++"s*_"++show c++".*")) ps <- forM fns $ \fn -> do mImgInf <- runResourceT $ CB.sourceFile fn $$ CI.sinkImageSize case mImgInf of Nothing -> fail "Couldn't read image." Just sz -> do let pname = hashImgNm $ takeFileName fn d <- BSL8.readFile fn BSL8.writeFile ("loadedPanels" </> pname) d return $ PanelData { pdWidth = CI.width sz , pdHeight = CI.height sz , pdImages = [ImagePart { ipPos = Pos 0 0, ipImageUrl = T.pack pname }] , pdText = [] , pdName = T.pack ("p"++show p++"s"++show s++"_"++show c) } if null ps then fail ("No panels found for "++show (s, p, c)) else return ps panelData2panel :: Int -> PanelData -> Panel panelData2panel xlast pd = Panel { pPos = Pos (xlast+pad) pad , pWidth = pdWidth pd , pHeight = pdHeight pd , pImages = pdImages pd , pText = pdText pd , pName = pdName pd } type PanelSizes = [PanelData] data Script = ScriptTo { sTarget :: !T.Text } | Script { sWidth :: !Int , sHeight :: !Int , sAltText :: !T.Text , sPanels :: [Panel] , sName :: !T.Text } deriving (Eq, Ord, Show) instance NFData Script where rnf (s@ScriptTo {sTarget=t}) = t `seq` s `seq` () rnf (s@Script {sWidth=w, sHeight=h, sAltText=a, sPanels=p, sName=n}) = w `seq` h `seq` a `deepseq` p `deepseq` n `deepseq` s `seq` () data Panel = Panel { pPos :: !Pos , pWidth :: !Int , pHeight :: !Int , pImages :: [ImagePart] , pText :: [TextPart] , pName :: !T.Text } deriving (Eq, Ord, Show) instance NFData Panel where rnf (pan@Panel {pPos=p, pWidth=w, pHeight=h, pImages=i, pText=t, pName=n}) = p `deepseq` w `seq` h `seq` i `deepseq` t `deepseq` n `deepseq` pan `seq` () data PanelData = PanelData { pdWidth :: !Int , pdHeight :: !Int , pdImages :: [ImagePart] , pdText :: [TextPart] , pdName :: !T.Text } deriving (Eq, Ord, Show) data ImagePart = ImagePart { ipPos :: !Pos , ipImageUrl :: !T.Text } deriving (Eq, Ord, Show) instance NFData ImagePart where rnf (i@ImagePart {ipPos=p, ipImageUrl=u}) = p `deepseq` u `deepseq` i `seq` () data TextPart = TextPart { tpPos :: !Pos , tpString :: !T.Text , tpSize :: !Float , tpFont :: !T.Text , tpAngle :: !Float } deriving (Eq, Ord, Show) instance NFData TextPart where rnf (tp@TextPart {tpPos=p, tpString=t, tpSize=s, tpFont=f, tpAngle=a}) = p `deepseq` t `deepseq` s `seq` f `deepseq` a `seq` tp `seq` () data Pos = Pos { pX :: !Int, pY :: !Int } deriving (Eq, Ord, Show) instance NFData Pos where rnf (p@Pos {pX=x, pY=y}) = x `seq` y `seq` p `seq` () instance JS.ToJSON Script where toJSON (ScriptTo t) = JS.object ["goto" .= t] toJSON (Script w h alt ps _) = JS.object [ "width" .= w , "height" .= h , "alttext" .= alt , "panels" .= ps ] instance JS.ToJSON Panel where toJSON (Panel p w h is ts _) = JS.object [ "pos" .= p , "width" .= w , "height" .= h , "images" .= is , "texts" .= ts ] instance JS.ToJSON ImagePart where toJSON (ImagePart p url) = JS.object [ "pos" .= p, "url" .= url ] instance JS.ToJSON TextPart where toJSON (TextPart p str sz f r) = JS.object [ "pos" .= p , "str" .= str , "size" .= sz , "font" .= f , "rad" .= r ] instance JS.ToJSON Pos where toJSON (Pos x y) = JS.object [ "x" .= x, "y" .= y ]
davean/waldo
Waldo/Script.hs
bsd-3-clause
5,916
0
27
2,037
2,151
1,210
941
198
3
module Language.Lambda.Syntax.Named.Testdata ( -- function s_ , k_ , i_ , omega_ , _Omega_ , fix_ -- logic , tru_ , fls_ , if_ , not_ , and_ , or_ , imp_ , iff_ -- arithmetic , iszro_ , scc_ , prd_ , add_ , sub_ , mlt_ , pow_ , leqnat_ , fac_ -- numbers , zro_ , one_ , n2_ , n3_ , n4_ , n5_ , n6_ , n7_ , n8_ , n9_ -- equality , eqbool_ , eqnat_ ) where import Language.Lambda.Syntax.Named.Exp -- functions -- S (substitution) s_ :: Exp String s_ = "x" ! "y" ! "z" ! Var "x" # Var "y" # (Var "x" # Var "z") -- K (constant) k_ :: Exp String k_ = "x" ! "y" ! Var "x" -- I (identity) i_ :: Exp String i_ = "x" ! Var "x" -- omega omega_ :: Exp String omega_ = "x" ! Var"x" # Var"x" _Omega_ :: Exp String _Omega_ = omega_ # omega_ -- fixpoint fix_ :: Exp String fix_ = "g" ! ("x" ! Var"g" # (Var"x" # Var"x")) # ("x" ! Var"g" # (Var"x" # Var"x")) -- logic tru_ :: Exp String tru_ = "t" ! "f" ! Var"t" fls_ :: Exp String fls_ = "t" ! "f" ! Var"f" if_ :: Exp String if_ = "p" ! "t" ! "f" ! Var"p" # Var"t" # Var"f" not_ :: Exp String not_ = "p" ! "x" ! "y" ! Var"p" # Var"y" # Var"x" and_ :: Exp String and_ = "p" ! "q" ! Var"p" # Var"q" # Var"p" or_ :: Exp String or_ = "p" ! "q" ! Var"p" # Var"p" # Var"q" imp_ :: Exp String imp_ = "p" ! "q" ! or_ # (not_ # Var"p") # Var"q" iff_ :: Exp String iff_ = "p" ! "q" ! and_ # (imp_ # Var"p" # Var"q") # (imp_ # Var"q" # Var"p") -- arithmetic zro_ :: Exp String zro_ = "f" ! "x" ! Var"x" one_ :: Exp String one_ = "f" ! "x" ! Var"f" # Var"x" iszro_ :: Exp String iszro_ = "n" ! Var"n" # ("_" ! fls_) # tru_ scc_ :: Exp String scc_ = "n" ! "f" ! "x" ! Var"f" # (Var"n" # Var"f" # Var"x") prd_ :: Exp String prd_ = "n" ! "f" ! "x" ! Var"n" # ("g" ! "h" ! Var"h" # (Var"g" # Var"f")) # ("_" ! Var"x") # i_ add_ :: Exp String add_ = "x" ! "y" ! if_ # (iszro_ # Var"y") # Var"x" # (add_ # (scc_ # Var"x") # (prd_ # Var"y")) sub_ :: Exp String sub_ = "x" ! "y" ! if_ # (iszro_ # Var"y") # Var"x" # (sub_ # (prd_ # Var"x") # (prd_ # Var"y")) mlt_ :: Exp String mlt_ = "x" ! "y" ! if_ # (iszro_ # Var"y") # zro_ # (add_ # Var"x" # (mlt_ # Var"x" # (prd_ # Var"y"))) pow_ :: Exp String pow_ = "b" ! "e" ! if_ # (iszro_ # Var"e") # one_ # (mlt_ # Var"b" # (pow_ # Var"b" # (prd_ # Var "e"))) fac_ :: Exp String fac_ = "x" ! if_ # (iszro_ # Var"x") # one_ # (mlt_ # Var"x" # (fac_ # (prd_ # Var"x"))) --relation leqnat_ :: Exp String leqnat_ = "x" ! "y" ! iszro_ # (sub_ # Var"x" # Var"y") -- equality eqbool_ :: Exp String eqbool_ = iff_ eqnat_ :: Exp String eqnat_ = "x" ! "y" ! and_ # (leqnat_ # Var"x" # Var"y") # (leqnat_ # Var"y" # Var"x") -- numbers n2_ :: Exp String n2_ = scc_ # one_ n3_ :: Exp String n3_ = scc_ # n2_ n4_ :: Exp String n4_ = scc_ # n3_ n5_ :: Exp String n5_ = scc_ # n4_ n6_ :: Exp String n6_ = scc_ # n5_ n7_ :: Exp String n7_ = scc_ # n6_ n8_ :: Exp String n8_ = scc_ # n7_ n9_ :: Exp String n9_ = scc_ # n8_
julmue/UntypedLambda
src/Language/Lambda/Syntax/Named/Testdata.hs
bsd-3-clause
3,270
0
12
1,072
1,531
795
736
119
1
module Problem113 where import Combinations main :: IO () -- increasing → sum_{r=1}^k 10Cr * (k-1)C(k-r) - 1 ⇒ (k+9)Ck - 1(for all zeroes) -- decreasing → sum_{r=1}^k [(r+9)Cr - 1] = (k+1)/10 * (k+10)C(k+1) - (k+1) [Sum telescopes] -- both → 9k [all same digits, 1-digit, 2-dgit and so on, each 9] -- increasing or decreasing → (k+9)Ck - 1 + (k+1)/10 * (k+10)C(k+1) - (k+1) - 9k main = print $ ((k + 9) `nCr` k) - 1 + ((k + 10) `nCr` (k + 1)) * (k + 1) `div` 10 - (k + 1) - 9 * k where k = 100
adityagupta1089/Project-Euler-Haskell
src/problems/Problem113.hs
bsd-3-clause
607
0
16
209
120
71
49
14
1
{-# LANGUAGE RecursiveDo #-} module Graphics.UI.WX.Turtle.Field( -- * types and classes Field(fFrame), Layer, Character, Coordinates(..), -- * basic functions openField, closeField, waitField, topleft, center, coordinates, fieldSize, -- * draw forkField, flushField, fieldColor, -- ** to Layer addLayer, drawLine, fillRectangle, fillPolygon, writeString, drawImage, undoLayer, undoField, clearLayer, -- ** to Character addCharacter, drawCharacter, drawCharacterAndLine, clearCharacter, -- * event driven oninputtext, onclick, onrelease, ondrag, onmotion, onkeypress, ontimer ) where import Graphics.UI.WX( on, command, Prop(..), text, button, frame, layout, widget, set, panel, Frame, Panel, minsize, sz, column, circle, paint, Point2(..), Point, line, repaint, DC, Rect, dcClear, polygon, red, green, brushColor, penColor, rgb, row, textEntry, processEnter, get, hfill, fill, size, Size2D(..), resize, TextCtrl, penWidth ) import qualified Graphics.UI.WX as WX import Graphics.UI.WX.Turtle.Layers( Layers, Layer, Character, newLayers, redrawLayers, makeLayer, background, addDraw, undoLayer, clearLayer, makeCharacter, character) import Text.XML.YJSVG(Position(..), Color(..), Font(..)) import Control.Monad(when, unless, forever, replicateM, forM_, join) import Control.Monad.Tools(doWhile_, doWhile) import Control.Arrow((***)) import Control.Concurrent( ThreadId, forkIO, killThread, threadDelay, Chan, newChan, readChan, writeChan) import Data.IORef(IORef, newIORef, readIORef, writeIORef) import Data.IORef.Tools(atomicModifyIORef_) import Data.Maybe(fromMaybe) import Data.List(delete) import Data.Convertible(convert) import Data.Function.Tools(const2, const3) -------------------------------------------------------------------------------- data Coordinates = CoordTopLeft | CoordCenter data Field = Field{ fFrame :: Frame (), fPanel :: Panel (), fAction :: IORef (DC () -> Rect -> IO ()), fActions :: IORef [DC () -> Rect -> IO ()], fCharacter :: Character, fCoordinates :: Coordinates, fPenColor :: (Int, Int, Int), fDrawColor :: (Int, Int, Int), fSize :: IORef (Double, Double), fInputtext :: IORef (String -> IO Bool), fLayers :: IORef Layers } -------------------------------------------------------------------------------- undoField :: Field -> IO () undoField f = do atomicModifyIORef_ (fActions f) tail openField :: IO Field openField = do fr <- frame [text := "turtle"] p <- panel fr [] quit <- button fr [text := "Quit", on command := WX.close fr] inputAction <- newIORef $ \_ -> return True rec input <- textEntry fr [ processEnter := True, on command := do str <- get input text putStrLn str set input [text := ""] cont <- ($ str) =<< readIORef inputAction when (not cont) $ WX.close fr] set fr [layout := column 5 [ fill $ minsize (sz 300 300) $ widget p, row 5 [hfill $ widget input] ]] -- , widget quit] ]] act <- newIORef $ \dc rct -> circle dc (Point 40 25) 25 [] acts <- newIORef [] layers <- newLayers 50 (return ()) -- (writeIORef act (\dc rect -> dcClear dc) >> repaint p) (return ()) (return ()) -- (writeIORef act (\dc rect -> dcClear dc) >> repaint p) -- (return ()) Size x y <- get p size print x print y sz <- newIORef (fromIntegral x, fromIntegral y) let f = Field{ fFrame = fr, fPanel = p, fAction = act, fActions = acts, fCoordinates = CoordCenter, fPenColor = (0, 0, 0), fSize = sz, fLayers = layers, fInputtext = inputAction } set p [ on paint := \dc rct -> do act <- readIORef $ fAction f acts <- readIORef $ fActions f mapM_ (($ rct) . ($ dc)) acts act dc rct, on resize := do Size x y <- get p size writeIORef sz (fromIntegral x, fromIntegral y) ] return f data InputType = XInput | End | Timer waitInput :: Field -> IO (Chan ()) waitInput f = newChan closeField :: Field -> IO () closeField = WX.close . fFrame waitField :: Field -> IO () waitField = const $ return () topleft, center :: Field -> IO () topleft = const $ return () center = const $ return () coordinates :: Field -> IO Coordinates coordinates = return . fCoordinates fieldSize :: Field -> IO (Double, Double) fieldSize = const $ return (0, 0) -------------------------------------------------------------------------------- forkField :: Field -> IO () -> IO ThreadId forkField f act = do tid <- forkIO act return tid flushField :: Field -> Bool -> IO a -> IO a flushField f real act = act fieldColor :: Field -> Layer -> Color -> IO () fieldColor f l clr = return () -------------------------------------------------------------------------------- addLayer = makeLayer . fLayers drawLayer f l drw = addDraw l (drw, drw) drawLine :: Field -> Layer -> Double -> Color -> Position -> Position -> IO () drawLine f l w c p q = do atomicModifyIORef_ (fActions f) $ (act :) repaint $ fPanel f where act = \dc rect -> do set dc [penColor := colorToWX c, penWidth := round w] p' <- positionToPoint f p q' <- positionToPoint f q line dc p' q' [] getPenColor :: Field -> WX.Color getPenColor Field{fPenColor = (r, g, b)} = rgb r g b colorToWX :: Color -> WX.Color colorToWX (RGB{colorRed = r, colorGreen = g, colorBlue = b}) = rgb r g b {- addDraw l (do atomicModifyIORef_ (fAction f) $ \f dc rect -> do f dc rect line dc (positionToPoint p) (positionToPoint q) [] repaint $ fPanel f, do atomicModifyIORef_ (fAction f) $ \f dc rect -> do f dc rect line dc (positionToPoint p) (positionToPoint q) [] repaint $ fPanel f) -} positionToPoint :: Field -> Position -> IO Point positionToPoint f (Center x y) = do (sx, sy) <- readIORef $ fSize f return $ Point (round $ x + sx / 2) (round $ - y + sy / 2) writeString :: Field -> Layer -> Font -> Double -> Color -> Position -> String -> IO () writeString f l fname size clr pos str = return () drawImage :: Field -> Layer -> FilePath -> Position -> Double -> Double -> IO () drawImage f l fp pos w h = return () fillRectangle :: Field -> Layer -> Position -> Double -> Double -> Color -> IO () fillRectangle f l p w h clr = return () fillPolygon :: Field -> Layer -> [Position] -> Color -> Color -> Double -> IO () fillPolygon f l ps clr lc lw = do atomicModifyIORef_ (fActions f) $ (act :) repaint $ fPanel f where act = \dc rect -> do set dc [brushColor := colorToWX clr, penColor := colorToWX lc, penWidth := round lw] sh' <- mapM (positionToPoint f) ps polygon dc sh' [] -------------------------------------------------------------------------------- addCharacter = makeCharacter . fLayers drawCharacter :: Field -> Character -> Color -> Color -> [Position] -> Double -> IO () drawCharacter f ch fc c ps lw = do writeIORef (fAction f) $ \dc rect -> do set dc [brushColor := colorToWX fc, penColor := colorToWX c, penWidth := round lw] sh' <- mapM (positionToPoint f) ps polygon dc sh' [] repaint $ fPanel f drawCharacterAndLine :: Field -> Character -> Color -> Color -> [Position] -> Double -> Position -> Position -> IO () drawCharacterAndLine f ch fclr clr sh lw p q = do -- putStrLn $ "drawCharacterAndLine" ++ show p ++ " : " ++ show q writeIORef (fAction f) $ \dc rect -> do set dc [brushColor := colorToWX fclr, penColor := colorToWX clr, penWidth := round lw] p' <- positionToPoint f p q' <- positionToPoint f q line dc p' q' [] sh' <- mapM (positionToPoint f) sh polygon dc sh' [] repaint $ fPanel f {- atomicModifyIORef_ (fAction f) $ \f dc rect -> do f dc rect line dc (positionToPoint p) (positionToPoint q) [] -} repaint $ fPanel f clearCharacter :: Character -> IO () clearCharacter ch = character ch $ return () -------------------------------------------------------------------------------- oninputtext :: Field -> (String -> IO Bool) -> IO () oninputtext = writeIORef . fInputtext onclick, onrelease :: Field -> (Int -> Double -> Double -> IO Bool) -> IO () onclick _ _ = return () onrelease _ _ = return () ondrag :: Field -> (Int -> Double -> Double -> IO ()) -> IO () ondrag _ _ = return () onmotion :: Field -> (Double -> Double -> IO ()) -> IO () onmotion _ _ = return () onkeypress :: Field -> (Char -> IO Bool) -> IO () onkeypress _ _ = return () ontimer :: Field -> Int -> IO Bool -> IO () ontimer f t fun = return ()
YoshikuniJujo/wxturtle
src/Graphics/UI/WX/Turtle/Field.hs
bsd-3-clause
8,287
158
18
1,634
3,272
1,714
1,558
218
1
module Style.Color where import Data.Word import Style.Types import qualified Graphics.UI.SDL as SDL rgb :: Word8 -> Word8 -> Word8 -> PropVal rgb r g b = Color $ SDL.Color r g b 0xff -- http://www.w3.org/TR/CSS2/syndata.html#value-def-color maroon = rgb 0x80 0x00 0x00 red = rgb 0xff 0x00 0x00 orange = rgb 0xff 0xa5 0x00 yellow = rgb 0xff 0xff 0x00 olive = rgb 0x80 0x80 0x00 purple = rgb 0x80 0x00 0x80 fuchsia = rgb 0xff 0x00 0xff white = rgb 0xff 0xff 0xff lime = rgb 0x00 0xff 0x00 green = rgb 0x00 0x80 0x00 navy = rgb 0x00 0x00 0x80 blue = rgb 0x00 0x00 0xff aqua = rgb 0x00 0xff 0xff teal = rgb 0x00 0x80 0x80 black = rgb 0x00 0x00 0x00 silver = rgb 0xc0 0xc0 0xc0 gray = rgb 0x80 0x80 0x80 transparent = Color $ SDL.Color 0x00 0x00 0x00 0x00
forestbelton/orb
src/Style/Color.hs
bsd-3-clause
791
0
7
185
294
152
142
24
1
{-# LANGUAGE FlexibleInstances #-} import qualified Data.Judy as J import qualified Data.Map as Map import Data.StateRef import Control.Monad instance Show (IO (J.JudyL Int)) where show a = "JudyMap -> J.JudyL Int: representation repressed" data SExp = SExp { sexp_type :: Int , sexp_name :: String , dummy_refs :: [Int] } deriving (Eq, Show) data AstGraph = AstGraph { ast_table :: J.JudyL Int , ast_map :: Ref IO (Map.Map Int SExp) } deriving Show data HNil = HNil instance Show (Ref IO (Map.Map Int SExp)) where show a = "IntMap -> Ref IO (Map.Map Int SExp): representation repressed" -- newGraph :: AstGraph newGraph = do jnew <- J.new :: IO (J.JudyL Int) let mnew = Map.empty :: Map.Map Int SExp mnewref <- newRef mnew let ngraph = AstGraph jnew mnewref return ngraph class SyntaxTree a where addNode :: a -> b -> Maybe Integer lookupNode :: a -> Integer -> Either Integer HNil numNodes :: a -> Integer delNode :: a -> Integer -> Maybe Bool {- instance SyntaxTree AstGraph where addNode ag b = do -} {- main = do g <- getStdGen rs <- randoms g j <- J.new :: IO (J.JudyL Int) forM_ (take 1000000 rs) $ \n -> J.insert n 1 j v <- J.findMax j case v of Nothing -> print "Done." Just (k,_) -> print k -}
rosenbergdm/language-r
src/Language/R/AST1.hs
bsd-3-clause
1,320
20
11
338
369
177
192
30
1
{-# language CPP #-} -- | = Name -- -- XR_KHR_loader_init_android - instance extension -- -- = Specification -- -- See -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_KHR_loader_init_android XR_KHR_loader_init_android> -- in the main specification for complete information. -- -- = Registered Extension Number -- -- 90 -- -- = Revision -- -- 1 -- -- = Extension and Version Dependencies -- -- - Requires OpenXR 1.0 -- -- - Requires @XR_KHR_loader_init@ -- -- = See Also -- -- 'LoaderInitInfoAndroidKHR' -- -- = Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_KHR_loader_init_android OpenXR Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module OpenXR.Extensions.XR_KHR_loader_init_android ( LoaderInitInfoAndroidKHR(..) , KHR_loader_init_android_SPEC_VERSION , pattern KHR_loader_init_android_SPEC_VERSION , KHR_LOADER_INIT_ANDROID_EXTENSION_NAME , pattern KHR_LOADER_INIT_ANDROID_EXTENSION_NAME , IsLoaderInitInfoKHR(..) , LoaderInitInfoBaseHeaderKHR(..) ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import OpenXR.CStruct (FromCStruct) import OpenXR.CStruct (FromCStruct(..)) import OpenXR.CStruct (ToCStruct) import OpenXR.CStruct (ToCStruct(..)) import OpenXR.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Foreign.Ptr (Ptr) import Data.Kind (Type) import OpenXR.Extensions.XR_KHR_loader_init (IsLoaderInitInfoKHR(..)) import OpenXR.Extensions.XR_KHR_loader_init (LoaderInitInfoBaseHeaderKHR(..)) import OpenXR.Core10.Enums.StructureType (StructureType) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_LOADER_INIT_INFO_ANDROID_KHR)) import OpenXR.Extensions.XR_KHR_loader_init (IsLoaderInitInfoKHR(..)) import OpenXR.Extensions.XR_KHR_loader_init (LoaderInitInfoBaseHeaderKHR(..)) -- | XrLoaderInitInfoAndroidKHR - Initializes OpenXR loader on Android -- -- == Valid Usage (Implicit) -- -- - #VUID-XrLoaderInitInfoAndroidKHR-extension-notenabled# The -- @XR_KHR_loader_init_android@ extension /must/ be enabled prior to -- using 'LoaderInitInfoAndroidKHR' -- -- - #VUID-XrLoaderInitInfoAndroidKHR-type-type# @type@ /must/ be -- 'OpenXR.Core10.Enums.StructureType.TYPE_LOADER_INIT_INFO_ANDROID_KHR' -- -- - #VUID-XrLoaderInitInfoAndroidKHR-next-next# @next@ /must/ be @NULL@ -- or a valid pointer to the -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrLoaderInitInfoAndroidKHR-applicationVM-parameter# -- @applicationVM@ /must/ be a pointer value -- -- - #VUID-XrLoaderInitInfoAndroidKHR-applicationContext-parameter# -- @applicationContext@ /must/ be a pointer value -- -- = See Also -- -- 'OpenXR.Core10.Enums.StructureType.StructureType', -- 'OpenXR.Extensions.XR_KHR_loader_init.initializeLoaderKHR' data LoaderInitInfoAndroidKHR = LoaderInitInfoAndroidKHR { -- | @applicationVM@ is a pointer to the JNI’s opaque @JavaVM@ structure, -- cast to a void pointer. applicationVM :: Ptr () , -- | @applicationContext@ is a JNI reference to an @android.content.Context@ -- associated with the application, cast to a void pointer. applicationContext :: Ptr () } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (LoaderInitInfoAndroidKHR) #endif deriving instance Show LoaderInitInfoAndroidKHR instance IsLoaderInitInfoKHR LoaderInitInfoAndroidKHR where toLoaderInitInfoBaseHeaderKHR LoaderInitInfoAndroidKHR{} = LoaderInitInfoBaseHeaderKHR{type' = TYPE_LOADER_INIT_INFO_ANDROID_KHR} instance ToCStruct LoaderInitInfoAndroidKHR where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p LoaderInitInfoAndroidKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_LOADER_INIT_INFO_ANDROID_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr (Ptr ()))) (applicationVM) poke ((p `plusPtr` 24 :: Ptr (Ptr ()))) (applicationContext) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_LOADER_INIT_INFO_ANDROID_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr (Ptr ()))) (zero) poke ((p `plusPtr` 24 :: Ptr (Ptr ()))) (zero) f instance FromCStruct LoaderInitInfoAndroidKHR where peekCStruct p = do applicationVM <- peek @(Ptr ()) ((p `plusPtr` 16 :: Ptr (Ptr ()))) applicationContext <- peek @(Ptr ()) ((p `plusPtr` 24 :: Ptr (Ptr ()))) pure $ LoaderInitInfoAndroidKHR applicationVM applicationContext instance Storable LoaderInitInfoAndroidKHR where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero LoaderInitInfoAndroidKHR where zero = LoaderInitInfoAndroidKHR zero zero type KHR_loader_init_android_SPEC_VERSION = 1 -- No documentation found for TopLevel "XR_KHR_loader_init_android_SPEC_VERSION" pattern KHR_loader_init_android_SPEC_VERSION :: forall a . Integral a => a pattern KHR_loader_init_android_SPEC_VERSION = 1 type KHR_LOADER_INIT_ANDROID_EXTENSION_NAME = "XR_KHR_loader_init_android" -- No documentation found for TopLevel "XR_KHR_LOADER_INIT_ANDROID_EXTENSION_NAME" pattern KHR_LOADER_INIT_ANDROID_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_LOADER_INIT_ANDROID_EXTENSION_NAME = "XR_KHR_loader_init_android"
expipiplus1/vulkan
openxr/src/OpenXR/Extensions/XR_KHR_loader_init_android.hs
bsd-3-clause
6,272
0
15
1,164
1,123
662
461
-1
-1
module Network.Orchid.FormatRegister ( wikiFormats , defaultFormat ) where import Network.Orchid.Core.Format (WikiFormat) import Network.Orchid.Format.Html (fHtml) import Network.Orchid.Format.Xml (fXml) import Network.Orchid.Format.Haskell (fHaskell) import Network.Orchid.Format.History (fHistory) import Network.Orchid.Format.Latex (fLatex) import Network.Orchid.Format.Pdf (fPdf) import Network.Orchid.Format.Plain (fPlain) wikiFormats :: [WikiFormat] wikiFormats = [ fPdf , fXml , fHtml , fPlain , fLatex , fHaskell , fHistory ] defaultFormat :: WikiFormat defaultFormat = fPlain
sebastiaanvisser/orchid
src/Network/Orchid/FormatRegister.hs
bsd-3-clause
616
0
5
89
155
102
53
22
1
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module Main where import Control.Exception (catch) import qualified Data.Text.IO as T import System.Environment import System.IO import Imp.Parser import Imp.Env import Imp.Prim import Imp.Eval main :: IO () main = do args <- getArgs case args of ["repl"] -> repl ["help"] -> help [filepath] -> readAndRun filepath _ -> help help :: IO () help = putStr $ unlines [ "Usage: imp [COMMAND or FILEPATH]" , "" , "Commands:" , " help show this help text" , " repl start REPL" ] repl :: IO () repl = do env <- initialEnv loop env where loop env = do putStr "imp> " hFlush stdout code <- T.getLine case parseCode code of Left err -> print err >> loop env Right prog -> do catch (run env prog >> return ()) $ \e -> do putStrLn $ show (e :: ImpError) loop env readAndRun :: FilePath -> IO () readAndRun filepath = do code <- T.readFile filepath putStrLn "======== code ========" T.putStr code putStrLn "======== end =========" case parseCode code of Left err -> print err Right prog -> do putStrLn "=== finish parsing ===" putStrLn $ show prog putStrLn "======== end =========" env <- initialEnv run env prog return ()
amutake/imp
src/Main.hs
bsd-3-clause
1,467
0
20
516
437
209
228
54
4
module AST.Module ( Module(..), Header(..), SourceTag(..) , UserImport, ImportMethod(..) , DetailedListing(..) ) where import qualified AST.Declaration as Declaration import qualified AST.Variable as Var import qualified Cheapskate.Types as Markdown import Data.Map.Strict (Map) import qualified Reporting.Annotation as A import AST.V0_16 -- MODULES data Module = Module { initialComments :: Comments , header :: Header , docs :: A.Located (Maybe Markdown.Blocks) , imports :: PreCommented (Map [UppercaseIdentifier] (Comments, ImportMethod)) , body :: [Declaration.Decl] } deriving (Eq, Show) instance A.Strippable Module where stripRegion m = Module { initialComments = initialComments m , header = Header { srcTag = srcTag $ header m , name = name $ header m , moduleSettings = moduleSettings $ header m , exports = exports $ header m } , docs = A.stripRegion $ docs m , imports = imports m , body = map A.stripRegion $ body m } -- HEADERS data SourceTag = Normal | Effect Comments | Port Comments deriving (Eq, Show) {-| Basic info needed to identify modules and determine dependencies. -} data Header = Header { srcTag :: SourceTag , name :: Commented [UppercaseIdentifier] , moduleSettings :: Maybe (KeywordCommented SourceSettings) , exports :: KeywordCommented (Var.Listing DetailedListing) } deriving (Eq, Show) data DetailedListing = DetailedListing { values :: Var.CommentedMap LowercaseIdentifier () , operators :: Var.CommentedMap SymbolIdentifier () , types :: Var.CommentedMap UppercaseIdentifier (Comments, Var.Listing (Var.CommentedMap UppercaseIdentifier ())) } deriving (Eq, Show) type SourceSettings = [(Commented LowercaseIdentifier, Commented UppercaseIdentifier)] -- IMPORTs type UserImport = (PreCommented [UppercaseIdentifier], ImportMethod) data ImportMethod = ImportMethod { alias :: Maybe (Comments, PreCommented UppercaseIdentifier) , exposedVars :: (Comments, PreCommented (Var.Listing DetailedListing)) } deriving (Eq, Show)
nukisman/elm-format-short
parser/src/AST/Module.hs
bsd-3-clause
2,182
0
14
489
601
349
252
54
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Graphics.Blank.Generated where import qualified Data.Text as ST import Data.Text.Lazy (fromStrict) import Graphics.Blank.Canvas import Graphics.Blank.JavaScript import Graphics.Blank.Types import Graphics.Blank.Types.Font import Graphics.Blank.Instr import Prelude.Compat import qualified Network.JavaScript as JS -- import TextShow (TextShow(..), FromTextShow(..), singleton) import Graphics.Blank.Types.Cursor(CanvasCursor, jsbCanvasCursor) {- instance InstrShow a => InstrShow (Prim a) where showiPrec _ = showi showi (PseudoProcedure f _) = showi f -- showi (Command c _) = showi c -- showi (MethodAudio a _) = showi a showi (Query q _) = showi q -} {- instance InstrShow MethodAudio where showiPrec _ = showi showi (PlayAudio audio) = jsAudio audio <> ".play()" showi (PauseAudio audio) = jsAudio audio <> ".pause()" showi (SetCurrentTimeAudio (audio, time)) = jsAudio audio <> ".currentTime = " <> jsDouble time <> singleton ';' showi (SetLoopAudio (audio, loop)) = jsAudio audio <> ".loop = " <> jsBool loop <> singleton ';' showi (SetMutedAudio (audio, mute)) = jsAudio audio <> ".muted = " <> jsBool mute <> singleton ';' showi (SetPlaybackRateAudio (audio, rate)) = jsAudio audio <> ".playbackRate = " <> jsDouble rate <> singleton ';' showi (SetVolumeAudio (audio, vol)) = jsAudio audio <> ".volume = " <> jsDouble vol <> singleton ';' -} -- showi (CurrentTimeAudio audio) = jsAudio audio <> ".currentTime" -- DSL -- | @'arc'(x, y, r, sAngle, eAngle, cc)@ creates a circular arc, where -- -- * @x@ is the x-coordinate of the center of the circle -- -- * @y@ is the y-coordinate of the center of the circle -- -- * @r@ is the radius of the circle on which the arc is drawn -- -- * @sAngle@ is the starting angle (where @0@ at the 3 o'clock position of the circle) -- -- * @eAngle@ is the ending angle -- -- * @cc@ is the arc direction, where @True@ indicates counterclockwise and -- @False@ indicates clockwise. arc :: (Double, Double, Double, Radians, Radians, Bool) -> Canvas () arc (a1,a2,a3,a4,a5,a6) = primitiveMethod "arc" [showJSB a1, showJSB a2, showJSB a3, showJSB a4, showJSB a5, showJSB a6] -- | @'arcTo'(x1, y1, x2, y2, r)@ creates an arc between two tangents, -- specified by two control points and a radius. -- -- * @x1@ is the x-coordinate of the first control point -- -- * @y1@ is the y-coordinate of the first control point -- -- * @x2@ is the x-coordinate of the second control point -- -- * @y2@ is the y-coordinate of the second control point -- -- * @r@ is the arc's radius arcTo :: (Double, Double, Double, Double, Double) -> Canvas () arcTo (a1,a2,a3,a4,a5) = primitiveMethod "arcTo" [ showJSB a1, showJSB a2, showJSB a3, showJSB a4, showJSB a5] -- | Begins drawing a new path. This will empty the current list of subpaths. -- -- ==== __Example__ -- -- @ -- 'beginPath'() -- 'moveTo'(20, 20) -- 'lineTo'(200, 20) -- 'stroke'() -- @ beginPath :: () -> Canvas () beginPath () = primitiveMethod "beginPath" [] -- | @'bezierCurveTo'(cp1x, cp1y, cp2x, cp2y x, y)@ adds a cubic Bézier curve to the path -- (whereas 'quadraticCurveTo' adds a quadratic Bézier curve). -- -- * @cp1x@ is the x-coordinate of the first control point -- -- * @cp1y@ is the y-coordinate of the first control point -- -- * @cp2x@ is the x-coordinate of the second control point -- -- * @cp2y@ is the y-coordinate of the second control point -- -- * @x@ is the x-coordinate of the end point -- -- * @y@ is the y-coordinate of the end point bezierCurveTo :: (Double, Double, Double, Double, Double, Double) -> Canvas () bezierCurveTo (a1,a2,a3,a4,a5,a6) = primitiveMethod "bezierCurveTo" [ showJSB a1, showJSB a2, showJSB a3, showJSB a4, showJSB a5, showJSB a6] -- | @'clearRect'(x, y, w, h)@ clears all pixels within the rectangle with upper-left -- corner @(x, y)@, width @w@, and height @h@ (i.e., sets the pixels to transparent black). -- -- ==== __Example__ -- -- @ -- 'fillStyle' \"red\" -- 'fillRect'(0, 0, 300, 150) -- 'clearRect'(20, 20, 100, 50) -- @ clearRect :: (Double, Double, Double, Double) -> Canvas () clearRect (a1,a2,a3,a4) = primitiveMethod "clearRect" [ showJSB a1, showJSB a2, showJSB a3, showJSB a4 ] -- | Turns the path currently being built into the current clipping path. -- Anything drawn after 'clip' is called will only be visible if inside the new -- clipping path. -- -- ==== __Example__ -- -- @ -- 'rect'(50, 20, 200, 120) -- 'stroke'() -- 'clip'() -- 'fillStyle' \"red\" -- 'fillRect'(0, 0, 150, 100) -- @ clip :: () -> Canvas () clip () = primitiveMethod "clip" [] -- | Creates a path from the current point back to the start, to close it. -- -- ==== __Example__ -- -- @ -- 'beginPath'() -- 'moveTo'(20, 20) -- 'lineTo'(200, 20) -- 'lineTo'(120, 120) -- 'closePath'() -- 'stroke'() -- @ closePath :: () -> Canvas () closePath () = primitiveMethod "closePath" [] -- | drawImage' takes 2, 4, or 8 'Double' arguments. See 'drawImageAt', 'drawImageSize', and 'drawImageCrop' for variants with exact numbers of arguments. drawImage :: Image image => (image,[Double]) -> Canvas () drawImage (img, args) = primitiveMethod "drawImage" (jsbImage img : map showJSB args) -- | Fills the current path with the current 'fillStyle'. -- -- ==== __Example__ -- -- @ -- 'rect'(10, 10, 100, 100) -- 'fill'() -- @ fill :: () -> Canvas () fill () = primitiveMethod "fill" [] -- | @'fillRect'(x, y, w, h)@ draws a filled rectangle with upper-left -- corner @(x, y)@, width @w@, and height @h@ using the current 'fillStyle'. -- -- ==== __Example__ -- -- @ -- 'fillStyle' \"red\" -- 'fillRect'(0, 0, 300, 150) -- @ fillRect :: (Double, Double, Double, Double) -> Canvas () fillRect (a1, a2, a3, a4) = primitiveMethod "fillRect" [ showJSB a1, showJSB a2, showJSB a3, showJSB a4 ] -- | Sets the color, gradient, or pattern used to fill a drawing ('black' by default). -- -- ==== __Examples__ -- -- @ -- 'fillStyle' 'red' -- -- grd <- 'createLinearGradient'(0, 0, 10, 10) -- 'fillStyle' grd -- -- img <- 'newImage' \"/myImage.jpg\" -- pat <- 'createPattern'(img, 'Repeat') -- 'fillStyle' pat -- @ fillStyle :: Style style => style -> Canvas () fillStyle st = primitiveAttribute "fillStyle" [jsbStyle st] -- | @'fillText'(t, x, y)@ fills the text @t@ at position @(x, y)@ -- using the current 'fillStyle'. -- -- ==== __Example__ -- -- @ -- 'font' \"48px serif\" -- 'fillText'(\"Hello, World!\", 50, 100) -- @ fillText :: (ST.Text, Double, Double) -> Canvas () fillText (t, a, b) = primitiveMethod "fillText" [showJSB t, showJSB a, showJSB b] -- | Sets the text context's font properties. -- -- ==== __Examples__ -- -- @ -- 'font' ('defFont' "Gill Sans Extrabold") { 'fontSize' = 40 # 'pt' } -- 'font' ('defFont' 'sansSerif') { 'fontSize' = 80 # 'percent' } -- 'font' ('defFont' 'serif') { -- 'fontWeight' = 'bold' -- , 'fontStyle' = 'italic' -- , 'fontSize' = 'large' -- } -- @ font :: CanvasFont canvasFont => canvasFont -> Canvas () font f = primitiveAttribute "font" [jsbCanvasFont f] -- | Set the alpha value that is applied to shapes before they are drawn onto the canvas. globalAlpha :: Alpha -> Canvas () globalAlpha a = primitiveAttribute "globalAlpha" [showJSB a] -- | Sets how new shapes should be drawn over existing shapes. -- -- ==== __Examples__ -- -- @ -- 'globalCompositeOperation' \"source-over\" -- 'globalCompositeOperation' \"destination-atop\" -- @ globalCompositeOperation :: ST.Text -> Canvas () globalCompositeOperation t = primitiveAttribute "globalCompositeOperation" [showJSB t] -- | Sets the 'LineEndCap' to use when drawing the endpoints of lines. lineCap :: LineEndCap -> Canvas () lineCap lec = primitiveAttribute "lineCap" [showJSB lec] -- | Sets the 'LineJoinCorner' to use when drawing two connected lines. lineJoin :: LineJoinCorner -> Canvas () lineJoin ljc = primitiveAttribute "lineJoin" [showJSB ljc] -- | @'lineTo'(x, y)@ connects the last point in the subpath to the given @(x, y)@ -- coordinates (without actually drawing it). -- -- ==== __Example__ -- -- @ -- 'beginPath'() -- 'moveTo'(50, 50) -- 'lineTo'(200, 50) -- 'stroke'() -- @ lineTo :: (Double, Double) -> Canvas () lineTo (a1,a2) = primitiveMethod "lineTo" [showJSB a1, showJSB a2] -- | Sets the thickness of lines in pixels (@1.0@ by default). lineWidth :: Double -> Canvas () lineWidth a = primitiveAttribute "lineWidth" [showJSB a] -- | Sets the maximum miter length (@10.0@ by default) to use when the -- 'lineWidth' is 'miter'. miterLimit :: Double -> Canvas () miterLimit a = primitiveAttribute "miterLimit" [showJSB a] -- | @'moveTo'(x, y)@ moves the starting point of a new subpath to the given @(x, y)@ coordinates. -- -- ==== __Example__ -- -- @ -- 'beginPath'() -- 'moveTo'(50, 50) -- 'lineTo'(200, 50) -- 'stroke'() -- @ moveTo :: (Double, Double) -> Canvas () moveTo (a1,a2) = primitiveMethod "moveTo" [showJSB a1,showJSB a2] {- playAudio :: Audio audio => audio -> Canvas () playAudio = primitive . MethodAudio . PlayAudio pauseAudio :: Audio audio => audio -> Canvas () pauseAudio = primitive . MethodAudio . PauseAudio -- | Sets the current position of the audio value (in seconds). setCurrentTimeAudio :: Audio audio => (audio, Double) -> Canvas () setCurrentTimeAudio = primitive . MethodAudio . SetCurrentTimeAudio -- | Set whether the audio value is set to loop (True) or not (False) setLoopAudio :: Audio audio => (audio, Bool) -> Canvas () setLoopAudio = primitive . MethodAudio . SetLoopAudio -- | Set the audio value to muted (True) or unmuted (False) setMutedAudio :: Audio audio => (audio, Bool) -> Canvas () setMutedAudio = primitive . MethodAudio . SetMutedAudio -- | Set the playback value, as a multiplier (2.0 is twice as fast, 0.5 is half speec, -2.0 is backwards, twice as fast) setPlaybackRateAudio :: Audio audio => (audio, Double) -> Canvas () setPlaybackRateAudio = primitive . MethodAudio . SetPlaybackRateAudio -- | Adjusts the volume. Scaled from 0.0 - 1.0, any number outside of this range will result in an error setVolumeAudio :: Audio audio => (audio, Double) -> Canvas () setVolumeAudio = primitive . MethodAudio . SetVolumeAudio -} -- | 'putImageData' takes 2 or 6 'Double' arguments. See `putImageDataAt' and `putImageDataDirty' for variants with exact numbers of arguments. putImageData :: (ImageData, [Double]) -> Canvas () putImageData (a1,a2) = primitiveMethod "putImageData" (showJSB a1 : map showJSB a2) -- | @'quadraticCurveTo'(cpx, cpy, x, y)@ adds a quadratic Bézier curve to the path -- (whereas 'bezierCurveTo' adds a cubic Bézier curve). -- -- * @cpx@ is the x-coordinate of the control point -- -- * @cpy@ is the y-coordinate of the control point -- -- * @x@ is the x-coordinate of the end point -- -- * @y@ is the y-coordinate of the end point quadraticCurveTo :: (Double, Double, Double, Double) -> Canvas () quadraticCurveTo (a1,a2,a3,a4) = primitiveMethod "quadraticCurveTo" [showJSB a1, showJSB a2, showJSB a3, showJSB a4] -- | @'rect'(x, y, w, h)@ creates a rectangle with an upper-left corner at position -- @(x, y)@, width @w@, and height @h@ (where width and height are in pixels). -- -- ==== __Example__ -- -- @ -- 'rect'(10, 10, 100, 100) -- 'fill'() -- @ rect :: (Double, Double, Double, Double) -> Canvas () rect (a1,a2,a3,a4) = primitiveMethod "rect" [showJSB a1, showJSB a2, showJSB a3, showJSB a4] -- | Restores the most recently saved canvas by popping the top entry off of the -- drawing state stack. If there is no state, do nothing. restore :: () -> Canvas () restore () = primitiveMethod "restore" [] -- | Applies a rotation transformation to the canvas. When you call functions -- such as 'fillRect' after 'rotate', the drawings will be rotated clockwise by -- the angle given to 'rotate' (in radians). -- -- ==== __Example__ -- -- @ -- 'rotate' ('pi'/2) -- Rotate the canvas 90° -- 'fillRect'(0, 0, 20, 10) -- Draw a 10x20 rectangle -- @ rotate :: Radians -> Canvas () rotate r = primitiveMethod "rotate" [showJSB r] -- | Saves the entire canvas by pushing the current state onto a stack. save :: () -> Canvas () save () = primitiveMethod "save" [] -- | Applies a scaling transformation to the canvas units, where the first argument -- is the percent to scale horizontally, and the second argument is the percent to -- scale vertically. By default, one canvas unit is one pixel. -- -- ==== __Examples__ -- -- @ -- 'scale'(0.5, 0.5) -- Halve the canvas units -- 'fillRect'(0, 0, 20, 20) -- Draw a 10x10 square -- 'scale'(-1, 1) -- Flip the context horizontally -- @ scale :: (Interval, Interval) -> Canvas () scale (a1,a2) = primitiveMethod "scale" [showJSB a1, showJSB a2] -- | Resets the canvas's transformation matrix to the identity matrix, -- then calls 'transform' with the given arguments. setTransform :: (Double, Double, Double, Double, Double, Double) -> Canvas () setTransform (a1,a2,a3,a4,a5,a6) = primitiveMethod "setTransform" [showJSB a1, showJSB a2, showJSB a3, showJSB a4, showJSB a5, showJSB a6] -- | Sets the blur level for shadows (@0.0@ by default). shadowBlur :: Double -> Canvas () shadowBlur a1 = primitiveAttribute "shadowBlur" [showJSB a1] -- | Sets the color used for shadows. -- -- ==== __Examples__ -- -- @ -- 'shadowColor' 'red' -- 'shadowColor' $ 'rgb' 0 255 0 -- @ shadowColor :: CanvasColor canvasColor => canvasColor -> Canvas () shadowColor a1 = primitiveAttribute "shadowColor" [jsbCanvasColor a1] -- | Sets the horizontal distance that a shadow will be offset (@0.0@ by default). shadowOffsetX :: Double -> Canvas () shadowOffsetX a1 = primitiveAttribute "shadowOffsetX" [showJSB a1] -- | Sets the vertical distance that a shadow will be offset (@0.0@ by default). shadowOffsetY :: Double -> Canvas () shadowOffsetY a1 = primitiveAttribute "shadowOffsetY" [showJSB a1] -- | Draws the current path's strokes with the current 'strokeStyle' ('black' by default). -- -- ==== __Example__ -- -- @ -- 'rect'(10, 10, 100, 100) -- 'stroke'() -- @ stroke :: () -> Canvas () stroke () = primitiveMethod "stroke" [] -- | @'strokeRect'(x, y, w, h)@ draws a rectangle (no fill) with upper-left -- corner @(x, y)@, width @w@, and height @h@ using the current 'strokeStyle'. -- -- ==== __Example__ -- -- @ -- 'strokeStyle' \"red\" -- 'strokeRect'(0, 0, 300, 150) -- @ strokeRect :: (Double, Double, Double, Double) -> Canvas () strokeRect (a1,a2,a3,a4) = primitiveMethod "strokeRect" [showJSB a1, showJSB a2, showJSB a3, showJSB a4] -- | Sets the color, gradient, or pattern used for strokes. -- -- ==== __Examples__ -- -- @ -- 'strokeStyle' 'red' -- -- grd <- 'createLinearGradient'(0, 0, 10, 10) -- 'strokeStyle' grd -- -- img <- 'newImage' \"/myImage.jpg\" -- pat <- 'createPattern'(img, 'Repeat') -- 'strokeStyle' pat -- @ strokeStyle :: Style style => style -> Canvas () strokeStyle a1 = primitiveAttribute "strokeStyle" [jsbStyle a1] -- | @'strokeText'(t, x, y)@ draws text @t@ (with no fill) at position @(x, y)@ -- using the current 'strokeStyle'. -- -- ==== __Example__ -- -- @ -- 'font' \"48px serif\" -- 'strokeText'(\"Hello, World!\", 50, 100) -- @ strokeText :: (ST.Text, Double, Double) -> Canvas () strokeText (t, a, b) = primitiveMethod "strokeText" [showJSB t, showJSB a, showJSB b] -- | Sets the 'TextAnchorAlignment' to use when drawing text. textAlign :: TextAnchorAlignment -> Canvas () textAlign a1 = primitiveAttribute "textAlign" [showJSB a1] -- | Sets the 'TextBaselineAlignment' to use when drawing text. textBaseline :: TextBaselineAlignment -> Canvas () textBaseline a1 = primitiveAttribute "textBaseline" [showJSB a1] -- | Applies a transformation by multiplying a matrix to the canvas's -- current transformation. If @'transform'(a, b, c, d, e, f)@ is called, the matrix -- -- @ -- ( a c e ) -- ( b d f ) -- ( 0 0 1 ) -- @ -- -- is multiplied by the current transformation. The parameters are: -- -- * @a@ is the horizontal scaling -- -- * @b@ is the horizontal skewing -- -- * @c@ is the vertical skewing -- -- * @d@ is the vertical scaling -- -- * @e@ is the horizontal movement -- -- * @f@ is the vertical movement transform :: (Double, Double, Double, Double, Double, Double) -> Canvas () transform (a1,a2,a3,a4,a5,a6) = primitiveMethod "transform" [showJSB a1, showJSB a2, showJSB a3, showJSB a4, showJSB a5, showJSB a6] -- | Applies a translation transformation by remapping the origin (i.e., the (0,0) -- position) on the canvas. When you call functions such as 'fillRect' after -- 'translate', the values passed to 'translate' are added to the x- and -- y-coordinate values. -- -- ==== __Example__ -- -- @ -- 'translate'(20, 20) -- 'fillRect'(0, 0, 40, 40) -- Draw a 40x40 square, starting in position (20, 20) -- @ translate :: (Double, Double) -> Canvas () translate (a1,a2) = primitiveMethod "translate" [showJSB a1, showJSB a2] -- | Change the canvas cursor to the specified URL or keyword. -- -- ==== __Examples__ -- -- @ -- cursor $ 'url' \"image.png\" 'default_' -- cursor 'crosshair' -- @ cursor :: CanvasCursor cursor => cursor -> Canvas () cursor cur = primitiveAttribute "canvas.style.cursor" [jsbCanvasCursor cur]
ku-fpg/blank-canvas
Graphics/Blank/Generated.hs
bsd-3-clause
17,380
0
8
3,155
2,551
1,496
1,055
115
1
{-# LANGUAGE OverloadedStrings #-} module Ttlv.Parser.Binary ( encodeTtlv , decodeTtlv , padTo , padTo8 ) where import Control.Monad import Control.Applicative import qualified Crypto.Number.Serialize as CN (i2osp, i2ospOf_, lengthBytes, os2ip) import Data.Binary import Data.Binary.Get import Data.Binary.Put import qualified Data.ByteString as B import qualified Data.ByteString.Internal as BS (c2w, w2c) import qualified Data.ByteString.Lazy as L import Data.Maybe import Data.Time.Clock.POSIX import Data.Text.Encoding (decodeUtf8, encodeUtf8) import qualified Data.Text as T import Data.Int import Data.Word import Unsafe.Coerce (unsafeCoerce) import Ttlv.Data import qualified Ttlv.Enum as E import Ttlv.Tag instance Binary Ttlv where get = parseTtlv put = unparseTtlv -- | calculate remaining bytes to specified alignment padTo :: (Integral a, Num a) => a -> a -> a padTo p n = (p - (n `rem` p)) `rem` p padTo8 = padTo 8 parseTtlvStructure' :: Get [Ttlv] parseTtlvStructure' = do empty <- isEmpty if empty -- handle empty structure then return [] else do ttlv <- parseTtlv empty <- isEmpty if empty then return [ttlv] else do rest <- parseTtlvStructure' return $ ttlv : rest parseTtlvStructure :: Get TtlvData parseTtlvStructure = do ttlvs <- parseTtlvStructure' return $ TtlvStructure ttlvs parseTtlvInt :: Get TtlvData parseTtlvInt = do val <- getWord32be return $ TtlvInt $ fromIntegral val parseTtlvLongInt :: Get TtlvData parseTtlvLongInt = do val <- getWord64be return $ TtlvLongInt $ fromIntegral val -- FIXME this doesn't handle negative numbers parseTtlvBigInt :: Int -> Get TtlvData parseTtlvBigInt n = do val <- getLazyByteString $ fromIntegral n return $ TtlvBigInt $ CN.os2ip $ L.toStrict val parseTtlvEnum :: Get TtlvData parseTtlvEnum = do val <- getWord32be return $ TtlvEnum $ fromIntegral val parseTtlvBool :: Get TtlvData parseTtlvBool = do val <- getWord64be return $ TtlvBool (val == 1) parseTtlvString :: Int -> Get TtlvData parseTtlvString n = do val <- getLazyByteString $ fromIntegral n return $ TtlvString $ decodeUtf8 $ L.toStrict val parseTtlvByteString :: Int -> Get TtlvData parseTtlvByteString n = do val <- getByteString $ fromIntegral n return $ TtlvByteString val parseTtlvDateTime :: Get TtlvData parseTtlvDateTime = do val <- getWord64be return $ TtlvDateTime $ posixSecondsToUTCTime $ fromIntegral val parseTtlvInterval :: Get TtlvData parseTtlvInterval = do val <- getWord32be return $ TtlvInterval $ fromIntegral val decodeTtlvTag :: L.ByteString -> Int decodeTtlvTag x = fromIntegral (decode (0 `L.cons'` x) :: Word32) encodeTtlvTag :: Int -> L.ByteString encodeTtlvTag x = snd $ fromJust $ L.uncons $ encode (fromIntegral x :: Word32) parseTtlv :: Get Ttlv parseTtlv = do tag <- getLazyByteString 3 typ <- fromIntegral <$> getWord8 len <- getWord32be val <- getLazyByteString $ fromIntegral len let skipBytes = padTo8 $ fromIntegral len when (skipBytes /= 0 && (typ `elem` [2, 5, 7, 8, 10])) $ skip $ fromIntegral skipBytes return $ Ttlv (toTag $ decodeTtlvTag tag) (case typ of 1 -> runGet parseTtlvStructure val 2 -> runGet parseTtlvInt val 3 -> runGet parseTtlvLongInt val 4 -> runGet (parseTtlvBigInt $ fromIntegral len) val 5 -> runGet parseTtlvEnum val 6 -> runGet parseTtlvBool val 7 -> runGet (parseTtlvString $ fromIntegral len) val 8 -> runGet (parseTtlvByteString $ fromIntegral len) val 9 -> runGet parseTtlvDateTime val 10 -> runGet parseTtlvInterval val _ -> error "unknown type") -- | Retrieve the corresponding ID for TtlvData ttlvDataType :: TtlvData -> Int ttlvDataType (TtlvStructure _) = 1 ttlvDataType (TtlvInt _) = 2 ttlvDataType (TtlvLongInt _) = 3 ttlvDataType (TtlvBigInt _) = 4 ttlvDataType (TtlvEnum _) = 5 ttlvDataType (TtlvBool _) = 6 ttlvDataType (TtlvString _) = 7 ttlvDataType (TtlvByteString _) = 8 ttlvDataType (TtlvDateTime _) = 9 ttlvDataType (TtlvInterval _) = 10 ttlvDataLength :: TtlvData -> Int ttlvDataLength (TtlvStructure x) = if null x then 0 -- empty structure else sum $ map ttlvLength x ttlvDataLength (TtlvInt _) = 4 -- w/o padding ttlvDataLength (TtlvLongInt _) = 8 ttlvDataLength (TtlvBigInt x) = CN.lengthBytes x -- w/o padding ttlvDataLength (TtlvEnum _) = 4 -- w/o padding ttlvDataLength (TtlvBool _) = 8 ttlvDataLength (TtlvString x) = fromIntegral $ B.length $ encodeUtf8 $ x -- w/o padding ttlvDataLength (TtlvByteString x) = fromIntegral $ B.length x -- w/o padding ttlvDataLength (TtlvDateTime _) = 8 ttlvDataLength (TtlvInterval _) = 4 -- w/o padding ttlvLength :: Ttlv -> Int ttlvLength (Ttlv _ d) = 3 + 1 + 4 + paddedTtlvDataLength d -- put data without padding unparseTtlvData :: TtlvData -> Put unparseTtlvData (TtlvStructure x) = mapM_ unparseTtlv x unparseTtlvData (TtlvInt x) = putWord32be $ fromIntegral x unparseTtlvData (TtlvLongInt x) = putWord64be $ fromIntegral x unparseTtlvData z@(TtlvBigInt x) = putByteString $ CN.i2ospOf_ (ttlvDataLength z) x unparseTtlvData (TtlvEnum x) = putWord32be $ fromIntegral x unparseTtlvData (TtlvBool x) = if x then putWord64be 1 else putWord64be 0 unparseTtlvData (TtlvString x) = putLazyByteString $ L.fromStrict $ encodeUtf8 x unparseTtlvData (TtlvByteString x) = putByteString x unparseTtlvData (TtlvDateTime x) = putWord64be $ fromIntegral $ round $ utcTimeToPOSIXSeconds x unparseTtlvData (TtlvInterval x) = putWord32be $ fromIntegral x paddedTtlvDataLength :: TtlvData -> Int paddedTtlvDataLength (TtlvInt _) = 8 paddedTtlvDataLength (TtlvEnum _) = 8 paddedTtlvDataLength (TtlvInterval _) = 8 paddedTtlvDataLength x@(TtlvString _) = let n = ttlvDataLength x in n + padTo8 n paddedTtlvDataLength x@(TtlvByteString _) = let n = ttlvDataLength x in n + padTo8 n paddedTtlvDataLength x = ttlvDataLength x unparseTtlv :: Ttlv -> Put unparseTtlv (Ttlv t d) = do putByteString $ L.toStrict $ encodeTtlvTag $ fromTag t putWord8 $ fromIntegral $ ttlvDataType d -- this is terrible. Find a better way to do this let len = ttlvDataLength d realLength = paddedTtlvDataLength d putWord32be $ fromIntegral len unparseTtlvData d -- add padding at end replicateM_ (realLength - len) (putWord8 0) -- | Decode a Lazy ByteString into the corresponding Ttlv type decodeTtlv :: B.ByteString -> Either String Ttlv decodeTtlv = decodeTtlvLazy . L.fromStrict decodeTtlvLazy :: L.ByteString -> Either String Ttlv decodeTtlvLazy b = case runGetOrFail parseTtlv b of Right (_, _, ttlv) -> Right ttlv Left (_, _, e) -> Left e encodeTtlv :: Ttlv -> B.ByteString encodeTtlv x = L.toStrict $ runPut $ unparseTtlv x
nymacro/hs-kmip
src/Ttlv/Parser/Binary.hs
bsd-3-clause
7,289
0
16
1,814
2,171
1,102
1,069
175
11
module Lambda.Compiler.Restore where import DeepControl.Applicative import DeepControl.Monad import Lambda.Action import Lambda.Convertor import qualified Lambda.DataType.PatternMatch as PM import qualified Lambda.DataType.Type as Ty import qualified Lambda.DataType.Expr as E import Lambda.DataType import Lambda.Util import qualified Util.LISP as L -- for debug import Debug.Trace ---------------------------------------------------------------------- -- restore pattern match ---------------------------------------------------------------------- restorePM :: PM -> Lambda PM restorePM (PM.VAR name msp) = localMSPBy msp $ do genv <- getDef let freevars = fst |$> genv if name `elem` freevars then do let newvar = newVar freevars (*:) $ PM.VAR newvar msp else (*:) $ PM.VAR name msp where newVar :: [Name] -> String newVar frees = (name++) |$> semiInfinitePostfixes >- filter (\x -> not (x `elem` frees)) >- head restorePM pm = (*:) pm
ocean0yohsuke/Simply-Typed-Lambda
src/Lambda/Compiler/Restore.hs
bsd-3-clause
1,029
0
14
209
270
155
115
26
2
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI, UnliftedFFITypes, MagicHash, BangPatterns #-} module Data.JSString.Int ( decimal , hexadecimal ) where import Data.JSString import Data.Monoid import GHC.Int import GHC.Word import GHC.Exts ( ByteArray# , Int(..), Int#, Int64# , Word(..), Word#, Word64# , (<#), (<=#), isTrue# ) import GHC.Integer.GMP.Internals import Unsafe.Coerce import GHCJS.Prim decimal :: Integral a => a -> JSString decimal i = decimal' i {-# RULES "decimal/Int" decimal = decimalI :: Int -> JSString #-} {-# RULES "decimal/Int8" decimal = decimalI8 :: Int8 -> JSString #-} {-# RULES "decimal/Int16" decimal = decimalI16 :: Int16 -> JSString #-} {-# RULES "decimal/Int32" decimal = decimalI32 :: Int32 -> JSString #-} {-# RULES "decimal/Int64" decimal = decimalI64 :: Int64 -> JSString #-} {-# RULES "decimal/Word" decimal = decimalW :: Word -> JSString #-} {-# RULES "decimal/Word8" decimal = decimalW8 :: Word8 -> JSString #-} {-# RULES "decimal/Word16" decimal = decimalW16 :: Word16 -> JSString #-} {-# RULES "decimal/Word32" decimal = decimalW32 :: Word32 -> JSString #-} {-# RULES "decimal/Word64" decimal = decimalW64 :: Word64 -> JSString #-} {-# RULES "decimal/Integer" decimal = decimalInteger :: Integer -> JSString #-} {-# SPECIALIZE decimal :: Integer -> JSString #-} {-# SPECIALIZE decimal :: Int -> JSString #-} {-# SPECIALIZE decimal :: Int8 -> JSString #-} {-# SPECIALIZE decimal :: Int16 -> JSString #-} {-# SPECIALIZE decimal :: Int32 -> JSString #-} {-# SPECIALIZE decimal :: Int64 -> JSString #-} {-# SPECIALIZE decimal :: Word -> JSString #-} {-# SPECIALIZE decimal :: Word8 -> JSString #-} {-# SPECIALIZE decimal :: Word16 -> JSString #-} {-# SPECIALIZE decimal :: Word32 -> JSString #-} {-# SPECIALIZE decimal :: Word64 -> JSString #-} {-# INLINE [1] decimal #-} decimalI :: Int -> JSString decimalI (I# x) = js_decI x {-# INLINE decimalI #-} decimalI8 :: Int8 -> JSString decimalI8 (I8# x) = js_decI x {-# INLINE decimalI8 #-} decimalI16 :: Int16 -> JSString decimalI16 (I16# x) = js_decI x {-# INLINE decimalI16 #-} decimalI32 :: Int32 -> JSString decimalI32 (I32# x) = js_decI x {-# INLINE decimalI32 #-} decimalI64 :: Int64 -> JSString decimalI64 (I64# x) = js_decI64 x {-# INLINE decimalI64 #-} decimalW8 :: Word8 -> JSString decimalW8 (W8# x) = js_decW x {-# INLINE decimalW8 #-} decimalW16 :: Word16 -> JSString decimalW16 (W16# x) = js_decW x {-# INLINE decimalW16 #-} decimalW32 :: Word32 -> JSString decimalW32 (W32# x) = js_decW32 x {-# INLINE decimalW32 #-} decimalW64 :: Word64 -> JSString decimalW64 (W64# x) = js_decW64 x {-# INLINE decimalW64 #-} decimalW :: Word -> JSString decimalW (W# x) = js_decW32 x {-# INLINE decimalW #-} -- hack warning, we should really expose J# somehow data MyI = MyS Int# | MyJ Int# ByteArray# decimalInteger :: Integer -> JSString decimalInteger (S# x) = js_decI x decimalInteger i = let !(MyJ _ x) = unsafeCoerce i -- hack for unexposed J# in js_decInteger x {-# INLINE decimalInteger #-} decimal' :: Integral a => a ->JSString decimal' i = decimalInteger (toInteger i) {-# NOINLINE decimal' #-} {- | i < 0 = if i <= -10 then let (q, r) = i `quotRem` (-10) !(I# rr) = fromIntegral r in js_minusDigit (positive q) rr else js_minus (positive (negate i)) | otherwise = positive i positive :: (Integral a) => a -> JSString positive i | toInteger i < 1000000000 = let !(I# x) = fromIntegral i in js_decI x | otherwise = let (q, r) = i `quotRem` 1000000000 !(I# x) = fromIntegral r in positive q <> js_decIPadded9 x -} hexadecimal :: Integral a => a -> JSString hexadecimal i = hexadecimal' i {-# RULES "hexadecimal/Int" hexadecimal = hexI :: Int -> JSString #-} {-# RULES "hexadecimal/Int8" hexadecimal = hexI8 :: Int8 -> JSString #-} {-# RULES "hexadecimal/Int16" hexadecimal = hexI16 :: Int16 -> JSString #-} {-# RULES "hexadecimal/Int32" hexadecimal = hexI32 :: Int32 -> JSString #-} {-# RULES "hexadecimal/Int64" hexadecimal = hexI64 :: Int64 -> JSString #-} {-# RULES "hexadecimal/Word" hexadecimal = hexW :: Word -> JSString #-} {-# RULES "hexadecimal/Word8" hexadecimal = hexW8 :: Word8 -> JSString #-} {-# RULES "hexadecimal/Word16" hexadecimal = hexW16 :: Word16 -> JSString #-} {-# RULES "hexadecimal/Word32" hexadecimal = hexW32 :: Word32 -> JSString #-} {-# RULES "hexadecimal/Word64" hexadecimal = hexW64 :: Word64 -> JSString #-} {-# RULES "hexadecimal/Integer" hexadecimal = hexInteger :: Integer -> JSString #-} {-# SPECIALIZE hexadecimal :: Integer -> JSString #-} {-# SPECIALIZE hexadecimal :: Int -> JSString #-} {-# SPECIALIZE hexadecimal :: Int8 -> JSString #-} {-# SPECIALIZE hexadecimal :: Int16 -> JSString #-} {-# SPECIALIZE hexadecimal :: Int32 -> JSString #-} {-# SPECIALIZE hexadecimal :: Int64 -> JSString #-} {-# SPECIALIZE hexadecimal :: Word -> JSString #-} {-# SPECIALIZE hexadecimal :: Word8 -> JSString #-} {-# SPECIALIZE hexadecimal :: Word16 -> JSString #-} {-# SPECIALIZE hexadecimal :: Word32 -> JSString #-} {-# SPECIALIZE hexadecimal :: Word64 -> JSString #-} {-# INLINE [1] hexadecimal #-} hexadecimal' :: Integral a => a -> JSString hexadecimal' i | i < 0 = error hexErrMsg | otherwise = hexInteger (toInteger i) {-# NOINLINE hexadecimal' #-} hexInteger :: Integer -> JSString hexInteger (S# x) = if isTrue# (x <# 0#) then error hexErrMsg else js_hexI x hexInteger i | i < 0 = error hexErrMsg | otherwise = let !(MyJ _ x) = unsafeCoerce i -- hack for non-exposed J# in js_hexInteger x {-# INLINE hexInteger #-} hexI :: Int -> JSString hexI (I# x) = if isTrue# (x <# 0#) then error hexErrMsg else js_hexI x {-# INLINE hexI #-} hexI8 :: Int8 -> JSString hexI8 (I8# x) = if isTrue# (x <# 0#) then error hexErrMsg else js_hexI x {-# INLINE hexI8 #-} hexI16 :: Int16 -> JSString hexI16 (I16# x) = if isTrue# (x <# 0#) then error hexErrMsg else js_hexI x {-# INLINE hexI16 #-} hexI32 :: Int32 -> JSString hexI32 (I32# x) = if isTrue# (x <# 0#) then error hexErrMsg else js_hexI x {-# INLINE hexI32 #-} hexI64 :: Int64 -> JSString hexI64 i@(I64# x) = if i < 0 then error hexErrMsg else js_hexI64 x {-# INLINE hexI64 #-} hexW :: Word -> JSString hexW (W# x) = js_hexW32 x {-# INLINE hexW #-} hexW8 :: Word8 -> JSString hexW8 (W8# x) = js_hexW x {-# INLINE hexW8 #-} hexW16 :: Word16 -> JSString hexW16 (W16# x) = js_hexW x {-# INLINE hexW16 #-} hexW32 :: Word32 -> JSString hexW32 (W32# x) = js_hexW32 x {-# INLINE hexW32 #-} hexW64 :: Word64 -> JSString hexW64 (W64# x) = js_hexW64 x {-# INLINE hexW64 #-} hexErrMsg :: String hexErrMsg = "Data.JSString.Int.hexadecimal: applied to negative number" -- ---------------------------------------------------------------------------- foreign import javascript unsafe "''+$1" js_decI :: Int# -> JSString foreign import javascript unsafe "h$jsstringDecI64" js_decI64 :: Int64# -> JSString foreign import javascript unsafe "''+$1" js_decW :: Word# -> JSString foreign import javascript unsafe "''+(($1>=0)?$1:($1+4294967296))" js_decW32 :: Word# -> JSString foreign import javascript unsafe "h$jsstringDecW64($1_1, $1_2)" js_decW64 :: Word64# -> JSString foreign import javascript unsafe "$1.toString()" js_decInteger :: ByteArray# -> JSString -- these are expected to be only applied to nonnegative integers foreign import javascript unsafe "$1.toString(16)" js_hexI :: Int# -> JSString foreign import javascript unsafe "h$jsstringHexI64" js_hexI64 :: Int64# -> JSString foreign import javascript unsafe "$1.toString(16)" js_hexW :: Word# -> JSString foreign import javascript unsafe "(($1>=0)?$1:($1+4294967296)).toString(16)" js_hexW32 :: Word# -> JSString foreign import javascript unsafe "h$jsstringHexW64($1_1, $1_2)" js_hexW64 :: Word64# -> JSString foreign import javascript unsafe "$1.toString(16)" js_hexInteger :: ByteArray# -> JSString -- hack warning! foreign import javascript unsafe "'-'+$1+(-$2)" js_minusDigit :: JSString -> Int# -> JSString foreign import javascript unsafe "'-'+$1" js_minus :: JSString -> JSString -- foreign import javascript unsafe "h$jsstringDecIPadded9" js_decIPadded9 :: Int# -> JSString foreign import javascript unsafe "h$jsstringHexIPadded8" js_hexIPadded8 :: Int# -> JSString
NewByteOrder/ghcjs-base
Data/JSString/Int.hs
mit
8,851
35
13
2,025
1,457
780
677
194
2
{-- snippet Functor --} {-# LANGUAGE FlexibleInstances #-} instance Functor (Either Int) where fmap _ (Left n) = Left n fmap f (Right r) = Right (f r) {-- /snippet Functor --}
binesiyu/ifl
examples/ch10/EitherIntFlexible.hs
mit
186
0
8
42
62
31
31
4
0
{-# LANGUAGE OverloadedStrings #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Route53Domains.Types -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.Route53Domains.Types ( -- * Service Configuration route53Domains -- * Errors , _InvalidInput , _OperationLimitExceeded , _DomainLimitExceeded , _UnsupportedTLD , _TLDRulesViolation , _DuplicateRequest -- * ContactType , ContactType (..) -- * CountryCode , CountryCode (..) -- * DomainAvailability , DomainAvailability (..) -- * ExtraParamName , ExtraParamName (..) -- * OperationStatus , OperationStatus (..) -- * OperationType , OperationType (..) -- * ContactDetail , ContactDetail , contactDetail , cdOrganizationName , cdEmail , cdState , cdFax , cdLastName , cdExtraParams , cdZipCode , cdAddressLine1 , cdCity , cdPhoneNumber , cdAddressLine2 , cdFirstName , cdCountryCode , cdContactType -- * DomainSummary , DomainSummary , domainSummary , dsExpiry , dsTransferLock , dsAutoRenew , dsDomainName -- * ExtraParam , ExtraParam , extraParam , epName , epValue -- * Nameserver , Nameserver , nameserver , nGlueIPs , nName -- * OperationSummary , OperationSummary , operationSummary , osOperationId , osStatus , osType , osSubmittedDate -- * Tag , Tag , tag , tagValue , tagKey ) where import Network.AWS.Prelude import Network.AWS.Route53Domains.Types.Product import Network.AWS.Route53Domains.Types.Sum import Network.AWS.Sign.V4 -- | API version '2014-05-15' of the Amazon Route 53 Domains SDK configuration. route53Domains :: Service route53Domains = Service { _svcAbbrev = "Route53Domains" , _svcSigner = v4 , _svcPrefix = "route53domains" , _svcVersion = "2014-05-15" , _svcEndpoint = defaultEndpoint route53Domains , _svcTimeout = Just 70 , _svcCheck = statusSuccess , _svcError = parseJSONError , _svcRetry = retry } where retry = Exponential { _retryBase = 5.0e-2 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check e | has (hasCode "ThrottlingException" . hasStatus 400) e = Just "throttling_exception" | has (hasCode "Throttling" . hasStatus 400) e = Just "throttling" | has (hasStatus 503) e = Just "service_unavailable" | has (hasStatus 500) e = Just "general_server_error" | has (hasStatus 509) e = Just "limit_exceeded" | otherwise = Nothing -- | The requested item is not acceptable. For example, for an OperationId it -- may refer to the ID of an operation that is already completed. For a -- domain name, it may not be a valid domain name or belong to the -- requester account. _InvalidInput :: AsError a => Getting (First ServiceError) a ServiceError _InvalidInput = _ServiceError . hasStatus 400 . hasCode "InvalidInput" -- | The number of operations or jobs running exceeded the allowed threshold -- for the account. _OperationLimitExceeded :: AsError a => Getting (First ServiceError) a ServiceError _OperationLimitExceeded = _ServiceError . hasStatus 400 . hasCode "OperationLimitExceeded" -- | The number of domains has exceeded the allowed threshold for the -- account. _DomainLimitExceeded :: AsError a => Getting (First ServiceError) a ServiceError _DomainLimitExceeded = _ServiceError . hasStatus 400 . hasCode "DomainLimitExceeded" -- | Amazon Route 53 does not support this top-level domain. _UnsupportedTLD :: AsError a => Getting (First ServiceError) a ServiceError _UnsupportedTLD = _ServiceError . hasStatus 400 . hasCode "UnsupportedTLD" -- | The top-level domain does not support this operation. _TLDRulesViolation :: AsError a => Getting (First ServiceError) a ServiceError _TLDRulesViolation = _ServiceError . hasStatus 400 . hasCode "TLDRulesViolation" -- | The request is already in progress for the domain. _DuplicateRequest :: AsError a => Getting (First ServiceError) a ServiceError _DuplicateRequest = _ServiceError . hasStatus 400 . hasCode "DuplicateRequest"
fmapfmapfmap/amazonka
amazonka-route53-domains/gen/Network/AWS/Route53Domains/Types.hs
mpl-2.0
4,533
0
13
1,090
770
442
328
101
1
{-| Purely functional top-down splay heaps. * D.D. Sleator and R.E. Rarjan, \"Self-Adjusting Binary Search Tree\", Journal of the Association for Computing Machinery, Vol 32, No 3, July 1985, pp 652-686. <http://www.cs.cmu.edu/~sleator/papers/self-adjusting.pdf> -} module Data.Heap.Splay ( -- * Data structures Heap(..) , Splay(..) -- * Creating heaps , empty , singleton , insert , fromList -- * Converting to a list , toList -- * Deleting , deleteMin -- * Checking heaps , null -- * Helper functions , partition , merge , minimum , valid , heapSort , showHeap , printHeap ) where import Control.Applicative hiding (empty) import Data.List (foldl', unfoldr) import Data.Maybe import Prelude hiding (minimum, maximum, null) ---------------------------------------------------------------- data Heap a = None | Some a (Splay a) deriving Show instance (Eq a, Ord a) => Eq (Heap a) where h1 == h2 = heapSort h1 == heapSort h2 data Splay a = Leaf | Node (Splay a) a (Splay a) deriving Show ---------------------------------------------------------------- {-| Splitting smaller and bigger with splay. Since this is a heap implementation, members is not necessarily unique. -} partition :: Ord a => a -> Splay a -> (Splay a, Splay a) partition _ Leaf = (Leaf, Leaf) partition k x@(Node xl xk xr) = case compare k xk of LT -> case xl of Leaf -> (Leaf, x) Node yl yk yr -> case compare k yk of LT -> let (lt, gt) = partition k yl -- LL :zig zig in (lt, Node gt yk (Node yr xk xr)) _ -> let (lt, gt) = partition k yr -- LR :zig zag in (Node yl yk lt, Node gt xk xr) _ -> case xr of Leaf -> (x, Leaf) Node yl yk yr -> case compare k yk of LT -> let (lt, gt) = partition k yl in (Node xl xk lt, Node gt yk yr) -- RL :zig zig _ -> let (lt, gt) = partition k yr -- RR :zig zag in (Node (Node xl xk yl) yk lt, gt) ---------------------------------------------------------------- {-| Empty heap. -} empty :: Heap a empty = None {-| See if the heap is empty. >>> Data.Heap.Splay.null empty True >>> Data.Heap.Splay.null (singleton 1) False -} null :: Heap a -> Bool null None = True null _ = False {-| Singleton heap. -} singleton :: a -> Heap a singleton x = Some x (Node Leaf x Leaf) ---------------------------------------------------------------- {-| Insertion. Worst-case: O(N), amortized: O(log N). >>> insert 7 (fromList [5,3]) == fromList [3,5,7] True >>> insert 5 empty == singleton 5 True -} insert :: Ord a => a -> Heap a -> Heap a insert x None = singleton x insert x (Some m t) = Some m' $ Node l x r where m' = min x m (l,r) = partition x t ---------------------------------------------------------------- {-| Creating a heap from a list. >>> empty == fromList [] True >>> singleton 'a' == fromList ['a'] True >>> fromList [5,3] == fromList [5,3] True -} fromList :: Ord a => [a] -> Heap a fromList = foldl' (flip insert) empty ---------------------------------------------------------------- {-| Creating a list from a heap. Worst-case: O(N) >>> let xs = [5,3,5] >>> length (toList (fromList xs)) == length xs True >>> toList empty [] -} toList :: Heap a -> [a] toList None = [] toList (Some _ t) = inorder t [] where inorder Leaf xs = xs inorder (Node l x r) xs = inorder l (x : inorder r xs) ---------------------------------------------------------------- {-| Finding the minimum element. Worst-case: O(1). >>> minimum (fromList [3,5,1]) Just 1 >>> minimum empty Nothing -} minimum :: Heap a -> Maybe a minimum None = Nothing minimum (Some m _) = Just m ---------------------------------------------------------------- {-| Deleting the minimum element. Worst-case: O(N), amortized: O(log N). >>> deleteMin (fromList [5,3,7]) == fromList [5,7] True >>> deleteMin empty == empty True -} deleteMin :: Heap a -> Heap a deleteMin None = None deleteMin (Some _ t) = fromMaybe None $ do t' <- deleteMin' t m <- findMin' t' return $ Some m t' deleteMin2 :: Heap a -> Maybe (a, Heap a) deleteMin2 None = Nothing deleteMin2 h = (\m -> (m, deleteMin h)) <$> minimum h -- deleteMin' and findMin' cannot be implemented together deleteMin' :: Splay a -> Maybe (Splay a) deleteMin' Leaf = Nothing deleteMin' (Node Leaf _ r) = Just r deleteMin' (Node (Node Leaf _ lr) x r) = Just (Node lr x r) deleteMin' (Node (Node ll lx lr) x r) = let Just t = deleteMin' ll in Just (Node t lx (Node lr x r)) findMin' :: Splay a -> Maybe a findMin' Leaf = Nothing findMin' (Node Leaf x _) = Just x findMin' (Node l _ _) = findMin' l ---------------------------------------------------------------- {-| Merging two heaps. Worst-case: O(N), amortized: O(log N). >>> merge (fromList [5,3]) (fromList [5,7]) == fromList [3,5,5,7] True -} merge :: Ord a => Heap a -> Heap a -> Heap a merge None t = t merge t None = t merge (Some m1 t1) (Some m2 t2) = Some m t where m = min m1 m2 t = merge' t1 t2 merge' :: Ord a => Splay a -> Splay a -> Splay a merge' Leaf t = t merge' (Node a x b) t = Node (merge' ta a) x (merge' tb b) where (ta,tb) = partition x t ---------------------------------------------------------------- -- Basic operations ---------------------------------------------------------------- {-| Checking validity of a heap. -} valid :: Ord a => Heap a -> Bool valid t = isOrdered (heapSort t) heapSort :: Ord a => Heap a -> [a] heapSort t = unfoldr deleteMin2 t isOrdered :: Ord a => [a] -> Bool isOrdered [] = True isOrdered [_] = True isOrdered (x:y:xys) = x <= y && isOrdered (y:xys) -- allowing duplicated keys showHeap :: Show a => Splay a -> String showHeap = showHeap' "" showHeap' :: Show a => String -> Splay a -> String showHeap' _ Leaf = "\n" showHeap' pref (Node l x r) = show x ++ "\n" ++ pref ++ "+ " ++ showHeap' pref' l ++ pref ++ "+ " ++ showHeap' pref' r where pref' = " " ++ pref printHeap :: Show a => Splay a -> IO () printHeap = putStr . showHeap
kazu-yamamoto/llrbtree
Data/Heap/Splay.hs
bsd-3-clause
6,304
0
19
1,598
1,860
950
910
111
6
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Test.Matrix.Tri.Banded -- Copyright : Copyright (c) 2008, Patrick Perry <[email protected]> -- License : BSD3 -- Maintainer : Patrick Perry <[email protected]> -- Stability : experimental -- module Test.Matrix.Tri.Banded ( TriBanded(..), TriBandedMV(..), TriBandedMM(..), TriBandedSV(..), TriBandedSM(..), ) where import Control.Monad ( replicateM ) import Test.QuickCheck hiding ( vector ) import Test.QuickCheck.BLAS ( TestElem ) import qualified Test.QuickCheck as QC import qualified Test.QuickCheck.BLAS as Test import Data.Vector.Dense ( Vector ) import Data.Matrix.Dense ( Matrix ) import Data.Matrix.Banded import Data.Elem.BLAS ( Elem, BLAS1, BLAS3 ) import Data.Matrix.Tri ( Tri, triFromBase ) import Data.Matrix.Class( UpLoEnum(..), DiagEnum(..) ) listsFromBanded :: (Elem e) => Banded e -> ((Int,Int), (Int,Int),[[e]]) listsFromBanded a = ( (m,n) , (kl,ku) , map paddedDiag [(-kl)..ku] ) where (m,n) = shape a (kl,ku) = bandwidths a padBegin i = replicate (max (-i) 0) 0 padEnd i = replicate (max (m-n+i) 0) 0 paddedDiag i = ( padBegin i ++ elems (diagBanded a i) ++ padEnd i ) triBanded :: (TestElem e) => UpLoEnum -> DiagEnum -> Int -> Int -> Gen (Banded e) triBanded Upper NonUnit n k = do a <- triBanded Upper Unit n k d <- Test.elems n let (_,_,(_:ds)) = listsFromBanded a return $ listsBanded (n,n) (0,k) (d:ds) triBanded Lower NonUnit n k = do a <- triBanded Lower Unit n k d <- Test.elems n let (_,_,ds) = listsFromBanded a ds' = (init ds) ++ [d] return $ listsBanded (n,n) (k,0) ds' triBanded _ Unit n 0 = do return $ listsBanded (n,n) (0,0) [replicate n 1] triBanded Upper Unit n k = do a <- triBanded Upper Unit n (k-1) let (_,_,ds) = listsFromBanded a d <- Test.elems (n-k) >>= \xs -> return $ xs ++ replicate k 0 return $ listsBanded (n,n) (0,k) $ ds ++ [d] triBanded Lower Unit n k = do a <- triBanded Lower Unit n (k-1) let (_,_,ds) = listsFromBanded a d <- Test.elems (n-k) >>= \xs -> return $ replicate k 0 ++ xs return $ listsBanded (n,n) (k,0) $ [d] ++ ds data TriBanded e = TriBanded (Tri Banded e) (Banded e) deriving Show instance (TestElem e) => Arbitrary (TriBanded e) where arbitrary = do u <- elements [ Upper, Lower ] d <- elements [ Unit, NonUnit ] (m,n) <- Test.shape (_,k) <- Test.bandwidths (m,n) a <- triBanded u d n k l <- if n == 0 then return 0 else choose (0,n-1) junk <- replicateM l $ Test.elems n diagJunk <- Test.elems n let (_,_,ds) = listsFromBanded a t = triFromBase u d $ case (u,d) of (Upper,NonUnit) -> listsBanded (n,n) (l,k) $ junk ++ ds (Upper,Unit) -> listsBanded (n,n) (l,k) $ junk ++ [diagJunk] ++ tail ds (Lower,NonUnit) -> listsBanded (n,n) (k,l) $ ds ++ junk (Lower,Unit) -> listsBanded (n,n) (k,l) $ init ds ++ [diagJunk] ++ junk (t',a') <- elements [ (t,a), (herm t, herm a)] return $ TriBanded t' a' data TriBandedMV e = TriBandedMV (Tri Banded e) (Banded e) (Vector e) deriving Show instance (TestElem e) => Arbitrary (TriBandedMV e) where arbitrary = do (TriBanded t a) <- arbitrary x <- Test.vector (numCols t) return $ TriBandedMV t a x data TriBandedMM e = TriBandedMM (Tri Banded e) (Banded e) (Matrix e) deriving Show instance (TestElem e, BLAS3 e) => Arbitrary (TriBandedMM e) where arbitrary = do (TriBanded t a) <- arbitrary (_,n) <- Test.shape b <- Test.matrix (numCols t, n) return $ TriBandedMM t a b data TriBandedSV e = TriBandedSV (Tri Banded e) (Vector e) deriving (Show) instance (TestElem e, BLAS3 e) => Arbitrary (TriBandedSV e) where arbitrary = do (TriBanded t a) <- arbitrary if any (== 0) (elems $ diagBanded a 0) then arbitrary else do x <- Test.vector (numCols t) let y = t <*> x return (TriBandedSV t y) data TriBandedSM e = TriBandedSM (Tri Banded e) (Matrix e) deriving (Show) instance (TestElem e, BLAS3 e) => Arbitrary (TriBandedSM e) where arbitrary = do (TriBandedSV t _) <- arbitrary (_,n) <- Test.shape a <- Test.matrix (numCols t, n) let b = t <**> a return (TriBandedSM t b)
patperry/hs-linear-algebra
tests-old/Test/Matrix/Tri/Banded.hs
bsd-3-clause
4,926
0
19
1,562
2,001
1,063
938
114
1
module Koan.List where import Prelude hiding (concat, head, init, last, reverse, tail, (++)) import Koan.Functor as K import Koan.Applicative as K import Koan.Monad as K enrolled :: Bool enrolled = False head :: [a] -> a head (x:_) = x tail :: [a] -> [a] tail (_:xs) = xs last :: [a] -> a last [x] = x last (_:xs) = last xs reverse :: [a] -> [a] reverse = go [] where go rs (x:xs) = go (x:rs) xs go rs [] = rs (++) :: [a] -> [a] -> [a] (++) (x:xs) ys = x:(xs ++ ys) (++) [] ys = ys concat :: [[a]] -> [a] concat (x:xs) = x ++ concat xs concat [] = [] tails :: [a] -> [[a]] tails (x:xs) = (x:xs) : tails xs tails [] = [[]] mapList :: (a -> b) -> [a] -> [b] mapList _ [] = [] mapList f (x:xs) = f x : mapList f xs filterList :: (a -> Bool) -> [a] -> [a] filterList _ [] = [] filterList p (x:xs) | p x = x : filterList p xs | otherwise = filterList p xs foldlList :: (b -> a -> b) -> b -> [a] -> b foldlList _ acc [] = acc foldlList op acc (x:xs) = foldlList op (op acc x) xs foldrList :: (a -> b -> b) -> b -> [a] -> b foldrList _ acc [] = acc foldrList op acc (x:xs) = op x (foldrList op acc xs) -- Note that those are square brackets, not round brackets. applyList :: [a -> b] -> [a] -> [b] applyList [] _ = [] applyList _ [] = [] applyList (f:fs) xs = (f K.<$> xs) ++ applyList fs xs bindList :: (a -> [b]) -> [a] -> [b] bindList _ [] = [] bindList f (x:xs) = f x ++ bindList f xs instance K.Functor [] where fmap = mapList instance K.Applicative [] where pure a = [a] (<*>) = applyList instance K.Monad [] where (>>=) = flip bindList
Kheldar/hw-koans
solution/Koan/List.hs
bsd-3-clause
1,649
0
9
455
961
523
438
55
2
{-# LANGUAGE CPP #-} -- | Our extended FCode monad. -- We add a mapping from names to CmmExpr, to support local variable names in -- the concrete C-- code. The unique supply of the underlying FCode monad -- is used to grab a new unique for each local variable. -- In C--, a local variable can be declared anywhere within a proc, -- and it scopes from the beginning of the proc to the end. Hence, we have -- to collect declarations as we parse the proc, and feed the environment -- back in circularly (to avoid a two-pass algorithm). module StgCmmExtCode ( CmmParse, unEC, Named(..), Env, loopDecls, getEnv, newLocal, newLabel, newBlockId, newFunctionName, newImport, lookupLabel, lookupName, code, emit, emitLabel, emitAssign, emitStore, getCode, getCodeR, emitOutOfLine, withUpdFrameOff, getUpdFrameOff ) where import qualified StgCmmMonad as F import StgCmmMonad (FCode, newUnique) import Cmm import CLabel import MkGraph -- import BasicTypes import BlockId import DynFlags import FastString import Module import UniqFM import Unique import Control.Monad (liftM, ap) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif -- | The environment contains variable definitions or blockids. data Named = VarN CmmExpr -- ^ Holds CmmLit(CmmLabel ..) which gives the label type, -- eg, RtsLabel, ForeignLabel, CmmLabel etc. | FunN PackageKey -- ^ A function name from this package | LabelN BlockId -- ^ A blockid of some code or data. -- | An environment of named things. type Env = UniqFM Named -- | Local declarations that are in scope during code generation. type Decls = [(FastString,Named)] -- | Does a computation in the FCode monad, with a current environment -- and a list of local declarations. Returns the resulting list of declarations. newtype CmmParse a = EC { unEC :: Env -> Decls -> FCode (Decls, a) } type ExtCode = CmmParse () returnExtFC :: a -> CmmParse a returnExtFC a = EC $ \_ s -> return (s, a) thenExtFC :: CmmParse a -> (a -> CmmParse b) -> CmmParse b thenExtFC (EC m) k = EC $ \e s -> do (s',r) <- m e s; unEC (k r) e s' instance Functor CmmParse where fmap = liftM instance Applicative CmmParse where pure = return (<*>) = ap instance Monad CmmParse where (>>=) = thenExtFC return = returnExtFC instance HasDynFlags CmmParse where getDynFlags = EC (\_ d -> do dflags <- getDynFlags return (d, dflags)) -- | Takes the variable decarations and imports from the monad -- and makes an environment, which is looped back into the computation. -- In this way, we can have embedded declarations that scope over the whole -- procedure, and imports that scope over the entire module. -- Discards the local declaration contained within decl' -- loopDecls :: CmmParse a -> CmmParse a loopDecls (EC fcode) = EC $ \e globalDecls -> do (_, a) <- F.fixC (\ ~(decls, _) -> fcode (addListToUFM e decls) globalDecls) return (globalDecls, a) -- | Get the current environment from the monad. getEnv :: CmmParse Env getEnv = EC $ \e s -> return (s, e) addDecl :: FastString -> Named -> ExtCode addDecl name named = EC $ \_ s -> return ((name, named) : s, ()) -- | Add a new variable to the list of local declarations. -- The CmmExpr says where the value is stored. addVarDecl :: FastString -> CmmExpr -> ExtCode addVarDecl var expr = addDecl var (VarN expr) -- | Add a new label to the list of local declarations. addLabel :: FastString -> BlockId -> ExtCode addLabel name block_id = addDecl name (LabelN block_id) -- | Create a fresh local variable of a given type. newLocal :: CmmType -- ^ data type -> FastString -- ^ name of variable -> CmmParse LocalReg -- ^ register holding the value newLocal ty name = do u <- code newUnique let reg = LocalReg u ty addVarDecl name (CmmReg (CmmLocal reg)) return reg -- | Allocate a fresh label. newLabel :: FastString -> CmmParse BlockId newLabel name = do u <- code newUnique addLabel name (mkBlockId u) return (mkBlockId u) newBlockId :: CmmParse BlockId newBlockId = code F.newLabelC -- | Add add a local function to the environment. newFunctionName :: FastString -- ^ name of the function -> PackageKey -- ^ package of the current module -> ExtCode newFunctionName name pkg = addDecl name (FunN pkg) -- | Add an imported foreign label to the list of local declarations. -- If this is done at the start of the module the declaration will scope -- over the whole module. newImport :: (FastString, CLabel) -> CmmParse () newImport (name, cmmLabel) = addVarDecl name (CmmLit (CmmLabel cmmLabel)) -- | Lookup the BlockId bound to the label with this name. -- If one hasn't been bound yet, create a fresh one based on the -- Unique of the name. lookupLabel :: FastString -> CmmParse BlockId lookupLabel name = do env <- getEnv return $ case lookupUFM env name of Just (LabelN l) -> l _other -> mkBlockId (newTagUnique (getUnique name) 'L') -- | Lookup the location of a named variable. -- Unknown names are treated as if they had been 'import'ed from the runtime system. -- This saves us a lot of bother in the RTS sources, at the expense of -- deferring some errors to link time. lookupName :: FastString -> CmmParse CmmExpr lookupName name = do env <- getEnv return $ case lookupUFM env name of Just (VarN e) -> e Just (FunN pkg) -> CmmLit (CmmLabel (mkCmmCodeLabel pkg name)) _other -> CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageKey name)) -- | Lift an FCode computation into the CmmParse monad code :: FCode a -> CmmParse a code fc = EC $ \_ s -> do r <- fc return (s, r) emit :: CmmAGraph -> CmmParse () emit = code . F.emit emitLabel :: BlockId -> CmmParse () emitLabel = code. F.emitLabel emitAssign :: CmmReg -> CmmExpr -> CmmParse () emitAssign l r = code (F.emitAssign l r) emitStore :: CmmExpr -> CmmExpr -> CmmParse () emitStore l r = code (F.emitStore l r) getCode :: CmmParse a -> CmmParse CmmAGraph getCode (EC ec) = EC $ \e s -> do ((s',_), gr) <- F.getCodeR (ec e s) return (s', gr) getCodeR :: CmmParse a -> CmmParse (a, CmmAGraph) getCodeR (EC ec) = EC $ \e s -> do ((s', r), gr) <- F.getCodeR (ec e s) return (s', (r,gr)) emitOutOfLine :: BlockId -> CmmAGraph -> CmmParse () emitOutOfLine l g = code (F.emitOutOfLine l g) withUpdFrameOff :: UpdFrameOffset -> CmmParse () -> CmmParse () withUpdFrameOff size inner = EC $ \e s -> F.withUpdFrameOff size $ (unEC inner) e s getUpdFrameOff :: CmmParse UpdFrameOffset getUpdFrameOff = code $ F.getUpdFrameOff
spacekitteh/smcghc
compiler/codeGen/StgCmmExtCode.hs
bsd-3-clause
7,042
0
15
1,812
1,686
903
783
136
3
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module CTT where import Control.Applicative import Data.List import Data.Maybe import Data.Map (Map,(!),filterWithKey,elems) import qualified Data.Map as Map import Text.PrettyPrint as PP import Connections -------------------------------------------------------------------------------- -- | Terms data Loc = Loc { locFile :: String , locPos :: (Int,Int) } deriving Eq type Ident = String type LIdent = String -- Telescope (x1 : A1) .. (xn : An) type Tele = [(Ident,Ter)] data Label = OLabel LIdent Tele -- Object label | PLabel LIdent Tele [Name] (System Ter) -- Path label deriving (Eq,Show) -- OBranch of the form: c x1 .. xn -> e -- PBranch of the form: c x1 .. xn i1 .. im -> e data Branch = OBranch LIdent [Ident] Ter | PBranch LIdent [Ident] [Name] Ter deriving (Eq,Show) -- Declarations: x : A = e type Decl = (Ident,(Ter,Ter)) declIdents :: [Decl] -> [Ident] declIdents decls = [ x | (x,_) <- decls ] declTers :: [Decl] -> [Ter] declTers decls = [ d | (_,(_,d)) <- decls ] declTele :: [Decl] -> Tele declTele decls = [ (x,t) | (x,(t,_)) <- decls ] declDefs :: [Decl] -> [(Ident,Ter)] declDefs decls = [ (x,d) | (x,(_,d)) <- decls ] labelTele :: Label -> (LIdent,Tele) labelTele (OLabel c ts) = (c,ts) labelTele (PLabel c ts _ _) = (c,ts) labelName :: Label -> LIdent labelName = fst . labelTele labelTeles :: [Label] -> [(LIdent,Tele)] labelTeles = map labelTele lookupLabel :: LIdent -> [Label] -> Maybe Tele lookupLabel x xs = lookup x (labelTeles xs) lookupPLabel :: LIdent -> [Label] -> Maybe (Tele,[Name],System Ter) lookupPLabel x xs = listToMaybe [ (ts,is,es) | PLabel y ts is es <- xs, x == y ] branchName :: Branch -> LIdent branchName (OBranch c _ _) = c branchName (PBranch c _ _ _) = c lookupBranch :: LIdent -> [Branch] -> Maybe Branch lookupBranch _ [] = Nothing lookupBranch x (b:brs) = case b of OBranch c _ _ | x == c -> Just b | otherwise -> lookupBranch x brs PBranch c _ _ _ | x == c -> Just b | otherwise -> lookupBranch x brs -- Terms data Ter = App Ter Ter | Pi Ter | Lam Ident Ter Ter | Where Ter [Decl] | Var Ident | U -- Sigma types: | Sigma Ter | Pair Ter Ter | Fst Ter | Snd Ter -- constructor c Ms | Con LIdent [Ter] | PCon LIdent Ter [Ter] [Formula] -- c A ts phis (A is the data type) -- branches c1 xs1 -> M1,..., cn xsn -> Mn | Split Ident Loc Ter [Branch] -- labelled sum c1 A1s,..., cn Ans (assumes terms are constructors) | Sum Loc Ident [Label] -- TODO: should only contain OLabels | HSum Loc Ident [Label] -- undefined and holes | Undef Loc Ter -- Location and type | Hole Loc -- Id type | IdP Ter Ter Ter | Path Name Ter | AppFormula Ter Formula -- Kan composition and filling | Comp Ter Ter (System Ter) | Fill Ter Ter (System Ter) -- Glue | Glue Ter (System Ter) | GlueElem Ter (System Ter) | UnGlueElem Ter (System Ter) deriving Eq -- For an expression t, returns (u,ts) where u is no application and t = u ts unApps :: Ter -> (Ter,[Ter]) unApps = aux [] where aux :: [Ter] -> Ter -> (Ter,[Ter]) aux acc (App r s) = aux (s:acc) r aux acc t = (t,acc) mkApps :: Ter -> [Ter] -> Ter mkApps (Con l us) vs = Con l (us ++ vs) mkApps t ts = foldl App t ts mkWheres :: [[Decl]] -> Ter -> Ter mkWheres [] e = e mkWheres (d:ds) e = Where (mkWheres ds e) d -------------------------------------------------------------------------------- -- | Values data Val = VU | Ter Ter Env | VPi Val Val | VSigma Val Val | VPair Val Val | VCon LIdent [Val] | VPCon LIdent Val [Val] [Formula] -- Id values | VIdP Val Val Val | VPath Name Val | VComp Val Val (System Val) -- Glue values | VGlue Val (System Val) | VGlueElem Val (System Val) | VUnGlueElem Val (System Val) -- Composition in the universe | VCompU Val (System Val) -- Composition for HITs; the type is constant | VHComp Val Val (System Val) -- Neutral values: | VVar Ident Val | VFst Val | VSnd Val | VSplit Val Val | VApp Val Val | VAppFormula Val Formula | VLam Ident Val Val | VUnGlueElemU Val Val (System Val) deriving Eq isNeutral :: Val -> Bool isNeutral v = case v of Ter Undef{} _ -> True Ter Hole{} _ -> True VVar{} -> True VComp{} -> True VFst{} -> True VSnd{} -> True VSplit{} -> True VApp{} -> True VAppFormula{} -> True VUnGlueElemU{} -> True VUnGlueElem{} -> True _ -> False isNeutralSystem :: System Val -> Bool isNeutralSystem = any isNeutral . elems -- isNeutralPath :: Val -> Bool -- isNeutralPath (VPath _ v) = isNeutral v -- isNeutralPath _ = True mkVar :: Int -> String -> Val -> Val mkVar k x = VVar (x ++ show k) mkVarNice :: [String] -> String -> Val -> Val mkVarNice xs x = VVar (head (ys \\ xs)) where ys = x:map (\n -> x ++ show n) [0..] unCon :: Val -> [Val] unCon (VCon _ vs) = vs unCon v = error $ "unCon: not a constructor: " ++ show v isCon :: Val -> Bool isCon VCon{} = True isCon _ = False -- Constant path: <_> v constPath :: Val -> Val constPath = VPath (Name "_") -------------------------------------------------------------------------------- -- | Environments data Ctxt = Empty | Upd Ident Ctxt | Sub Name Ctxt | Def [Decl] Ctxt deriving (Show,Eq) -- The Idents and Names in the Ctxt refer to the elements in the two -- lists. This is more efficient because acting on an environment now -- only need to affect the lists and not the whole context. type Env = (Ctxt,[Val],[Formula]) emptyEnv :: Env emptyEnv = (Empty,[],[]) def :: [Decl] -> Env -> Env def ds (rho,vs,fs) = (Def ds rho,vs,fs) sub :: (Name,Formula) -> Env -> Env sub (i,phi) (rho,vs,fs) = (Sub i rho,vs,phi:fs) upd :: (Ident,Val) -> Env -> Env upd (x,v) (rho,vs,fs) = (Upd x rho,v:vs,fs) upds :: [(Ident,Val)] -> Env -> Env upds xus rho = foldl (flip upd) rho xus updsTele :: Tele -> [Val] -> Env -> Env updsTele tele vs = upds (zip (map fst tele) vs) subs :: [(Name,Formula)] -> Env -> Env subs iphis rho = foldl (flip sub) rho iphis mapEnv :: (Val -> Val) -> (Formula -> Formula) -> Env -> Env mapEnv f g (rho,vs,fs) = (rho,map f vs,map g fs) valAndFormulaOfEnv :: Env -> ([Val],[Formula]) valAndFormulaOfEnv (_,vs,fs) = (vs,fs) valOfEnv :: Env -> [Val] valOfEnv = fst . valAndFormulaOfEnv formulaOfEnv :: Env -> [Formula] formulaOfEnv = snd . valAndFormulaOfEnv domainEnv :: Env -> [Name] domainEnv (rho,_,_) = domCtxt rho where domCtxt rho = case rho of Empty -> [] Upd _ e -> domCtxt e Def ts e -> domCtxt e Sub i e -> i : domCtxt e -- Extract the context from the environment, used when printing holes contextOfEnv :: Env -> [String] contextOfEnv rho = case rho of (Empty,_,_) -> [] (Upd x e,VVar n t:vs,fs) -> (n ++ " : " ++ show t) : contextOfEnv (e,vs,fs) (Upd x e,v:vs,fs) -> (x ++ " = " ++ show v) : contextOfEnv (e,vs,fs) (Def _ e,vs,fs) -> contextOfEnv (e,vs,fs) (Sub i e,vs,phi:fs) -> (show i ++ " = " ++ show phi) : contextOfEnv (e,vs,fs) -------------------------------------------------------------------------------- -- | Pretty printing instance Show Env where show = render . showEnv True showEnv :: Bool -> Env -> Doc showEnv b e = let -- This decides if we should print "x = " or not names x = if b then text x <+> equals else PP.empty par x = if b then parens x else x com = if b then comma else PP.empty showEnv1 e = case e of (Upd x env,u:us,fs) -> showEnv1 (env,us,fs) <+> names x <+> showVal1 u <> com (Sub i env,us,phi:fs) -> showEnv1 (env,us,fs) <+> names (show i) <+> text (show phi) <> com (Def _ env,vs,fs) -> showEnv1 (env,vs,fs) _ -> showEnv b e in case e of (Empty,_,_) -> PP.empty (Def _ env,vs,fs) -> showEnv b (env,vs,fs) (Upd x env,u:us,fs) -> par $ showEnv1 (env,us,fs) <+> names x <+> showVal u (Sub i env,us,phi:fs) -> par $ showEnv1 (env,us,fs) <+> names (show i) <+> text (show phi) instance Show Loc where show = render . showLoc showLoc :: Loc -> Doc showLoc (Loc name (i,j)) = text (show (i,j) ++ " in " ++ name) showFormula :: Formula -> Doc showFormula phi = case phi of _ :\/: _ -> parens (text (show phi)) _ :/\: _ -> parens (text (show phi)) _ -> text $ show phi instance Show Ter where show = render . showTer showTer :: Ter -> Doc showTer v = case v of U -> char 'U' App e0 e1 -> showTer e0 <+> showTer1 e1 Pi e0 -> text "Pi" <+> showTer e0 Lam x t e -> char '\\' <> parens (text x <+> colon <+> showTer t) <+> text "->" <+> showTer e Fst e -> showTer1 e <> text ".1" Snd e -> showTer1 e <> text ".2" Sigma e0 -> text "Sigma" <+> showTer1 e0 Pair e0 e1 -> parens (showTer e0 <> comma <> showTer e1) Where e d -> showTer e <+> text "where" <+> showDecls d Var x -> text x Con c es -> text c <+> showTers es PCon c a es phis -> text c <+> braces (showTer a) <+> showTers es <+> hsep (map ((char '@' <+>) . showFormula) phis) Split f _ _ _ -> text f Sum _ n _ -> text n HSum _ n _ -> text n Undef{} -> text "undefined" Hole{} -> text "?" IdP e0 e1 e2 -> text "IdP" <+> showTers [e0,e1,e2] Path i e -> char '<' <> text (show i) <> char '>' <+> showTer e AppFormula e phi -> showTer1 e <+> char '@' <+> showFormula phi Comp e t ts -> text "comp" <+> showTers [e,t] <+> text (showSystem ts) Fill e t ts -> text "fill" <+> showTers [e,t] <+> text (showSystem ts) Glue a ts -> text "glue" <+> showTer1 a <+> text (showSystem ts) GlueElem a ts -> text "glueElem" <+> showTer1 a <+> text (showSystem ts) UnGlueElem a ts -> text "unglueElem" <+> showTer1 a <+> text (showSystem ts) showTers :: [Ter] -> Doc showTers = hsep . map showTer1 showTer1 :: Ter -> Doc showTer1 t = case t of U -> char 'U' Con c [] -> text c Var{} -> showTer t Undef{} -> showTer t Hole{} -> showTer t Split{} -> showTer t Sum{} -> showTer t HSum{} -> showTer t Fst{} -> showTer t Snd{} -> showTer t _ -> parens (showTer t) showDecls :: [Decl] -> Doc showDecls defs = hsep $ punctuate comma [ text x <+> equals <+> showTer d | (x,(_,d)) <- defs ] instance Show Val where show = render . showVal showVal :: Val -> Doc showVal v = case v of VU -> char 'U' Ter t@Sum{} rho -> showTer t <+> showEnv False rho Ter t@HSum{} rho -> showTer t <+> showEnv False rho Ter t@Split{} rho -> showTer t <+> showEnv False rho Ter t rho -> showTer1 t <+> showEnv True rho VCon c us -> text c <+> showVals us VPCon c a us phis -> text c <+> braces (showVal a) <+> showVals us <+> hsep (map ((char '@' <+>) . showFormula) phis) VHComp v0 v1 vs -> text "hComp" <+> showVals [v0,v1] <+> text (showSystem vs) VPi a l@(VLam x t b) | "_" `isPrefixOf` x -> showVal1 a <+> text "->" <+> showVal1 b | otherwise -> char '(' <> showLam v VPi a b -> text "Pi" <+> showVals [a,b] VPair u v -> parens (showVal u <> comma <> showVal v) VSigma u v -> text "Sigma" <+> showVals [u,v] VApp u v -> showVal u <+> showVal1 v VLam{} -> text "\\(" <> showLam v VPath{} -> char '<' <> showPath v VSplit u v -> showVal u <+> showVal1 v VVar x _ -> text x VFst u -> showVal1 u <> text ".1" VSnd u -> showVal1 u <> text ".2" VIdP v0 v1 v2 -> text "IdP" <+> showVals [v0,v1,v2] VAppFormula v phi -> showVal v <+> char '@' <+> showFormula phi VComp v0 v1 vs -> text "comp" <+> showVals [v0,v1] <+> text (showSystem vs) VGlue a ts -> text "glue" <+> showVal1 a <+> text (showSystem ts) VGlueElem a ts -> text "glueElem" <+> showVal1 a <+> text (showSystem ts) VUnGlueElem a ts -> text "unglueElem" <+> showVal1 a <+> text (showSystem ts) VUnGlueElemU v b es -> text "unGlueElemU" <+> showVals [v,b] <+> text (showSystem es) VCompU a ts -> text "comp (<_> U)" <+> showVal1 a <+> text (showSystem ts) showPath :: Val -> Doc showPath e = case e of VPath i a@VPath{} -> text (show i) <+> showPath a VPath i a -> text (show i) <> char '>' <+> showVal a _ -> showVal e -- Merge lambdas of the same type showLam :: Val -> Doc showLam e = case e of VLam x t a@(VLam _ t' _) | t == t' -> text x <+> showLam a | otherwise -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal a VPi _ (VLam x t a@(VPi _ (VLam _ t' _))) | t == t' -> text x <+> showLam a | otherwise -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal a VLam x t e -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal e VPi _ (VLam x t e) -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal e _ -> showVal e showVal1 :: Val -> Doc showVal1 v = case v of VU -> showVal v VCon c [] -> showVal v VVar{} -> showVal v VFst{} -> showVal v VSnd{} -> showVal v Ter t@Sum{} rho -> showTer t <+> showEnv False rho Ter t@HSum{} rho -> showTer t <+> showEnv False rho Ter t@Split{} rho -> showTer t <+> showEnv False rho Ter t rho -> showTer1 t <+> showEnv True rho _ -> parens (showVal v) showVals :: [Val] -> Doc showVals = hsep . map showVal1
abooij/cubicaltt
CTT.hs
mit
14,424
0
17
4,506
5,959
3,053
2,906
333
27
{- ---------------------------------------------------------------------------------- - Copyright (C) 2010-2011 Massachusetts Institute of Technology - Copyright (C) 2010-2011 Yuan Tang <[email protected]> - Charles E. Leiserson <[email protected]> - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>. - - Suggestsions: [email protected] - Bugs: [email protected] - -------------------------------------------------------------------------------- -} module PParser2 where {- modules for 2nd pass parsers -} import Text.ParserCombinators.Parsec import Control.Monad import PBasicParser import PShow import PData import qualified Data.Map as Map pToken1 :: GenParser Char ParserState String pToken1 = do reserved "Pochoir_Array" (l_type, l_rank) <- angles pDeclStatic <?> "Pochoir_Array static parameters" l_arrayDecl <- commaSep1 pDeclDynamic <?> "Pochoir_Array Dynamic parameters" semi l_state <- getState return (concat $ map (outputSArray (l_type, l_rank) (pArray l_state)) l_arrayDecl) -- return ("Pochoir_Array <" ++ show l_type ++ ", " ++ show l_rank ++ "> " ++ pShowArrayDynamicDecl l_arrayDecl ++ ";\n") <|> do ch <- anyChar return [ch] <?> "line" outputSArray :: (PType, Int) -> Map.Map PName PArray -> ([PName], PName, [DimExpr]) -> String outputSArray (l_type, l_rank) m_array (l_qualifiers, l_array, l_dims) = case Map.lookup l_array m_array of Nothing -> breakline ++ "Pochoir_Array <" ++ show l_type ++ ", " ++ show l_rank ++ "> " ++ pShowDynamicDecl [(l_qualifiers, l_array, l_dims)] pShowArrayDim ++ ";" Just l_pArray -> breakline ++ "Pochoir_Array <" ++ show l_type ++ ", " ++ show l_rank ++ "> " ++ pShowDynamicDecl [(l_qualifiers, l_array, l_dims)] pShowArrayDim ++ ";"
Pochoir/Pochoir
src/PParser2.hs
gpl-3.0
2,636
0
16
679
364
192
172
27
2
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} module Yesod.Core.Class.Handler ( MonadHandler (..) , MonadWidget (..) , liftHandlerT , liftWidgetT ) where import Yesod.Core.Types import Control.Monad.Logger (MonadLogger) import Control.Monad.Trans.Resource (MonadResource) import Control.Monad.Trans.Class (lift) import Data.Conduit.Internal (Pipe, ConduitM) import Control.Monad.Trans.Identity ( IdentityT) import Control.Monad.Trans.List ( ListT ) import Control.Monad.Trans.Maybe ( MaybeT ) import Control.Monad.Trans.Except ( ExceptT ) import Control.Monad.Trans.Reader ( ReaderT ) import Control.Monad.Trans.State ( StateT ) import Control.Monad.Trans.Writer ( WriterT ) import Control.Monad.Trans.RWS ( RWST ) import qualified Control.Monad.Trans.RWS.Strict as Strict ( RWST ) import qualified Control.Monad.Trans.State.Strict as Strict ( StateT ) import qualified Control.Monad.Trans.Writer.Strict as Strict ( WriterT ) -- FIXME should we just use MonadReader instances instead? class (MonadResource m, MonadLogger m) => MonadHandler m where type HandlerSite m type SubHandlerSite m liftHandler :: HandlerFor (HandlerSite m) a -> m a liftSubHandler :: SubHandlerFor (SubHandlerSite m) (HandlerSite m) a -> m a liftHandlerT :: MonadHandler m => HandlerFor (HandlerSite m) a -> m a liftHandlerT = liftHandler {-# DEPRECATED liftHandlerT "Use liftHandler instead" #-} instance MonadHandler (HandlerFor site) where type HandlerSite (HandlerFor site) = site type SubHandlerSite (HandlerFor site) = site liftHandler = id {-# INLINE liftHandler #-} liftSubHandler (SubHandlerFor f) = HandlerFor f {-# INLINE liftSubHandler #-} instance MonadHandler (SubHandlerFor sub master) where type HandlerSite (SubHandlerFor sub master) = master type SubHandlerSite (SubHandlerFor sub master) = sub liftHandler (HandlerFor f) = SubHandlerFor $ \hd -> f hd { handlerEnv = let rhe = handlerEnv hd in rhe { rheRoute = fmap (rheRouteToMaster rhe) (rheRoute rhe) , rheRouteToMaster = id , rheChild = rheSite rhe } } {-# INLINE liftHandler #-} liftSubHandler = id {-# INLINE liftSubHandler #-} instance MonadHandler (WidgetFor site) where type HandlerSite (WidgetFor site) = site type SubHandlerSite (WidgetFor site) = site liftHandler (HandlerFor f) = WidgetFor $ f . wdHandler {-# INLINE liftHandler #-} liftSubHandler (SubHandlerFor f) = WidgetFor $ f . wdHandler {-# INLINE liftSubHandler #-} #define GO(T) instance MonadHandler m => MonadHandler (T m) where type HandlerSite (T m) = HandlerSite m; type SubHandlerSite (T m) = SubHandlerSite m; liftHandler = lift . liftHandler; liftSubHandler = lift . liftSubHandler #define GOX(X, T) instance (X, MonadHandler m) => MonadHandler (T m) where type HandlerSite (T m) = HandlerSite m; type SubHandlerSite (T m) = SubHandlerSite m; liftHandler = lift . liftHandler; liftSubHandler = lift . liftSubHandler GO(IdentityT) GO(ListT) GO(MaybeT) GO(ExceptT e) GO(ReaderT r) GO(StateT s) GOX(Monoid w, WriterT w) GOX(Monoid w, RWST r w s) GOX(Monoid w, Strict.RWST r w s) GO(Strict.StateT s) GOX(Monoid w, Strict.WriterT w) GO(Pipe l i o u) GO(ConduitM i o) #undef GO #undef GOX class MonadHandler m => MonadWidget m where liftWidget :: WidgetFor (HandlerSite m) a -> m a instance MonadWidget (WidgetFor site) where liftWidget = id {-# INLINE liftWidget #-} liftWidgetT :: MonadWidget m => WidgetFor (HandlerSite m) a -> m a liftWidgetT = liftWidget {-# DEPRECATED liftWidgetT "Use liftWidget instead" #-} #define GO(T) instance MonadWidget m => MonadWidget (T m) where liftWidget = lift . liftWidget #define GOX(X, T) instance (X, MonadWidget m) => MonadWidget (T m) where liftWidget = lift . liftWidget GO(IdentityT) GO(ListT) GO(MaybeT) GO(ExceptT e) GO(ReaderT r) GO(StateT s) GOX(Monoid w, WriterT w) GOX(Monoid w, RWST r w s) GOX(Monoid w, Strict.RWST r w s) GO(Strict.StateT s) GOX(Monoid w, Strict.WriterT w) GO(Pipe l i o u) GO(ConduitM i o) #undef GO #undef GOX
geraldus/yesod
yesod-core/src/Yesod/Core/Class/Handler.hs
mit
4,343
0
17
840
1,151
612
539
-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="ro-RO"> <title>Image Locaiton and Privacy Scanner | 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>
thc202/zap-extensions
addOns/imagelocationscanner/src/main/javahelp/org/zaproxy/zap/extension/imagelocationscanner/resources/help_ro_RO/helpset_ro_RO.hs
apache-2.0
995
78
66
162
419
212
207
-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="de-DE"> <title>Call Graph</title> <maps> <homeID>callgraph</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/callgraph/src/main/javahelp/help_de_DE/helpset_de_DE.hs
apache-2.0
961
77
66
156
407
206
201
-1
-1
import System.IO (hFlush, stdout) import Control.Monad (mapM) import Control.Monad.Error (runErrorT) import Control.Monad.Trans (liftIO) import qualified Data.Map as Map import qualified Data.Traversable as DT import Readline (readline, load_history) import Types import Reader (read_str) import Printer (_pr_str) import Env (Env, env_new, env_bind, env_get, env_set) import Core as Core -- read mal_read :: String -> IOThrows MalVal mal_read str = read_str str -- eval eval_ast :: MalVal -> Env -> IOThrows MalVal eval_ast sym@(MalSymbol _) env = env_get env sym eval_ast ast@(MalList lst m) env = do new_lst <- mapM (\x -> (eval x env)) lst return $ MalList new_lst m eval_ast ast@(MalVector lst m) env = do new_lst <- mapM (\x -> (eval x env)) lst return $ MalVector new_lst m eval_ast ast@(MalHashMap lst m) env = do new_hm <- DT.mapM (\x -> (eval x env)) lst return $ MalHashMap new_hm m eval_ast ast env = return ast let_bind :: Env -> [MalVal] -> IOThrows Env let_bind env [] = return env let_bind env (b:e:xs) = do evaled <- eval e env x <- liftIO $ env_set env b evaled let_bind env xs apply_ast :: MalVal -> Env -> IOThrows MalVal apply_ast ast@(MalList (MalSymbol "def!" : args) _) env = do case args of (a1@(MalSymbol _): a2 : []) -> do evaled <- eval a2 env liftIO $ env_set env a1 evaled _ -> throwStr "invalid def!" apply_ast ast@(MalList (MalSymbol "let*" : args) _) env = do case args of (a1 : a2 : []) -> do params <- (_to_list a1) let_env <- liftIO $ env_new $ Just env let_bind let_env params eval a2 let_env _ -> throwStr "invalid let*" apply_ast ast@(MalList (MalSymbol "do" : args) _) env = do case args of ([]) -> return Nil _ -> do el <- eval_ast (MalList args Nil) env case el of (MalList lst _) -> return $ last lst apply_ast ast@(MalList (MalSymbol "if" : args) _) env = do case args of (a1 : a2 : a3 : []) -> do cond <- eval a1 env if cond == MalFalse || cond == Nil then eval a3 env else eval a2 env (a1 : a2 : []) -> do cond <- eval a1 env if cond == MalFalse || cond == Nil then return Nil else eval a2 env _ -> throwStr "invalid if" apply_ast ast@(MalList (MalSymbol "fn*" : args) _) env = do case args of (a1 : a2 : []) -> do params <- (_to_list a1) return $ (_func (\args -> do fn_env1 <- liftIO $ env_new $ Just env fn_env2 <- liftIO $ env_bind fn_env1 params args eval a2 fn_env2)) _ -> throwStr "invalid fn*" apply_ast ast@(MalList _ _) env = do el <- eval_ast ast env case el of (MalList ((Func (Fn f) _) : rest) _) -> f $ rest el -> throwStr $ "invalid apply: " ++ (show el) eval :: MalVal -> Env -> IOThrows MalVal eval ast env = do case ast of (MalList _ _) -> apply_ast ast env _ -> eval_ast ast env -- print mal_print :: MalVal -> String mal_print exp = show exp -- repl rep :: Env -> String -> IOThrows String rep env line = do ast <- mal_read line exp <- eval ast env return $ mal_print exp repl_loop :: Env -> IO () repl_loop env = do line <- readline "user> " case line of Nothing -> return () Just "" -> repl_loop env Just str -> do res <- runErrorT $ rep env str out <- case res of Left (StringError str) -> return $ "Error: " ++ str Left (MalValError mv) -> return $ "Error: " ++ (show mv) Right val -> return val putStrLn out hFlush stdout repl_loop env main = do load_history repl_env <- env_new Nothing -- core.hs: defined using Haskell (mapM (\(k,v) -> (env_set repl_env (MalSymbol k) v)) Core.ns) -- core.mal: defined using the language itself runErrorT $ rep repl_env "(def! not (fn* (a) (if a false true)))" repl_loop repl_env
profan/mal
haskell/step4_if_fn_do.hs
mpl-2.0
4,277
0
21
1,450
1,633
803
830
117
10
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-} module ClassEqContext where class a ~ b => C a b
urbanslug/ghc
testsuite/tests/indexed-types/should_compile/ClassEqContext.hs
bsd-3-clause
106
0
7
20
23
12
11
-1
-1
{-# LANGUAGE TypeOperators, TypeFamilies, RankNTypes #-} {-| Module : Action.Internals Copyright : (c) Kai Lindholm, 2014 License : MIT Maintainer : [email protected] Stability : experimental -} module Network.RTorrent.Action.Internals ( Action (..) , simpleAction , pureAction , sequenceActions , (<+>) , Param (..) , ActionB (..) , AllAction (..) , allToMulti ) where import Control.Applicative import Control.Monad import Data.Monoid import Data.Traversable hiding (mapM) import Network.XmlRpc.Internals import Network.RTorrent.Command.Internals import Network.RTorrent.Priority -- | A type for actions that can act on different things like torrents and files. -- -- @a@ is the return type. data Action i a = Action [(String, [Param])] (forall m. (Monad m, Applicative m) => Value -> m a) i -- | Wrapper to get monoid and applicative instances. newtype ActionB i a = ActionB { runActionB :: i -> Action i a} -- | A simple action that can be used when constructing new ones. -- -- Watch out for using @Bool@ as @a@ since using it with this function will probably result in an error, -- since RTorrent actually returns 0 or 1 instead of a bool. -- One workaround is to get an @Int@ and use @Bool@'s @Enum@ instance. simpleAction :: XmlRpcType a => String -> [Param] -> i -> Action i a simpleAction cmd params = Action [(cmd, params)] parseSingle instance Functor (Action i) where fmap f (Action cmds p fid) = Action cmds (fmap f . p) fid instance Functor (ActionB i) where fmap f = ActionB . (fmap f .) . runActionB instance Applicative (ActionB i) where pure a = ActionB $ Action [] (const (pure a)) (ActionB a) <*> (ActionB b) = ActionB $ \tid -> let parse :: (Monad m, Applicative m) => (Value -> m (a -> b)) -> (Value -> m a) -> Value -> m b parse parseA parseB arr = do (valsA, valsB) <- splitAt len <$> getArray arr parseA (ValueArray valsA) <*> parseB (ValueArray valsB) len = length cmdsA Action cmdsA pA _ = a tid Action cmdsB pB _ = b tid in Action (cmdsA ++ cmdsB) (parse pA pB) tid instance Monoid a => Monoid (ActionB i a) where mempty = pure mempty mappend = liftA2 mappend instance XmlRpcType i => Command (Action i a) where type Ret (Action i a) = a commandCall (Action cmds _ tid) = RTMethodCall . ValueArray . concatMap (\(cmd, params) -> getArray' . runRTMethodCall $ mkRTMethodCall cmd (toValue tid : map toValue params)) $ cmds commandValue (Action _ parse _) = parse levels (Action cmds _ _) = length cmds -- | Parameters for actions. data Param = PString String | PInt Int | PTorrentPriority TorrentPriority | PFilePriority FilePriority instance Show Param where show (PString str) = show str show (PInt i) = show i show (PTorrentPriority p) = show (fromEnum p) show (PFilePriority p) = show (fromEnum p) instance XmlRpcType Param where toValue (PString str) = toValue str toValue (PInt i) = toValue i toValue (PTorrentPriority p) = toValue p toValue (PFilePriority p) = toValue p fromValue = fail "No fromValue for Params" getType _ = TUnknown -- | Sequence multiple actions, for example with @f = []@. sequenceActions :: Traversable f => f (i -> Action i a) -> i -> Action i (f a) sequenceActions = runActionB . traverse ActionB -- | An action that does nothing but return the value. pureAction :: a -> i -> Action i a pureAction a = Action [] (const (return a)) infixr 6 <+> -- | Combine two actions to get a new one. (<+>) :: (i -> Action i a) -> (i -> Action i b) -> i -> Action i (a :*: b) a <+> b = runActionB $ (:*:) <$> ActionB a <*> ActionB b data AllAction i a = AllAction i String (i -> Action i a) makeMultiCall :: [(String, [Param])] -> [String] makeMultiCall = ("" :) . map (\(cmd, params) -> cmd ++ "=" ++ makeList params) where makeList :: Show a => [a] -> String makeList params = ('{' :) . go params $ "}" where go :: Show a => [a] -> ShowS go [x] = shows x go (x:xs) = shows x . (',' :) . go xs go [] = id wrapForParse :: Monad m => Value -> m [Value] wrapForParse = mapM ( return . ValueArray . map (ValueArray . (:[])) <=< getArray) <=< getArray <=< single <=< single allToMulti :: AllAction i a -> j -> Action j [a] allToMulti (AllAction emptyId multicall action) = Action [(multicall, map PString $ makeMultiCall cmds)] (mapM parse <=< wrapForParse) where Action cmds parse _ = action emptyId instance Command (AllAction i a) where type Ret (AllAction i a) = [a] commandCall (AllAction emptyId multicall action) = mkRTMethodCall multicall . map ValueString . makeMultiCall $ cmds where Action cmds _ _ = action emptyId commandValue (AllAction emptyId _ action) = mapM parse <=< wrapForParse where Action _ parse _ = action emptyId
megantti/rtorrent-rpc
Network/RTorrent/Action/Internals.hs
mit
5,292
0
18
1,533
1,714
891
823
-1
-1
{-# LANGUAGE OverloadedStrings #-} import System.FilePath import System.IO.Temp import Test.Tasty import Test.Tasty.HUnit import qualified Data.ByteString.Char8 as BC8 import qualified Data.Sequence as Seq import System.Directory.Watchman.Fields import System.Directory.Watchman.Query import System.Directory.Watchman.Subscribe import System.Directory.Watchman.WFilePath import System.Directory.Watchman.WatchmanServer import qualified System.Directory.Watchman as Watchman import qualified System.Directory.Watchman.Expression as Expr tests :: TestTree tests = testGroup "Tests" [ testCase "test_watchmanServer" test_watchmanServer , testCase "test_version" test_version , testCase "test_watchList" test_watchList , testCase "test_query1" test_query1 , testCase "test_subscribe" test_subscribe ] main :: IO () main = defaultMain $ tests test_watchmanServer :: Assertion test_watchmanServer = withWatchmanServer Nothing (const $ pure ()) test_version :: Assertion test_version = withWatchmanServer Nothing $ \sockFile -> do Watchman.WatchmanVersion v <- Watchman.version sockFile assertBool "Version string not empty" (not (null v)) test_watchList :: Assertion test_watchList = withWatchmanServer Nothing $ \sockFile -> do withSystemTempDirectory "watchman_test" $ \tmpDir -> do let watchDir = WFilePath (BC8.pack tmpDir) _ <- Watchman.watch sockFile watchDir watchDirs <- Watchman.watchList sockFile watchDirs @?= [watchDir] test_query1 :: Assertion test_query1 = withWatchmanServer Nothing $ \sockFile -> do withSystemTempDirectory "watchman_test" $ \tmpDir -> do let watchDir = WFilePath (BC8.pack tmpDir) _ <- Watchman.watch sockFile watchDir BC8.writeFile (tmpDir </> "blah.txt") "blah" qr <- Watchman.query sockFile watchDir [] Expr.true [] [FLname] _QueryResult_Files qr @?= Seq.fromList [[Fname (WFilePath "blah.txt")]] pure () test_subscribe :: Assertion test_subscribe = withWatchmanServer Nothing $ \sockFile -> do withSystemTempDirectory "watchman_test" $ \tmpDir -> do BC8.writeFile (tmpDir </> "foo.txt") "foo" let watchDir = WFilePath (BC8.pack tmpDir) _ <- Watchman.watch sockFile watchDir Watchman.withConnect sockFile $ \sock -> do subscription <- Watchman.subscribe sock watchDir (SubscriptionName "sub1") Expr.true [] [FLname, FLexists] initialMessage <- Watchman.readNotification subscription case initialMessage of Subscription_Files files -> do _SubscriptionFiles_Files files @?= Seq.fromList [[Fname (WFilePath "foo.txt"), Fexists True]] x -> assertFailure $ "Unexpected notification: " ++ show x BC8.writeFile (tmpDir </> "blah.txt") "blah" notification <- Watchman.readNotification subscription case notification of Subscription_Files files -> do _SubscriptionFiles_Files files @?= Seq.fromList [[Fname (WFilePath "blah.txt"), Fexists True]] x -> assertFailure $ "Unexpected notification: " ++ show x
bitc/hs-watchman
tests/test.hs
mit
3,169
0
28
657
827
417
410
64
3
module Main where import Game.Mahjong.Wall main :: IO () main = do wall <- randomWall Include print wall
gspindles/mj-score-eval
app/Main.hs
mit
111
0
8
24
41
21
20
6
1
{-# LANGUAGE OverloadedStrings #-} module Handler.Fay where import Fay.Convert (readFromFay) import Data.List (nub, head) import Import hiding (pack, head, concat, threadDelay) import Yesod.Fay import Database.Persist.Sql import Data.Text (pack, concat) import Cache import Data.ByteString.Base64 (decodeLenient) import System.Random import Control.Concurrent (threadDelay) import Form import SessionState import Data.Time.Clock (getCurrentTime) onCommand :: CommandHandler App onCommand render command = do c <- getCache case readFromFay command of Just (AModel "" r) -> render r [] Just (AModel i r) -> do let k = toSqlKey $ fromIntegral $ parseDefInt i 0 m = filter ((==k) . modelMarkId . entityVal) $ getModels c render r $ fmap modelToFront m Just (AAge "" r) -> render r [] Just (AAge i r) -> do let k = toSqlKey $ fromIntegral $ parseDefInt i 0 m = nub $ fmap (lkModelAgeAgeId . entityVal) $ filter ((==k) . lkModelAgeModelId . entityVal) $ getLkModelAges c a :: [Entity Age] a = filter (\x -> elem (entityKey $ x) m) $ getAges c render r $ fmap ageToFront a Just (AGen (m,a) r) -> do case or $ fmap (=="") [m,a] of True -> render r [] False -> do let km = (toSqlKey . fromIntegral . \x -> parseDefInt x 0) m ka = (toSqlKey . fromIntegral . \x -> parseDefInt x 0) a lma = nub . filter ((==km) . lkModelAgeModelId . entityVal) . filter ((==ka) . lkModelAgeAgeId . entityVal) $ getLkModelAges c stat = case null lma of True -> [] False -> let stat2 = lkModelAgeMultiple . entityVal . head $ lma age = ageAge . entityVal $ head $ filter ((==ka) . entityKey) $ getAges c gen2 = filter ((>= age) . fromJustInt . generationTopAge . entityVal) . filter ((<= age) . fromJustInt . generationBottomAge . entityVal) $ gen in if (stat2 == False) then [] else (nub $ fmap generationToFront gen2) gen = filter ((==km) . generationModelId . entityVal) $ getGenerations c render r stat Just (LkAdd (Nothing,_) r) -> render r Nothing Just (LkAdd (_,Nothing) r) -> render r Nothing Just (LkAdd (Just i,Just ta) r) -> do let k = toSqlKey $ fromIntegral i (g:_) = filter ((==k) . entityKey) $ getGenerations c tak = toSqlKey $ fromIntegral ta _ <- runDB $ insertUnique $ LkTag tak k (ma,mo,ge) <- runDB $ do (ge':_) <- selectList [GenerationId ==. k] [LimitTo 1] (mo':_) <- selectList [ModelId ==. (generationModelId . entityVal $ ge')] [LimitTo 1] (ma':_) <- selectList [MarkId ==. (generationMarkId . entityVal $ ge')] [LimitTo 1] return (ma',mo',ge') runDB $ update tak [TextAdviseName =. (showQueryGen ma mo ge)] render r $ Just ( pack $ show i , fromJustText . generationGeneration . entityVal $ g , textFromJustInt . generationBottomAge . entityVal $ g , textFromJustInt . generationTopAge . entityVal $ g) Just (LkDel (Nothing,_) r) -> render r False Just (LkDel (_,Nothing) r) -> render r False Just (LkDel (Just i, Just ta) r) -> do runDB $ deleteWhere [ LkTagTextAdviseId ==. (toSqlKey $ fromIntegral ta) , LkTagGeneration ==. (toSqlKey $ fromIntegral i) ] render r True Just (ImgAdd (Nothing,_) r) -> render r [] Just (ImgAdd (_,[]) r) -> render r [] Just (ImgAdd (Just i,is) r) -> do let files = fmap processFileFromText is fnames <- liftIO $ mapM writeToServer files let images = fmap (flip toImage (toSqlKey $ fromIntegral i)) fnames runDB $ mapM_ insert_ images render r $ fmap imgToFront images Just (ImgDel Nothing r) -> render r False Just (ImgDel (Just i) r) -> do runDB $ deleteWhere [ ImageId ==. (toSqlKey $ fromIntegral i) ] render r True Just (ReqAdd (IR3 ge em) r) -> do let gen = selectGeneration c ge t <- liftIO $ getCurrentTime runDB $ insert_ $ NewAdvice em gen t render r True Just (PAdd p@(PRInsert k v d) r) -> do p' <- runDB $ selectList [AsPropertyK ==. k] [LimitTo 1] if null p' then do _ <- runDB $ insertUnique $ AsProperty k v d render r $ Just p else render r Nothing Just (PUpd (PRUpdate k v) r) -> do runDB $ updateWhere [AsPropertyId ==. (toSqlKey $ fromIntegral $ parseDefInt k 0)] [AsPropertyV =. v] render r False Just (PriceMatrix prices r) -> do let validatedPrices = filter validated $ fmap validate prices insertPrice (PriceV v s h _) = runDB $ do k <- insertObj v 3 insertRef 1 k (toSqlKey . fromIntegral $ s) insertRef 2 k (toSqlKey . fromIntegral $ h) insertRef atr obj ref = insert_ $ AsParam (toSqlKey atr) obj Nothing Nothing (Just ref) insertObj nam typ = insert $ AsObject (pack . show $ nam) (toSqlKey typ) Nothing Nothing 0 logMessage $ pack . show $ length $ validatedPrices runDB $ do ps <- selectList [AsObjectT ==. (toSqlKey 3)] [] let kps = fmap entityKey ps deleteWhere [AsParamAo <-. kps] deleteWhere [AsParamAr <-. (fmap return kps)] deleteWhere [AsObjectId <-. kps] mapM_ insertPrice validatedPrices render r True Nothing -> invalidArgs ["Invalid command"] fromJustInt :: Maybe Int -> Int fromJustInt Nothing = 1900 fromJustInt (Just a) = a fromJustText :: Maybe Text -> Text fromJustText Nothing = "I" fromJustText (Just a) = a textFromJustInt :: Maybe Int -> Text textFromJustInt Nothing = "-" textFromJustInt (Just a) = pack . show $ a processFileFromText :: Text -> ByteString processFileFromText = decodeLenient . encodeUtf8 . drop 1 . dropWhile (/= ',') writeToServer :: ByteString -> IO Text writeToServer content = do name <- randomName let fname = "cdn/img/" <> name <> ".png" writeFile (unpack fname) content return $ "/" <> fname toImage :: Text -> Key TextAdvise -> Image toImage url ta = Image url ta imgToFront :: Image -> (Text,Text) imgToFront (Image url gen) = (pack . show . fromSqlKey $ gen, url) randomName :: IO Text randomName = do threadDelay 1000000 t <- getCurrentTime return $ pack . take 10 $ randomRs ('a','z') $ mkStdGen (parseInt $ pack $ formatTime defaultTimeLocale "%s" t) chooseGeneration :: Text -> Text -> Text -> HandlerT App IO (Key Generation) chooseGeneration g y m = do c <- getCache let models = filter (byKey mo . entityKey) $ getModels c gens = getGenerations c ages = getAges c ge = parseInt g ye = parseInt y mo = parseInt m gs = case ge of 0 -> let currentAge = head $ fmap (ageAge . entityVal) $ filter (byKey ye . entityKey) $ ages currentGens = filter (byKey mo . generationModelId . entityVal) gens in filter ((<= (Just currentAge)) . generationBottomAge . entityVal) $ filter ((>= (Just currentAge)) . generationTopAge . entityVal) currentGens _ -> filter (byKey ge . entityKey) gens return $ entityKey $ head gs selectGeneration c ge = entityKey $ head $ filter (byKey (parseInt ge) . entityKey) (getGenerations c) validate :: Price -> PriceV validate (Price v s h) = if and [isMaybe s, isMaybe h, isDouble v] then PriceV (parseDouble v) (safeFromJust 0 s) (safeFromJust 0 h) True else PriceV 0.0 0 0 False
swamp-agr/carbuyer-advisor
Handler/Fay.hs
mit
8,218
85
29
2,752
2,865
1,457
1,408
176
25
{-# LANGUAGE OverloadedStrings #-} module Qwu.DB.Test where import Qwu.DB.Manipulation import Qwu.DB.Table.Account import Qwu.DB.Table.Post import Data.Default import Data.Text import Data.UUID as U testCreatePost :: IO () testCreatePost = createPost (def :: Post) U.nil testUpdatePostBody :: PostId -> IO () testUpdatePostBody = updatePostBody "updated" testUpdateAccountUsername :: IO () testUpdateAccountUsername = updateAccountUsername "updatedUsername" U.nil testUpdateAccountEmail :: IO () testUpdateAccountEmail = updateAccountEmail "updatedEmail" U.nil testUpdateAccountPassword :: IO () testUpdateAccountPassword = updateAccountPassword "updatedPassword" U.nil testCreateAccount :: IO () testCreateAccount = createAccount (def :: Account) testWithAccount :: (UUID -> IO ()) -> String -> IO () testWithAccount action accountIdStr = case U.fromString accountIdStr of Just accountId -> action accountId Nothing -> action U.nil testDeleteAccount :: IO () testDeleteAccount = deleteAccount U.nil
bryangarza/qwu
src/Qwu/DB/Test.hs
mit
1,027
0
9
142
277
147
130
27
2
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.ElementCSSInlineStyle (getStyle, ElementCSSInlineStyle(..), gTypeElementCSSInlineStyle, IsElementCSSInlineStyle, toElementCSSInlineStyle) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle.style Mozilla ElementCSSInlineStyle.style documentation> getStyle :: (MonadDOM m, IsElementCSSInlineStyle self) => self -> m CSSStyleDeclaration getStyle self = liftDOM (((toElementCSSInlineStyle self) ^. js "style") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/ElementCSSInlineStyle.hs
mit
1,460
0
11
193
363
234
129
26
1
-- JsonPretty.hs -- A pretty printer tool for JSON data -- -- vim: ft=haskell sw=2 ts=2 et -- -- Taken from the Haskell tutorial: -- http://funktionale-programmierung.de/2014/10/23/haskell-einstieg-3.html {-# OPTIONS_GHC -F -pgmF htfpp #-} {-# LANGUAGE OverloadedStrings #-} import qualified Data.Aeson as J import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.ByteString as BS import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import qualified Data.Vector as V import Data.Maybe import Text.PrettyPrint import Test.Framework import System.IO import System.Environment import System.Exit -- use Text class for JSON paths type JsonPath = [T.Text] -- filter a given path from a JSON hierarchy filterJson :: JsonPath -> J.Value -> Maybe J.Value filterJson path json = case path of [] -> Just json (p:ps) -> case json of J.Object m -> case HashMap.lookup p m of Nothing -> Nothing Just v -> filterJson ps v J.Array arr -> let newArr = V.fromList (mapMaybe (filterJson path) (V.toList arr)) in Just (J.Array newArr) _ -> Nothing -- format JSON value tree prettyJson :: J.Value -> Doc prettyJson json = case json of J.Object m -> let elems = map prettyKv (HashMap.toList m) in braces (prettyList elems) J.Array arr -> let elems = map prettyJson (V.toList arr) in brackets (prettyList elems) J.String t -> prettyString t J.Number n -> text (show n) J.Bool b -> text (if b then "true" else "false") J.Null -> text "null" where prettyList l = nest 1 (vcat (punctuate comma l)) prettyKv (k, v) = let combine x y = if isStructured v then x $$ (nest 1 y) else x <+> y in (prettyString k Text.PrettyPrint.<> text ":") `combine` prettyJson v prettyString t = text (show t) isStructured json = case json of J.Object _ -> True J.Array _ -> True _ -> False -- read, parse and pretty print JSON processFile :: JsonPath -> FilePath -> IO () processFile filter file = if file == "-" then action stdin else withFile file ReadMode action where action handle = do bytes <- BS.hGetContents handle case J.decodeStrict bytes of Just v -> case filterJson filter v of Nothing -> return () Just outV -> putStrLn (show (prettyJson outV)) Nothing -> hPutStrLn stderr ("Error parsing JSON from " ++ file) -- main entry point & argument parser main :: IO () main = do args <- getArgs if ("--help" `elem` args || "-h" `elem` args) then usage else return () case args of "--test":rest -> runTests rest "--filter":filter:files -> doWork (parseFilter filter) files "--filter":[] -> usage files -> doWork [] files where parseFilter :: String -> JsonPath parseFilter str = T.splitOn "." (T.pack str) usage :: IO a usage = do hPutStrLn stderr ("USAGE: jsonpp [--test] [--filter EXPR] [FILE..]") exitWith (ExitFailure 1) doWork :: JsonPath -> [FilePath] -> IO () doWork filter files = if null files then processFile filter "-" else mapM_ (processFile filter) files runTests :: [String] -> IO () runTests args = htfMainWithArgs args htf_thisModulesTests -- -- Tests -- test_filterJson = do assertEqual (Just $ unsafeParseJson "[36, 23]") (filterJson ["age"] sampleJson) assertEqual (Just $ unsafeParseJson "[\"Stefan\"]") (filterJson ["name", "first"] sampleJson) assertEqual Nothing (filterJson ["name"] (J.Number 42)) assertEqual (Just sampleJson) (filterJson [] sampleJson) unsafeParseJson :: T.Text -> J.Value unsafeParseJson t = case J.decodeStrict (T.encodeUtf8 t) of Just v -> v Nothing -> error ("Could not parse JSON: " ++ T.unpack t) sampleJson :: J.Value sampleJson = unsafeParseJson (T.concat ["[{\"name\": {\"first\": \"Stefan\", \"last\": \"Wehr\"}, \"age\": 36},", " {\"name\": \"Max\", \"age\": 23}]"]) test_prettyJson = do assertEqual expected (show (prettyJson sampleJson)) where expected = ("[{\"age\": 36.0,\n" ++ " \"name\":\n" ++ " {\"first\": \"Stefan\",\n" ++ " \"last\": \"Wehr\"}},\n" ++ " {\"age\": 23.0,\n" ++ " \"name\": \"Max\"}]")
kkirstein/proglang-playground
Haskell/src/JsonPretty.hs
mit
4,512
7
20
1,217
1,303
674
629
116
10
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift Compiler (0.9.0) -- -- -- -- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING -- ----------------------------------------------------------------- module Database.HBase.HBase_Consts where import Prelude ( Bool(..), Enum, Double, String, Maybe(..), Eq, Show, Ord, return, length, IO, fromIntegral, fromEnum, toEnum, (.), (&&), (||), (==), (++), ($), (-) ) import Control.Exception import Data.ByteString.Lazy import Data.Hashable import Data.Int import Data.Text.Lazy ( Text ) import qualified Data.Text.Lazy as TL import Data.Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import Thrift import Thrift.Types () import Database.HBase.Internal.Thrift2.HBase_Types
danplubell/hbase-haskell
src/Database/HBase/Internal/Thrift2/HBase_Consts.hs
mit
1,298
0
6
265
204
147
57
25
0
module Model.Event where import Import import qualified Data.Text as T getEvents :: Day -> Day -> DB [Entity Event] getEvents start end = selectList ( [EventStartDate >=. start, EventStartDate <=. end] ||. [EventEndDate >=. Just start, EventEndDate <=. Just end] ) [Desc EventStartDate] getEventsDay :: Day -> DB [Entity Event] getEventsDay day = selectList ( [EventStartDate ==. day] ||. [EventStartDate <. day, EventEndDate >=. Just day] ) [Desc EventStartDate] toParagraphs :: Event -> [Text] toParagraphs event = (T.splitOn "\r\n\r\n") $ unTextarea $ eventContent event
isankadn/yesod-testweb-full
Model/Event.hs
mit
610
0
10
120
208
110
98
17
1
module HigherOrder where import Data.List (sort) -- Exercise 1: Wholemeal programming -- fun1 :: [Integer] -> Integer -- fun1 [] = 1 -- fun1 (x:xs) -- | even x = (x - 2) * fun1 xs -- | otherwise = fun1 xs fun1' :: [Integer] -> Integer fun1' = product . subtract2 . evensOnly evensOnly :: [Integer] -> [Integer] evensOnly = filter even subtract2 :: [Integer] -> [Integer] subtract2 = map (\x -> x - 2) -- fun2 :: Integer -> Integer -- fun2 1 = 0 -- fun2 n | even n = n + fun2 (n `div` 2) -- | otherwise = fun2 (3 * n + 1) fun2' :: Integer -> Integer fun2' 1 = 0 fun2' n | even n = n + (fun2' . intDivBy2) n | otherwise = (fun2' . add1 . multiplyBy3) n intDivBy2 :: Integer -> Integer intDivBy2 n = n `div` 2 add1 :: Integer -> Integer add1 = (+ 1) multiplyBy3 :: Integer -> Integer multiplyBy3 = (* 3) -- Exercise 2: Folding with trees data Tree a = Leaf | Node Int (Tree a) a (Tree a) deriving (Show, Eq) foldTree :: Ord a => [a] -> Tree a foldTree = buildTree . sort buildTree :: [a] -> Tree a buildTree xs = build xs 0 (length xs) where build :: [a] -> Int -> Int -> Tree a build ys mn mx | mn >= mx = Leaf | otherwise = Node level ltree node rtree where mdn = mn + (mx - mn) `div` 2 level = nearestPowerOf2 (mx-mn) ltree = build ys mn mdn node = head (drop mdn ys) rtree = build ys mdn mx nearestPowerOf2 :: Int -> Int nearestPowerOf2 = nearest 2 where nearest :: Int -> Int -> Int nearest p n | p > n = p | otherwise = nearest (2*p) n -- Exercise 3: More folds! xor :: [Bool] -> Bool xor = odd . length . foldr (\x acc -> if x then x:acc else acc) [] map' :: (a -> b) -> [a] -> [b] map' f = foldr (\x acc -> f x:acc) []
slogsdon/haskell-exercises
cis194/HigherOrder.hs
mit
1,820
0
12
554
677
364
313
44
2
module Euler.E70 where import Data.List ( sort ) import Euler.Lib ( totient , intToList , primes ) -- Note: it looks like we have the best values of the totient for semiprimes -- (i.e. the product of two primes), as phi(p*q)=phi(p)*phi(q) if they are -- different, and phi(p^2)=p*(p-1) otherwise -- Tactics: compute the full list of semiprimes (since we have an efficient -- prime list) and test only those. -- Updated tactics: he computing of the products of all semiprimes is far too -- long for 60 seconds; we will instead take a set of all integers and remove -- all multiples of semiprimes -- Herm, maybe the value is highest for primes? -- Okay, so this is the highest for a prime (phi(p) = p-1), but we need the -- permutations anyway. -- When limited to 1,000,000, we get 783,169, with totient 781,396, which is the -- product of 827 and 947 (i.e. a semiprime). -- We know that phi(s) = (p-1)-q-1), for s = p*q, p and q primes. -- We can perhaps compute the totient for semiprimes based on close primes? euler70 :: Int -> Int euler70 n = snd $ last $ getPerms 5 $ takeWhile (<n) $ primes -- [ 1 .. n ] -- initial value is five, as it appears to be easy to best (see Wikipedia -- article "Euler's totient function"). semiPrimeThreshold :: Double semiPrimeThreshold = 0.8 genSemiPrimes :: Int -> [Int] genSemiPrimes b = ps where ps = takeWhile (< floor ( (sqrt $ fromIntegral b) / semiPrimeThreshold)) $ primes getPerms :: Double -> [Int] -> [(Double, Int)] getPerms _ [] = [] getPerms r (x:xs) -- TODO: we need to not compute the totients as much as possible -- | r' > r = os -- if we exceed the stored ratio, do not bother to check | isValid x t = (r', x) : os' | otherwise = os where t = x-1 --t = totient x r' = q x t os = getPerms r xs os' = getPerms r' xs isValid :: Int -> Int -> Bool isValid x t = (sort $ intToList x) == (sort $ intToList t) q :: Int -> Int -> Double q n t = (fromIntegral n) / (fromIntegral t) main :: IO () main = print $ euler70 10000000
D4r1/project-euler
Euler/E70.hs
mit
2,020
8
15
436
407
225
182
29
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} {-| Module : Datatypes Description : SODA Datatypes Copyright : (c) Steven W License : MIT Maintainer : Steven W <[email protected]> Stability : Unstable These are Haskell types which represent SoQL query types as described on the <https://dev.socrata.com/docs/datatypes Datatypes page> in the SODA documentation. Geographic values displayed plainly (like in a simple filter or where clause comparison) is displayed in <https://en.wikipedia.org/wiki/Well-known_text Well-known Text (WKT)>. -} module Datatypes ( UrlParam , SodaError (BadLower) , SodaExpr (toUrlParam, lower) , Expr (Expr) , getVal , exprUrlParam , Column (Column) , SodaVal (SodaVal) , SodaType -- * Extra typeclasses for constraints , SodaNumeric , SodaPseudoNumeric , SodaOrd , SodaGeo , SodaSimplifyGeo -- * Haskell types corresponding to SODA Types , Checkbox , Money (..) , SodaNum (..) , SodaText , Timestamp , Point (..) , MultiPoint , Location , Line (..) , MultiLine , Polygon (..) , MultiPolygon ) where import Data.List import Data.Time.Calendar import Data.Time.Clock import Data.Time.Format -- Improve -- |Indicates what has been interpreted to be put into a URL. The name could possibly use some improvement. type UrlParam = String -- Replace Misc with actual things later data SodaError = BadLower | Misc deriving (Eq, Show) -- Maybe make an exportable super or sub typeclass so they can use toUrlParam but can't create any instances of type. -- |The class of all things that can represent a SODA query level type. These include concrete values, columns, and SODA functions. --class Eq m => SodaExpr m where class SodaExpr m where toUrlParam :: m a -> UrlParam lower :: (SodaType a) => m a -> Either SodaError a -- This makes it even more verbose, but I'm trying to just make it work initially. -- |Some types require their input to have the type constructor be anonymized. This existential type does just that. data Expr expr where Expr :: (SodaExpr m, SodaType a) => m a -> Expr a --deriving instance Eq a => Eq (Expr a) -- instance SodaType a => Eq (Expr a) where -- (==) (Expr a) (Expr b) = a == b instance SodaType a => Show (Expr a) where show (Expr a) = toUrlParam a getVal :: (SodaType a) => Expr a -> Either SodaError a getVal (Expr a) = lower a exprUrlParam :: (SodaType a) => Expr a -> UrlParam exprUrlParam (Expr (expr)) = toUrlParam expr -- |The type representing a column. The value it holds is just a string of the column's name, but this GADT also carries around information about the type of the column at the query level. data Column sodatype where Column :: (SodaType sodatype) => String -> Column sodatype instance Eq (Column a) where (==) (Column nameA) (Column nameB) = nameA == nameB instance SodaExpr Column where toUrlParam (Column name) = name lower col = Left BadLower -- |A class of all of the Haskell types which correspond with types that SODA uses. class (Eq sodatype) => SodaType sodatype where toUrlPart :: sodatype -> UrlParam -- |This type just allows us to be able to have Haskell values with Haskell types that correspond with SODA types be able to interact with other SODA expressions like columns and SODA functions. data SodaVal datatype where SodaVal :: (SodaType a) => a -> SodaVal a instance Eq (SodaVal a) where (==) (SodaVal a) (SodaVal b) = a == b instance SodaExpr SodaVal where toUrlParam (SodaVal val) = toUrlPart val lower (SodaVal a) = Right a -- Possibly differentiate this and SodaNum more. -- |Not to be confused with SodaNum, this is a class with Doubles, Number, and Money in it because these three types can interact. class (SodaType a) => SodaNumeric a -- |I'll admit, I named this one this way for the wordplay. This class has Doubles, Number, Money, Timestamp, and SodaText. It's used in Min, Max, and Sum. class (SodaType a) => SodaPseudoNumeric a class (SodaType a) => SodaOrd a -- |For the different geometric SodaTypes. class (SodaType a) => SodaGeo a -- |Just for the functions simplify and simplify_preserve_topology. class (SodaType a) => SodaSimplifyGeo a -- |The type that corresponds with <https://dev.socrata.com/docs/datatypes/checkbox.html SODA's Checkbox type>. It is the basic ternary type with Nothing as null. type Checkbox = Maybe Bool instance SodaType (Maybe Bool) where toUrlPart Nothing = "null" toUrlPart (Just True) = "true" toUrlPart (Just False) = "false" -- |The type that corresponds with <https://dev.socrata.com/docs/datatypes/money.html SODA's Money type>. The precision beyond the hundreths place doesn't make sense for how most currecies, including the U.S. dollar, is represented, but this datatype can represent any currency whose representation's precision is not necessarily restricted to the hundreths place. newtype Money = Money { getMoney :: Double } deriving (Show, Eq) instance SodaType Money where toUrlPart m = "'" ++ (show . getMoney $ m) ++ "'" instance SodaNumeric Money instance SodaPseudoNumeric Money instance SodaOrd Money -- |The type that corresponds with <https://dev.socrata.com/docs/datatypes/double.html SODA's Double type>, is just a Haskell Double type. instance SodaType Double where toUrlPart = show instance SodaNumeric Double instance SodaPseudoNumeric Double instance SodaOrd Double -- |The type that corresponds with <https://dev.socrata.com/docs/datatypes/double.html SODA's Number type>. Number is actually supposed to have arbitrary precision, and is a bit repetative as a double since we already have double, but I wasn't exactly sure how to implement it. We'll have to look around for true arbitrary precision Haskell types. newtype SodaNum = SodaNum { getSodaNum :: Double } deriving (Show, Eq) instance SodaType SodaNum where toUrlPart n = (show $ getSodaNum n) instance SodaNumeric SodaNum instance SodaPseudoNumeric SodaNum instance SodaOrd SodaNum -- |The type that corresponds with <https://dev.socrata.com/docs/datatypes/text.html SODA's Text type>. The difference in the name of the Haskell type and the SODA type is to prevent collisions and confusion with the more popular Haskell Text type. type SodaText = String instance SodaType SodaText where toUrlPart t = let aposFinder '\'' accum = '\'' : '\'' : accum aposFinder char accum = char : accum in "'" ++ foldr aposFinder "" t ++ "'" instance SodaOrd SodaText -- Cuts off instead of rounding because I have no idea of a good way to handle rounding things like 999.9 milliseconds. If anyone has any better idea of how to handle this, let me know. I suppose I could test and see if the API will handle greater precision, even if it doesn't use it. -- |The type that corresponds with <https://dev.socrata.com/docs/datatypes/floating_timestamp.html SODA's Floating Timestamp Type>. The name is a bit different because floating timestamp seemed a bit long. The precision and rounding of this type need improvement. type Timestamp = UTCTime instance SodaType Timestamp where toUrlPart t = (formatTime defaultTimeLocale tsFormat t) ++ "." ++ ms where tsFormat = iso8601DateFormat (Just "%T") ms = take 3 $ formatTime defaultTimeLocale "%q" t instance SodaPseudoNumeric Timestamp instance SodaOrd Timestamp -- I'm actually not completely sure of the precision required here. -- Perhaps rename to Position and then have point as a type synonym (since I think that is semantically more correct). -- Might also want to shorten fields to long and lat or something. -- |The type that corresponds with <https://dev.socrata.com/docs/datatypes/point.html SODA's Point Type>. I didn't make it a simple tuple because the order of the longitude and latitude differ a bit in places. Also, this is a bit more descriptive. data Point = Point { longitude :: Double , latitude :: Double } deriving (Show, Eq) instance SodaType Point where toUrlPart point = "'POINT (" ++ (pointUPart point) ++ ")'" instance SodaGeo Point -- This has an alternate WKT format. Have to test it out. -- |The type that Corresponds with <https://dev.socrata.com/docs/datatypes/multipoint.html SODA's Multipoint type>. type MultiPoint = [Point] instance SodaType MultiPoint where toUrlPart points = "'MULTIPOINT " ++ (pointsUPart points) ++ "'" -- Possibly restrict the values used for these. -- Since the constructor for location is currently not exported, there's currently no reason to export this. -- |Used as part of the Location type. data USAddress = USAddress { address :: String , city :: String , state :: String , zipCode :: String } deriving (Show, Eq) -- Use record syntax? -- One of the developers said on stack overflow that there is no representation for location types in things like a simple filter. -- Since we're not exporting the constructor and it isn't ever used, then the type definition doesn't really matter. -- |Corresponds with <https://dev.socrata.com/docs/datatypes/location.html SODA's Location type>. According to the SODA documentation, location is a legacy datatype so it is discouraged from being used and some SODA functions available for the point datatype are not available for the location datatype. The constructor is not exported because there the library currently doesn't know how to represent them in the URL data Location = Location (Maybe Point) (Maybe USAddress) deriving (Show, Eq) instance SodaType Location where toUrlPart _ = "" instance SodaGeo Location -- The only difference in the data structure of Line and Multipoint is that Line has to have at least two positions/points in them -- |Corresponds with <https://dev.socrata.com/docs/datatypes/line.html SODA's Line type>. newtype Line = Line { getLinePoints :: [Point] } deriving (Show, Eq) instance SodaType Line where toUrlPart (Line points) = "'LINESTRING " ++ (pointsUPart points) ++ "'" instance SodaGeo Line instance SodaSimplifyGeo Line -- |Corresponds with <https://dev.socrata.com/docs/datatypes/multiline.html SODA's Multiline type>. type MultiLine = [Line] instance SodaType MultiLine where toUrlPart lines = "'MULTILINESTRING " ++ (linesUPart $ map getLinePoints lines) ++ "'" instance SodaGeo MultiLine instance SodaSimplifyGeo MultiLine -- |Corresponds with <https://dev.socrata.com/docs/datatypes/polygon.html SODA's Polygon type>. newtype Polygon = Polygon { getPolyPoints :: [[Point]] } deriving (Show, Eq) instance SodaType Polygon where toUrlPart (Polygon lines) = "'POLYGON " ++ (linesUPart lines) ++ "'" instance SodaGeo Polygon instance SodaSimplifyGeo Polygon -- |Corresponds with <https://dev.socrata.com/docs/datatypes/multipolygon.html SODA's Multipolygon type>. type MultiPolygon = [Polygon] instance SodaType MultiPolygon where toUrlPart polygons = "'MULTIPOLYGON (" ++ (intercalate ", " $ map (linesUPart . getPolyPoints) polygons) ++ ")'" instance SodaGeo MultiPolygon instance SodaSimplifyGeo MultiPolygon -- TODO Bad name. Improve. -- |Utility function pointUPart :: Point -> UrlParam pointUPart (Point long lat) = (show long) ++ " " ++ (show lat) -- TODO Similarly bad name -- |Utility function pointsUPart :: [Point] -> UrlParam pointsUPart points = "(" ++ (intercalate ", " $ map pointUPart points) ++ ")" -- |Utility function linesUPart :: [[Point]] -> UrlParam linesUPart lines = "(" ++ (intercalate ", " $ map pointsUPart lines) ++ ")"
StevenWInfo/haskell-soda
src/Datatypes.hs
mit
11,751
0
12
2,271
1,796
981
815
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloud9-environmentec2-repository.html module Stratosphere.ResourceProperties.Cloud9EnvironmentEC2Repository where import Stratosphere.ResourceImports -- | Full data type definition for Cloud9EnvironmentEC2Repository. See -- 'cloud9EnvironmentEC2Repository' for a more convenient constructor. data Cloud9EnvironmentEC2Repository = Cloud9EnvironmentEC2Repository { _cloud9EnvironmentEC2RepositoryPathComponent :: Val Text , _cloud9EnvironmentEC2RepositoryRepositoryUrl :: Val Text } deriving (Show, Eq) instance ToJSON Cloud9EnvironmentEC2Repository where toJSON Cloud9EnvironmentEC2Repository{..} = object $ catMaybes [ (Just . ("PathComponent",) . toJSON) _cloud9EnvironmentEC2RepositoryPathComponent , (Just . ("RepositoryUrl",) . toJSON) _cloud9EnvironmentEC2RepositoryRepositoryUrl ] -- | Constructor for 'Cloud9EnvironmentEC2Repository' containing required -- fields as arguments. cloud9EnvironmentEC2Repository :: Val Text -- ^ 'ceecrPathComponent' -> Val Text -- ^ 'ceecrRepositoryUrl' -> Cloud9EnvironmentEC2Repository cloud9EnvironmentEC2Repository pathComponentarg repositoryUrlarg = Cloud9EnvironmentEC2Repository { _cloud9EnvironmentEC2RepositoryPathComponent = pathComponentarg , _cloud9EnvironmentEC2RepositoryRepositoryUrl = repositoryUrlarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloud9-environmentec2-repository.html#cfn-cloud9-environmentec2-repository-pathcomponent ceecrPathComponent :: Lens' Cloud9EnvironmentEC2Repository (Val Text) ceecrPathComponent = lens _cloud9EnvironmentEC2RepositoryPathComponent (\s a -> s { _cloud9EnvironmentEC2RepositoryPathComponent = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloud9-environmentec2-repository.html#cfn-cloud9-environmentec2-repository-repositoryurl ceecrRepositoryUrl :: Lens' Cloud9EnvironmentEC2Repository (Val Text) ceecrRepositoryUrl = lens _cloud9EnvironmentEC2RepositoryRepositoryUrl (\s a -> s { _cloud9EnvironmentEC2RepositoryRepositoryUrl = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/Cloud9EnvironmentEC2Repository.hs
mit
2,274
0
13
220
265
151
114
29
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} module Main where import Data.IORef import Data.List import System.Console.CmdArgs import Webcam import Yesod data Opts = Opts { listen :: Int , videoDevice :: [String] , interval :: Int -- ^ refresh interval, seconds } deriving(Show, Data, Typeable) cmdLineOpts :: Opts cmdLineOpts = Opts { listen = 9091 &= help "local port to bind to, defaults to 9091" , videoDevice = [] &= help "video device paths to grab frames from, defaults to /dev/video*" , interval = 3 &= help "refresh interval (seconds), defaults to 3" } &= program "www-webcam-snapshot" &= summary "Periodically grabs frames from attached USB webcams and serves them as JPG." &= help "Usage: www-webcam-snapshot [--listen 1234] [--video-device /dev/video0] [--video-device /dev/video1]" data App = App { webcamImages :: [WebcamImage] , refreshInterval :: Int -- ^ seconds } mkYesod "App" [parseRoutes| / HomeR GET /#WebcamId WebCamR GET |] instance Yesod App where makeSessionBackend _ = return Nothing getHomeR :: Handler Value getHomeR = do App {..} <- getYesod let devices = (flip map) webcamImages $ \WebcamImage{..} -> object [ "id" .= fromEnum webcamId , "path" .= webcamDevice ] returnJson $ object [ "refreshInterval" .= refreshInterval , "devices" .= devices ] getWebCamR :: WebcamId -> Handler Value getWebCamR wid = do App {..} <- getYesod case find ((wid ==) . webcamId) webcamImages of Nothing -> notFound Just WebcamImage{..} -> do ibs <- liftIO $ readIORef imageBytes addHeader "Cache-Control" "public, max-age=3" sendResponse (typeJpeg, toContent ibs) main :: IO () main = do Opts{..} <- cmdArgs cmdLineOpts if (interval <= 0) then error $ "Refresh interval must be > 0!" else return () if (listen <= 0) then error $ "Port number must be > 0!" else return () wis <- startFrameGrabber interval videoDevice warp listen $ App wis interval
andreyk0/www-webcam-snapshot
Main.hs
gpl-2.0
2,432
0
15
707
538
281
257
60
3
{-# LANGUAGE TemplateHaskell #-} module Moonbase.Util.TH ( which , exists ) where import Language.Haskell.TH import Language.Haskell.TH.Quote import Control.Applicative import Data.Bool import Data.Maybe import System.Directory which = QuasiQuoter { quoteExp = \s -> maybe (notFound s) (\path -> [|path|]) =<< runIO (findExecutable s) , quotePat = invalid , quoteDec = invalid , quoteType = invalid } where invalid = error "Can only check for values nothing other" notFound exec = error $ "\n*** ERROR *** Could not find executable `" ++ exec ++"`. Make sure the application is installed correctly\n" exists = QuasiQuoter { quoteExp = \s -> bool (notFound s) [|s|] =<< runIO ((||) <$> doesFileExist s <*> doesDirectoryExist s) , quotePat = invalid , quoteDec = invalid , quoteType = invalid } where invalid = error "Can only check for values nothing other" notFound path = error $ "\n*** ERROR *** File or Directory not found: " ++ path
felixsch/moonbase
src/Moonbase/Util/TH.hs
gpl-3.0
1,062
0
13
275
252
146
106
24
1
{---------------------------------------------------------------------} {- Copyright 2015, 2016 Nathan Bloomfield -} {- -} {- This file is part of Feivel. -} {- -} {- Feivel is free software: you can redistribute it and/or modify -} {- it under the terms of the GNU General Public License version 3, -} {- as published by the Free Software Foundation. -} {- -} {- Feivel 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 Feivel. If not, see <http://www.gnu.org/licenses/>. -} {---------------------------------------------------------------------} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Feivel.Grammar.Type ( Type(..), TypeErr(..), unify, unifyAll, Typed, typeOf, OfType(..) ) where import Carl.String import Carl.Data.ZZMod import Carl.Data.Rat import Carl.Struct.Polynomial import Carl.Struct.Matrix import Data.List (intersperse) import Control.Monad (foldM) import Control.Monad.Instances () {--------------} {- Contents -} {- :Type -} {- :TypeErr -} {--------------} {---------} {- :Type -} {---------} data OfType a = a :# Type deriving (Eq, Show) class Typed t where typeOf :: t -> Type data Type = XX -- Type Variable -- Atomic types | DD -- Doc | ZZ -- Integers | SS -- Strings | BB -- Booleans | QQ -- Rationals -- Parameterized types | ZZMod Integer -- Modular Integers | PermOf Type -- Permutations -- Constructed types | ListOf Type -- Lists | MatOf Type -- Matrices | PolyOver Type -- Polynomials | TupleOf [Type] -- Tuples | MacTo Type -- Macros deriving Eq unify :: Type -> Type -> Either TypeErr Type unify XX t = Right t unify t XX = Right t unify t1 t2 = if t1==t2 then Right t1 else Left $ TypeUnificationError t1 t2 unifyAll :: [Type] -> Either TypeErr Type unifyAll = foldM unify XX instance Show Type where show XX = "x" show DD = "doc" show ZZ = "int" show SS = "str" show BB = "bool" show QQ = "rat" show (ZZMod n) = "mod" ++ show (abs n) show (ListOf t) = "{" ++ show t ++ "}" show (MatOf t) = "[" ++ show t ++ "]" show (PolyOver t) = "^" ++ show t show (PermOf t) = "$" ++ show t show (TupleOf ts) = "(" ++ (concat $ intersperse "," $ map show ts) ++ ")" show (MacTo t) = ">" ++ show t {------------} {- :TypeErr -} {------------} data TypeErr = TypeMismatch Type Type -- expected, received | NumericTypeExpected Type | FieldTypeExpected Type | ListExpected Type | NumericListExpected Type | SortableListExpected Type | MatrixListExpected Type | MacroListExpected Type | ListListExpected Type | MatrixExpected Type | NumericMatrixExpected Type | MacroMatrixExpected Type | ListMatrixExpected Type | FieldMatrixExpected Type | MatrixMatrixExpected Type | MacroExpected Type | SortableExpected Type | PolynomialExpected Type | NumericPolynomialExpected Type | PolynomialListExpected Type | PolynomialMatrixExpected Type | PermutationExpected Type | PermutationListExpected Type | PermutationMatrixExpected Type | ModularIntegerExpected Type | ModularIntegerListExpected Type | ModularIntegerMatrixExpected Type | TypeUnificationError Type Type deriving Eq instance Show TypeErr where show (TypeMismatch ex re) = "An expression of type " ++ show ex ++ " was expected, but this expression has type " ++ show re ++ "." show (NumericTypeExpected u) = "A numeric type was expected, but this expression has type " ++ show u ++ "." show (FieldTypeExpected u) = "A field type was expected, but this expression has type " ++ show u ++ "." show (ListExpected t) = "A list was expected, but this expression has type " ++ show t ++ "." show (NumericListExpected t) = "A numeric list was expected, but this expression has type " ++ show t ++ "." show (SortableListExpected t) = "A sortable list was expected, but this expression has type " ++ show t ++ "." show (MatrixListExpected t) = "A list of matrices was expected, but this expression has type " ++ show t ++ "." show (MacroListExpected t) = "A list of macros was expected, but this expression has type " ++ show t ++ "." show (ListListExpected t) = "A list of lists was expected, but this expression has type " ++ show t ++ "." show (MatrixExpected t) = "A matrix was expected, but this expression has type " ++ show t ++ "." show (NumericMatrixExpected t) = "A numeric matrix was expected, but this expression has type " ++ show t ++ "." show (MacroMatrixExpected t) = "A matrix of macros was expected, but this expression has type " ++ show t ++ "." show (ListMatrixExpected t) = "A matrix of lists was expected, but this expression has type " ++ show t ++ "." show (FieldMatrixExpected t) = "A matrix over a field was expected, but this expression has type " ++ show t ++ "." show (MatrixMatrixExpected t) = "A matrix of matrices was expected, but this expression has type " ++ show t ++ "." show (MacroExpected t) = "A macro was expected, but thus expression has type " ++ show t ++ "." show (SortableExpected t) = "A sortable type was expected, but this expression has type " ++ show t ++ "." show (PolynomialExpected t) = "A polynomial was expected, but this expression has type " ++ show t ++ "." show (NumericPolynomialExpected t) = "A numeric polynomial was expected, but this expression has type " ++ show t ++ "." show (PolynomialListExpected t) = "A list of polynomials was expected, but this expression has type " ++ show t ++ "." show (PolynomialMatrixExpected t) = "A matrix of polynomials was expected, but this expression has type " ++ show t ++ "." show (PermutationExpected t) = "A permutation was expected, but this expression has type " ++ show t ++ "." show (PermutationListExpected t) = "A list of permutations was expected, but this expression has type " ++ show t ++ "." show (PermutationMatrixExpected t) = "A matrix of permutations was expected, but this expression has type " ++ show t ++ "." show (ModularIntegerExpected t) = "A modular integer was expected, but this expression has type " ++ show t ++ "." show (ModularIntegerListExpected t) = "A list of modular integers was expected, but this expression has type " ++ show t ++ "." show (ModularIntegerMatrixExpected t) = "A matrix of modular integers was expected, but this expression has type " ++ show t ++ "." show (TypeUnificationError a b) = "Cannot unify types: " ++ show a ++ " and " ++ show b ++ "." instance Typed Integer where typeOf _ = ZZ instance Typed Text where typeOf _ = SS instance Typed Bool where typeOf _ = BB instance Typed Rat where typeOf _ = QQ instance Typed ZZModulo where typeOf (ZZModulo _ n) = ZZMod n instance (Typed a) => Typed (Poly VarString a) where typeOf x = case getCoefficients x of (c:_) -> PolyOver (typeOf c) [] -> PolyOver XX instance (Typed a) => Typed (Matrix a) where typeOf x = case toListM x of (a:_) -> MatOf (typeOf a) [] -> MatOf XX instance (Typed a) => Typed [a] where typeOf (x:_) = typeOf x typeOf [] = XX
nbloomf/feivel
src/Feivel/Grammar/Type.hs
gpl-3.0
8,023
0
11
2,197
1,761
924
837
156
2
import Test.Tasty import Test.Tasty.Golden import System.IO.Silently (capture_) import Data.ByteString.Lazy.Char8 (pack) import Evaluator (runBfNoLog) import Parser (parseBfFile) main :: IO () main = defaultMain golden golden :: TestTree golden = testGroup "Golden tests" [ goldenVsString "Hello World" "test/golden/wh.out" (do codeE <- parseBfFile source case codeE of Left err -> return $ pack err Right code -> pack <$> (capture_ $ runBfNoLog code)) ] source :: FilePath source = "examples/hello_world.bf"
agremm/bfint
test/Spec.hs
gpl-3.0
659
0
17
218
163
87
76
19
2