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
module Main where import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..)) import System.Exit (ExitCode(..), exitWith) import qualified Data.RevisionsTest as RevisionsTest main :: IO () main = exitProperly $ runTestTT $ TestList [ TestList RevisionsTest.tests ] exitProperly :: IO Counts -> IO () exitProperly m = do counts <- m exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
AKST/wikit
socket-server/tests/Main.hs
mit
455
0
12
85
163
91
72
11
2
{-# language GeneralizedNewtypeDeriving #-} {-# language RecursiveDo #-} {-# language FlexibleContexts #-} {-# language TupleSections #-} -- | implementation of reduced ordered binary decision diagrams. module OBDD.Data ( -- * the data type OBDD -- abstract , size -- * for external use , null, satisfiable , number_of_models , variables, paths, models , some_model , fold, foldM , full_fold, full_foldM -- * for internal use , Node (..) , make , register, checked_register , top , access , not_ , assocs ) where import Data.IntMap.Strict ( IntMap ) import qualified Data.IntMap.Strict as IM import OBDD.IntIntMap (IntIntMap) import qualified OBDD.IntIntMap as IIM import OBDD.VarIntIntMap (VarIntIntMap) import qualified OBDD.VarIntIntMap as VIIM import Data.Map.Strict ( Map ) import qualified Data.Map.Strict as M import qualified Data.Array as A import Data.Set ( Set ) import qualified Data.Set as S import Data.Bool (bool) import Control.Arrow ( (&&&) ) import Control.Monad.State.Strict (State, runState, evalState, get, put, gets, modify) import qualified System.Random import Control.Monad.Fix import Control.Monad ( forM, guard, void ) import qualified Control.Monad ( foldM ) import Data.Functor.Identity import Data.List (isPrefixOf, isSuffixOf) import Prelude hiding ( null ) import qualified Prelude -- newtype Index = Index { unIndex :: Int } -- deriving ( Eq, Ord, Num, Enum, Show ) type Index = Int ; unIndex = id -- | assumes total ordering on variables data OBDD v = OBDD { core :: !(IntMap ( Node v Index )) -- , icore :: !(Map ( Node v Index ) Index) , icore :: !(VarIntIntMap v Index) , ifalse :: !Index , itrue :: !Index , next :: !Index , top :: !Index } assocs :: OBDD v -> [(Index, Node v Index)] assocs o = IM.toAscList $ core o -- | Apply function in each node, bottom-up. -- return the value in the root node. -- Will cache intermediate results. -- You might think that -- @count_models = fold (\b -> if b then 1 else 0) (\v l r -> l + r)@ -- but that's not true because a path might omit variables. -- Use @full_fold@ to fold over interpolated nodes as well. fold :: Ord v => ( Bool -> a ) -> ( v -> a -> a -> a ) -> OBDD v -> a fold leaf branch o = runIdentity $ foldM ( return . leaf ) ( \ v l r -> return $ branch v l r ) o -- | Run action in each node, bottum-up. -- return the value in the root node. -- Will cache intermediate results. foldM :: (Monad m, Ord v) => ( Bool -> m a ) -> ( v -> a -> a -> m a ) -> OBDD v -> m a foldM leaf branch o = do m <- Control.Monad.foldM ( \ m (i,n) -> do val <- case n of Leaf b -> leaf b Branch v l r -> branch v (m M.! l) (m M.! r) return $ M.insert i val m ) M.empty $ IM.toAscList $ core o return $ m M.! top o -- | Apply function in each node, bottom-up. -- Also apply to interpolated nodes: when a link -- from a node to a child skips some variables: -- for each skipped variable, we run the @branch@ function -- on an interpolated node that contains this missing variable, -- and identical children. -- With this function, @number_of_models@ -- can be implemented as -- @full_fold vars (bool 0 1) ( const (+) )@. -- And it actually is, see the source. full_fold :: Ord v => Set v -> ( Bool -> a ) -> ( v -> a -> a -> a ) -> OBDD v -> a full_fold vars leaf branch o = runIdentity $ full_foldM vars ( return . leaf ) ( \ v l r -> return $ branch v l r ) o full_foldM :: (Monad m, Ord v) => Set v -> ( Bool -> m a ) -> ( v -> a -> a -> m a ) -> OBDD v -> m a full_foldM vars leaf branch o = do let vs = S.toAscList $ S.union (variables o) vars low = head vs m = M.fromList $ zip vs $ tail vs up v = M.lookup v m interpolate now goal x | now == goal = return x interpolate (Just now) goal x = branch now x x >>= interpolate (up now) goal (a,res) <- foldM ( \ b -> (Just low ,) <$> leaf b ) ( \ v (p,l) (q,r) -> do l' <- interpolate p (Just v) l r' <- interpolate q (Just v) r (up v,) <$> branch v l' r' ) o interpolate a Nothing res size = unIndex . next -- | Number of satisfying assignments with given set of variables. -- The set of variables must be given since the current OBDD may not contain -- all variables that were used to construct it, since some nodes may have been removed -- because they had identical children. number_of_models :: Ord v => Set v -> OBDD v -> Integer number_of_models vars o = full_fold vars (bool 0 1) ( const (+) ) o empty :: OBDD v empty = OBDD { core = IM.fromList [(0,Leaf False),(1,Leaf True)] , icore = VIIM.empty , ifalse = 0 , itrue = 1 , next = 2 , top = -1 } data Node v i = Leaf !Bool | Branch !v !i !i deriving ( Eq, Ord ) not_ o = o { ifalse = itrue o , itrue = ifalse o , core = IM.insert (itrue o) (Leaf False) $ IM.insert (ifalse o) (Leaf True) $ core o } access :: OBDD v -> Node v ( OBDD v ) access s = case top s of i | i == ifalse s -> Leaf False i | i == itrue s -> Leaf True t -> case IM.lookup ( top s ) ( core s ) of Nothing -> error "OBDD.Data.access" Just n -> case n of Leaf p -> error "Leaf in core" Branch v l r -> Branch v ( s { top = l } ) ( s { top = r } ) -- | does the OBDD have any models? satisfiable :: OBDD v -> Bool satisfiable = not . null -- | does the OBDD not have any models? null :: OBDD v -> Bool null s = case access s of Leaf False -> True _ -> False -- | randomly select one model, if possible some_model :: Ord v => OBDD v -> IO ( Maybe ( Map v Bool ) ) some_model s = case access s of Leaf True -> return $ Just $ M.empty Leaf False -> return Nothing Branch v l r -> do let nonempty_children = do ( p, t ) <- [ (False, l), (True, r) ] guard $ case access t of Leaf False -> False _ -> True return ( p, t ) (p, t) <- select_one nonempty_children Just m <- some_model t return $ Just $ M.insert v p m -- | all variables that occur in the nodes variables :: Ord v => OBDD v -> S.Set v variables f = fold (\ b -> S.empty ) ( \ v l r -> S.insert v $ S.union l r ) f -- | list of all paths paths :: Ord v => OBDD v -> [ Map v Bool ] paths = fold ( bool [] [ M.empty ] ) ( \ v l r -> (M.insert v False <$> l) ++ (M.insert v True <$> r) ) -- | list of all models (a.k.a. minterms) models vars = full_fold vars ( bool [] [ M.empty ] ) ( \ v l r -> (M.insert v False <$> l) ++ (M.insert v True <$> r) ) select_one :: [a] -> IO a select_one xs | not ( Prelude.null xs ) = do i <- System.Random.randomRIO ( 0, length xs - 1 ) return $ xs !! i make :: State ( OBDD v ) Index -> OBDD v make action = let ( i, s ) = runState action empty in i `seq` s { top = i } fresh :: State ( OBDD v ) Index fresh = do s <- get let i = next s put $! s { next = succ i } return i register :: Ord v => Node v Index -> State ( OBDD v ) Index register n = case n of Leaf False -> ifalse <$> get Leaf True -> itrue <$> get Branch v l r -> if l == r then return l else do s <- get case VIIM.lookup (v, l, r) ( icore s ) of Just i -> return i Nothing -> do i <- fresh s <- get put $! s { core = IM.insert i n $ core s , icore = VIIM.insert (v, l, r) i $ icore s } return i checked_register :: Ord v => Node v Index -> State ( OBDD v ) Index checked_register n = case n of Branch v l r -> do s <- get let check_var_ordering b = case IM.lookup b (core s ) of Just (Branch av _ _) | not (v > av) -> error "wrong variable ordering" _ -> return () check_var_ordering l ; check_var_ordering r register n _ -> register n
jwaldmann/haskell-obdd
src/OBDD/Data.hs
gpl-2.0
8,625
0
21
2,965
2,868
1,491
1,377
237
5
{-# LANGUAGE TemplateHaskell #-} module Language.LCC.AST.Translation where import Control.Lens import Text.Parsec (SourcePos) import Language.LCC.AST.Annotation import Language.LCC.AST.Expr import Language.LCC.AST.Path import Language.LCC.AST.Signature data Translation path ret = Translation { _trSig :: Signature AbsolutePath ret , _trImpl :: Expr path , _trAnnotations :: [Annotation] , _trSourcePos :: SourcePos } deriving (Eq, Show) makeLenses ''Translation type RelTranslation ret = Translation RelativeVarPath ret type AbsTranslation ret = Translation AbsoluteVarPath ret type RawTranslation = RelTranslation UnknownType type AnalyzedTranslation = AbsTranslation Type isBuiltinTr :: Translation path ret -> Bool isBuiltinTr = any isBuiltin . view trAnnotations isPrivateTr :: Translation path ret -> Bool isPrivateTr = any isPrivate . view trAnnotations isPublicTr :: Translation path ret -> Bool isPublicTr = not . isPrivateTr trParamTypes :: Traversal' (Translation path ret) Type trParamTypes = trSig.sigParamTypes matchTrParams :: Eq path => Translation path ret -> Translation path ret -> Bool matchTrParams t1 t2 = matchSig (t1^.trSig) (t2^.trSig) lookupParam :: Translation path ret -> PathNode -> Maybe Param lookupParam t name = t^?trSig.sigParams.folded.filtered (\p -> p^.paramName == name)
xcv-/LCC
lib/Language/LCC/AST/Translation.hs
gpl-3.0
1,419
0
10
276
384
209
175
-1
-1
{-# LANGUAGE OverloadedStrings , FlexibleContexts #-} module Session where import Imports import Control.Applicative import Control.Monad.Catch import Control.Monad.Reader import Data.TimeMap as TM import qualified Data.Text.Encoding as T import Data.Aeson as A hiding (json) import qualified Crypto.Saltine.Core.Sign as NaCl import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Base16 as BS16 -- * Signatures newtype Signature = Signature { getSignature :: BS.ByteString } deriving (Show, Eq) instance FromJSON Signature where parseJSON (String s) = case BS16.decode $ T.encodeUtf8 s of (decoded, rest) | rest /= "" -> fail "Not base-16 encoded" | otherwise -> pure $ Signature decoded parseJSON _ = fail "Not a string" instance ToJSON Signature where toJSON (Signature s) = toJSON . T.decodeUtf8 . BS16.encode $ s -- * Requests data SignedRequest = SignedRequest { sessionPublicKey :: ClientPublicKey , sessionSignature :: Signature } deriving (Show, Eq) instance FromJSON SignedRequest where parseJSON (Object o) = SignedRequest <$> (o .: "publicKey") <*> (o .: "signature") parseJSON _ = empty -- * Signing and Verification sign :: ( ToJSON a , MonadApp m ) => a -> m Signature sign x = do sk <- envSecretKey <$> ask pure . Signature . NaCl.sign sk . LBS.toStrict . A.encode $ x verify :: ( FromJSON a ) => SignedRequest -> Maybe a verify (SignedRequest pk (Signature s)) = do pk' <- toNaClPublicKey pk message <- NaCl.signOpen pk' s A.decodeStrict message withSession :: ( MonadApp m , FromJSON a , ToJSON b ) => (a -> m b) -> SignedRequest -> m Signature withSession f req@(SignedRequest sId sig) = case verify req of Nothing -> throwM $ InvalidSignedRequest $ show req Just x -> do -- update the session id sessionCache <- envSession <$> ask liftIO $ TM.touch sId sessionCache sign =<< f x -- TODO: Authentication; for each route? Some kind of UserId -> Credentials doodad? -- sessionCache <- envSession <$> ask -- storedUserId <- do -- mh <- liftIO . atomically $ TM.lookup sId sessionCache -- case mh of -- Nothing -> throwM (NonexistentSessionId sId) -- Just h -> pure h
athanclark/happ-store
src/Session.hs
gpl-3.0
2,419
0
12
616
627
338
289
60
2
module Main where import System.Environment import Control.Exception as EX import Data.Char (toUpper) import Data.List (nub) import qualified Data.Vector as V import Board import Piece import DistanceTables strToLocation :: [String] -> [(Int, Int)] strToLocation [] = [] strToLocation str = do let x = read ( head str) :: Int let y = read ( head (drop 1 str) ) :: Int (x, y) : strToLocation (drop 3 str) mainProgram :: IO () mainProgram = do args <- getArgs case (map toUpper (head args)) of "DISTANCE" -> displayTableIO $ drop 1 args "CHESSDISTANCE" -> displayChessTableIO $ drop 1 args "BUNDLE" -> bundleIO $ drop 1 args "ACCEPTABLEBUNDLE" -> acceptableBundleIO $ drop 1 args "BUNDLESTRING" -> bundleIOString $ drop 1 args "ACCEPTABLEBUNDLESTRING" -> acceptableBundleIOString $ drop 1 args displayTableIO :: [String] -> IO () displayTableIO args = do let tablename = head args let colour = head $ drop 1 args let rnk = head $ drop 2 args let obst = strToLocation $ drop 6 args let locat = (read (head (drop 3 args)) :: Int , read (head (drop 4 args)) :: Int ) let offserObst = map (\x -> ((fst locat) - (fst x) + 8, (snd locat) - (snd x) + 8) ) obst let distance_table = generateDistenceTableObst offserObst (getColorFromString colour) (getRankFromString rnk) displayTable tablename $ distance_table displayChessTableIO :: [String] -> IO () displayChessTableIO args = do let tablename = head args let colour = head $ drop 1 args let rnk = head $ drop 2 args let obst = strToLocation $ drop 6 args let locat = (read (head (drop 3 args)) :: Int , read (head (drop 4 args)) :: Int ) let piece = makeChessPiece (getColorFromString colour) (getRankFromString rnk) locat let distance_table = appliedDistenceTable piece obst displayTable tablename $ distance_table bundleIO args = do let filename = head args let colour = head $ drop 1 args let rnk = head $ drop 2 args let obst = strToLocation $ drop 9 args let locat = (read (head (drop 3 args)) :: Int , read (head (drop 4 args)) :: Int ) let destination = (read (head (drop 6 args)) :: Int , read (head (drop 7 args)) :: Int ) let piece = makeChessPiece (getColorFromString colour) (getRankFromString rnk) locat let bundle = buildTrajectoryBundle 1 piece destination obst putStrLn $ generateDotString bundle obst acceptableBundleIO args = do let filename = head args let colour = head $ drop 1 args let rnk = head $ drop 2 args let obst = strToLocation $ drop 10 args let locat = (read (head (drop 3 args)) :: Int , read (head (drop 4 args)) :: Int ) let destination = (read (head (drop 6 args)) :: Int , read (head (drop 7 args)) :: Int ) let maxLength = read ( head ( drop 9 args ) ) :: Integer let piece = makeChessPiece (getColorFromString colour) (getRankFromString rnk) locat let bundle = builtAcceptableTrajectoriesBundle 1 piece destination obst maxLength putStrLn $ generateDotString bundle obst bundleIOString args = do let filename = head args let colour = head $ drop 1 args let rnk = head $ drop 2 args let obst = strToLocation $ drop 9 args let locat = (read (head (drop 3 args)) :: Int , read (head (drop 4 args)) :: Int ) let destination = (read (head (drop 6 args)) :: Int , read (head (drop 7 args)) :: Int ) let piece = makeChessPiece (getColorFromString colour) (getRankFromString rnk) locat let bundle = buildTrajectoryBundle 1 piece destination obst mapM putStrLn $ nub $ map trajectoryToString bundle return () acceptableBundleIOString args = do let filename = head args let colour = head $ drop 1 args let rnk = head $ drop 2 args let obst = strToLocation $ drop 10 args let locat = (read (head (drop 3 args)) :: Int , read (head (drop 4 args)) :: Int ) let destination = (read (head (drop 6 args)) :: Int , read (head (drop 7 args)) :: Int ) let maxLength = read ( head ( drop 9 args ) ) :: Integer let piece = makeChessPiece (getColorFromString colour) (getRankFromString rnk) locat let bundle = builtAcceptableTrajectoriesBundle 1 piece destination obst maxLength mapM putStrLn $ nub $ map trajectoryToString bundle return () showHelp :: SomeException -> IO () showHelp _ = do putStrLn $ "The program requires command line input.\nAlthough it is assumed \ \that the board is 8x8x1 for now. Try entering this: \n\ \\n \ \./compiled/Distance DISTANCE \"Rook\" Black Rook 4 4 1 4 7 1 4 2 1 5 4 1 \n\ \or \n\ \./compiled/Distance BUNDLE \"King\" Black King 3 3 1 3 6 1 4 3 1 4 4 1 4 5 1 4 6 1 3 4 1 3 5 1 \n\ \or \n\ \./compiled/Distance ACCEPTABLEBUNDLE \"King\" Black King 3 3 1 3 6 1 4 4 3 1 4 4 1 4 5 1 4 6 1 3 4 1 3 5 1 \n\ \or \n\ \./compiled/Distance BUNDLESTRING \"King\" Black King 3 3 1 3 6 1 4 3 1 4 4 1 4 5 1 4 6 1 3 4 1 3 5 1 \n\ \or \n\ \./compiled/Distance ACCEPTABLEBUNDLESTRING \"King\" Black King 3 3 1 3 6 1 4 4 3 1 4 4 1 4 5 1 4 6 1 3 4 1 3 5 1 \n\ \ \n" {-- do let obst = [(4,3),(4,4),(4,5),(4,6),(5,3),(5,4),(5,5),(5,6),(6,3),(3,4),(3,5)] let s_color = White let s_rank = Underwood let start = (3,2) let destination = (4,1) let subject = makeChessPiece s_color s_rank start --let bundle = buildTrajectoryBundle 1 subject destination obst let bundle = bAJT 1 subject destination obst 4 --print $ length.nub $ map trajectoryToString bundle --mapM putStrLn $ map (\x -> " " ++ locationOnChessboard x ++ " [fillcolor=yellow]") obst putStrLn $ (unlines.nub.lines.concat) $ map trajectoryToDotString bundle --displayTable "White moves:" $ appliedDistenceTable x obsticals --print $ map trajectoryToString bundle displayTable "Underwood moves:" $ appliedDistenceTable subject [] --} generateDotFile filename bundle obsticals = writeFile filename (generateDotString bundle obsticals) generateDotString bundle obsticals = do let header = "digraph {" let nodes = [ (x,y) | x <- [8, 7..1] , y <- [1..8] ] let nodeStrings = map (makeNodeString obsticals) nodes let trajectoryStrings = (unlines.nub.lines.concat) $ map trajectoryToDotString bundle let footer = "}" header ++ (foldr1 (++) nodeStrings) ++ trajectoryStrings ++ footer makeNodeString obsticals node@(x,y) | node `elem` obsticals = "" | otherwise = " " ++ locationOnChessboard node ++ "[label=\"" ++ locationOnChessboard node ++ "\" pos=\"" ++ (show (9-x)) ++ "," ++ (show y) ++ "!\"] \n" {-- TODO: Issues with GraphViz moving nodes around. | node `elem` obsticals = " " ++ locationOnChessboard node ++ "[label=\"" ++ locationOnChessboard node ++ "\" pos=\"" ++ (show x) ++ "," ++ (show y) ++ "!\" fontcolor=red] \n" | otherwise = " " ++ locationOnChessboard node ++ "[label=\"" ++ locationOnChessboard node ++ "\" pos=\"" ++ (show (9-x)) ++ "," ++ (show y) ++ "!\"] \n" --} main :: IO () main = EX.catch mainProgram showHelp
joshuaunderwood7/HaskeLinGeom
Main.hs
gpl-3.0
7,213
0
17
1,806
2,133
1,036
1,097
105
6
module Problem012 (answer) where import Primes (factorize) answer :: Int answer = head $ dropWhile (\x -> dn x <= 500) triangulars -- for a number n = prod(p_i^k_i) where p_i^k_i is its prime factorization -- the number of divisor d(n) is prod(k_i + 1) dn :: Int -> Int dn n = product $ map ((+1) . snd) (aggregate (factorize n)) triangulars = [n * (n+1) `div` 2 | n <- [1..]] -- count the number of items from a given sorted list -- aggregate [2,2,3,5,5] -> [(2, 2), (3, 1), (5, 2)] aggregate :: [Int] -> [(Int, Int)] aggregate = foldl aggregate' [] where aggregate' [] n = [(n, 1)] aggregate' acc@((x, count):xs) n = if x == n then (x, count+1):xs else (n, 1):acc
geekingfrog/project-euler
Problem012.hs
gpl-3.0
693
0
11
154
258
148
110
13
3
module Helpers ( mapList , commitTime ) where import Data.Git (Commit, commitAuthor, personTime) import Data.Git.Types (toUTCTime) import Data.Time.Clock (UTCTime) mapList :: ([a] -> b -> [a]) -> [a] -> [b] -> [a] mapList _ baseList [] = baseList mapList f baseList (c:cs) = mapList f (f baseList c) cs -- | Take a 'Commit' object and returns it\'s author\'s 'personTime'. commitTime :: Commit -> UTCTime commitTime commit = toUTCTime $ personTime $ commitAuthor commit
cdepillabout/haskell-git-too-many-cherry-picks
Helpers.hs
gpl-3.0
492
0
9
96
170
96
74
11
1
module File where import CNTypes import CN import Vector writeWaveset :: Show a => Waveset a -> FilePath -> IO () writeWaveset set filename = do let dx = show $ wsetDx set dt = show $ wsetDt set x0 = show $ wsetX0 set ws = show $ map fillVec $ wsetWaves set cb = dx ++ "\n" ++ dt ++ "\n" ++ x0 ++ "\n" ++ ws writeFile filename cb readWaveset :: (Read a) => FilePath -> IO (Waveset a) readWaveset filename = do str <- readFile filename let [dx',dt',x0',ws'] = lines str [dx,dt,x0] = map read [dx',dt',x0']-- :: [a] ws = read ws'-- :: [[a]] return $ Waveset (map vecList ws) dx dt x0 -- wanted format: t x Re(psi) Im(psi) writeWavesetGnuplot :: (Show a) => Waveset a -> FilePath -> IO String writeWavesetGnuplot filename = do -- let ws = show $ map -- return str undefined
KiNaudiz/bachelor
CN/File.hs
gpl-3.0
923
0
15
303
322
164
158
22
1
reverse' :: String -> String -> String reverse' start end = case start of "" -> end start -> reverse' (tail start) ((head start):end) main :: IO () main = do line <- getLine putStrLn $ reverse' line ""
torchhound/projects
haskell/reverseString.hs
gpl-3.0
240
0
12
77
98
48
50
7
2
-- | -- Module : GameKeeper.API -- Copyright : (c) 2012-2015 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module GameKeeper.API (module E) where import GameKeeper.API.Binding as E import GameKeeper.API.Connection as E import GameKeeper.API.Channel as E import GameKeeper.API.Exchange as E import GameKeeper.API.Node as E import GameKeeper.API.Overview as E import GameKeeper.API.Queue as E
brendanhay/gamekeeper
src/GameKeeper/API.hs
mpl-2.0
803
0
4
184
79
61
18
8
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.DeleteVpcPeeringConnection -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Deletes a VPC peering connection. Either the owner of the requester VPC or -- the owner of the peer VPC can delete the VPC peering connection if it's in -- the 'active' state. The owner of the requester VPC can delete a VPC peering -- connection in the 'pending-acceptance' state. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpcPeeringConnection.html> module Network.AWS.EC2.DeleteVpcPeeringConnection ( -- * Request DeleteVpcPeeringConnection -- ** Request constructor , deleteVpcPeeringConnection -- ** Request lenses , dvpcDryRun , dvpcVpcPeeringConnectionId -- * Response , DeleteVpcPeeringConnectionResponse -- ** Response constructor , deleteVpcPeeringConnectionResponse -- ** Response lenses , dvpcrReturn ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data DeleteVpcPeeringConnection = DeleteVpcPeeringConnection { _dvpcDryRun :: Maybe Bool , _dvpcVpcPeeringConnectionId :: Text } deriving (Eq, Ord, Read, Show) -- | 'DeleteVpcPeeringConnection' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dvpcDryRun' @::@ 'Maybe' 'Bool' -- -- * 'dvpcVpcPeeringConnectionId' @::@ 'Text' -- deleteVpcPeeringConnection :: Text -- ^ 'dvpcVpcPeeringConnectionId' -> DeleteVpcPeeringConnection deleteVpcPeeringConnection p1 = DeleteVpcPeeringConnection { _dvpcVpcPeeringConnectionId = p1 , _dvpcDryRun = Nothing } -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have the -- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'. dvpcDryRun :: Lens' DeleteVpcPeeringConnection (Maybe Bool) dvpcDryRun = lens _dvpcDryRun (\s a -> s { _dvpcDryRun = a }) -- | The ID of the VPC peering connection. dvpcVpcPeeringConnectionId :: Lens' DeleteVpcPeeringConnection Text dvpcVpcPeeringConnectionId = lens _dvpcVpcPeeringConnectionId (\s a -> s { _dvpcVpcPeeringConnectionId = a }) newtype DeleteVpcPeeringConnectionResponse = DeleteVpcPeeringConnectionResponse { _dvpcrReturn :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'DeleteVpcPeeringConnectionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dvpcrReturn' @::@ 'Maybe' 'Bool' -- deleteVpcPeeringConnectionResponse :: DeleteVpcPeeringConnectionResponse deleteVpcPeeringConnectionResponse = DeleteVpcPeeringConnectionResponse { _dvpcrReturn = Nothing } -- | Returns 'true' if the request succeeds; otherwise, it returns an error. dvpcrReturn :: Lens' DeleteVpcPeeringConnectionResponse (Maybe Bool) dvpcrReturn = lens _dvpcrReturn (\s a -> s { _dvpcrReturn = a }) instance ToPath DeleteVpcPeeringConnection where toPath = const "/" instance ToQuery DeleteVpcPeeringConnection where toQuery DeleteVpcPeeringConnection{..} = mconcat [ "DryRun" =? _dvpcDryRun , "VpcPeeringConnectionId" =? _dvpcVpcPeeringConnectionId ] instance ToHeaders DeleteVpcPeeringConnection instance AWSRequest DeleteVpcPeeringConnection where type Sv DeleteVpcPeeringConnection = EC2 type Rs DeleteVpcPeeringConnection = DeleteVpcPeeringConnectionResponse request = post "DeleteVpcPeeringConnection" response = xmlResponse instance FromXML DeleteVpcPeeringConnectionResponse where parseXML x = DeleteVpcPeeringConnectionResponse <$> x .@? "return"
romanb/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DeleteVpcPeeringConnection.hs
mpl-2.0
4,725
0
9
947
488
298
190
61
1
module CombinationSpec where import Test.Hspec import Combinations import Data.List (tails, sort) import Test.QuickCheck -- combinations :: Int -> [a] -> [[a]] -- combinations = undefined (~~) a b = f a `shouldBe` f b where f = sort . fmap sort main :: IO () main = hspec $ do describe "Testing combinations" $ do it "should work for examples" $ do combinations 0 [1..5] ~~ [[]] combinations 1 [1..5] ~~ [[1],[2],[3],[4],[5]] combinations 2 [1..5] ~~ [[1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4],[3,5],[4,5]] combinations 3 [1..5] ~~ [[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]] combinations 4 [1..5] ~~ [[1,2,3,4],[1,2,3,5],[1,2,4,5],[1,3,4,5],[2,3,4,5]] combinations 5 [1..5] ~~ [[1,2,3,4,5]] it "randomized testing with integers" $ property $ \n -> forAll (resize 10 arbitrary) $ \xs-> combinations (p xs n) xs ~~ combinations' (p xs n) (xs :: [Integer]) it "should work for polymorphic list" $ property $ \n -> forAll (resize 10 arbitrary) $ \xs -> combinations n xs ~~ combinations' n (xs :: [()]) -- p :: [a] -> Int -> Int p [] _ = 0 p xs n = ((1 + abs n) `mod` length xs) combinations' :: Int -> [a] -> [[a]] combinations' n xs = case n of 0 -> [[]] _ -> [ y : ys | y : xs' <- tails xs, ys <- combinations' (n - 1) xs' ] --
ice1000/OI-codes
codewars/authoring/haskell/CombinationsSpec.hs
agpl-3.0
1,352
0
19
291
848
487
361
29
2
{-# LANGUAGE OverloadedStrings #-} module TestTrie(testTrie) where import Test.Tasty import Test.Tasty.QuickCheck import Test.QuickCheck import Data.FixFile import Data.FixFile.Trie import qualified Data.ByteString.Lazy as BS import Data.Function import Data.List hiding (null) import Data.Maybe import Data.Monoid import Control.Applicative hiding (empty) import Prelude hiding (null) instance Arbitrary BS.ByteString where arbitrary = BS.pack <$> arbitrary instance CoArbitrary BS.ByteString where coarbitrary c = coarbitrary $ BS.unpack c prop_TrieInsert :: [(BS.ByteString, Int)] -> Bool prop_TrieInsert xs = allIns where empt = empty :: Fix (Trie Int) fullSet = foldr (uncurry insertTrie) empt xs allIns = all (isJust . flip lookupTrie fullSet) $ fmap fst xs prop_TrieLookupNegative :: [BS.ByteString] -> [BS.ByteString] -> Bool prop_TrieLookupNegative xs negs = allIns where empt = empty :: Fix (Trie Int) fullSet = foldr (flip insertTrie 0) empt xs negs' = filter (\x -> not (any (== x) xs)) negs allIns = all (isNothing . flip lookupTrie fullSet) negs' prop_TrieFreeze :: [(BS.ByteString, Int)] -> Bool prop_TrieFreeze xs = allIns where empt = empty :: Fix (Trie Int) fullSet = freeze $ foldr (uncurry insertTrie) empt xs allIns = all (isJust . flip lookupTrie fullSet) $ fmap fst xs prop_TrieThaw :: [(BS.ByteString, Int)] -> [(BS.ByteString, Int)] -> Bool prop_TrieThaw xs ys = allIns where empt = empty :: Fix (Trie Int) halfSet = freeze $ foldr (uncurry insertTrie) empt xs fullSet = foldr (uncurry insertTrie) halfSet ys keys = fmap fst $ xs ++ ys allIns = all (isJust . flip lookupTrie fullSet) keys prop_TrieDelete :: [(BS.ByteString, Int)] -> BS.ByteString -> BS.ByteString -> Bool prop_TrieDelete ins pre del = allDels where empt = empty :: Fix (Trie Int) pres = [(BS.append pre ik, iv) | (ik,iv) <- ins] dels = [(BS.append del ik, iv) | (ik,iv) <- ins] delks = fmap fst dels fullTrie = foldr (uncurry insertTrie) empt (pres ++ dels) delSet = foldr deleteTrie fullTrie delks allDels = all (isNothing . flip lookupTrie delSet) delks prop_TrieDeleteAll :: [(BS.ByteString, Int)] -> Bool prop_TrieDeleteAll xs = allDels where empt = empty :: Fix (Trie Int) fullSet = foldr (uncurry insertTrie) empt xs delSet = foldr deleteTrie fullSet $ fmap fst xs allDels = [] == iterateTrie "" delSet prop_TrieReplace :: [(BS.ByteString, Int)] -> BS.ByteString -> Int -> Int -> Bool prop_TrieReplace xs rk rv rv' = replTest where empt = empty :: Fix (Trie Int) fullSet = foldr (uncurry insertTrie) empt xs replSet = insertTrie rk rv' $ insertTrie rk rv fullSet replTest = Just rv' == lookupTrie rk replSet prop_TrieIterate :: [(BS.ByteString, Int)] -> BS.ByteString -> Bool prop_TrieIterate xs pre = allIter where empt = empty :: Fix (Trie Int) ins = [(BS.append pre suf, x) | (suf, x) <- xs] fullSet = foldr (uncurry insertTrie) empt ins iter = iterateTrie pre fullSet allIter = all (isJust . flip lookup ins) $ fmap fst iter prop_TrieFunctor :: [(BS.ByteString, String)] -> Bool prop_TrieFunctor xs = testAll where testAll = xs'' == iterateTrie BS.empty trie' && xs'' == iterateTrie BS.empty frozenTrie' xs' = nubBy ((==) `on` fst) $ sortBy (compare `on` fst) xs xs'' = fmap (fmap length) xs' trie = foldr (uncurry insertTrie) empty xs' :: Fix (Trie String) trie' = fmapF' length trie frozenTrie' = fmapF' length (freeze trie) prop_TrieFoldable :: [(BS.ByteString, Int)] -> Bool prop_TrieFoldable xs = testAll where testAll = listSum == trieSum && listSum == frozenTrieSum xs' = nubBy ((==) `on` fst) $ sortBy (compare `on` fst) xs listSum = getSum $ foldMap (Sum . snd) xs' trie = foldr (uncurry insertTrie) empty xs' :: Fix (Trie Int) trieSum = getSum $ foldMapF Sum trie frozenTrieSum = getSum $ foldMapF Sum (freeze trie) prop_TrieTraversable :: [(BS.ByteString, Int)] -> Bool prop_TrieTraversable xs = testAll where testAll = testEvens evens'' && testOdds odds'' && testEvens frozenEvens'' && testOdds frozenOdds'' evens = filter (even . snd) xs odds = filter (odd . snd) xs evens' = foldr (uncurry insertTrie) empty evens :: Fix (Trie Int) odds' = foldr (uncurry insertTrie) empty odds :: Fix (Trie Int) frozenEvens' = freeze evens' frozenOdds' = freeze odds' f x = if even x then Nothing else Just x evens'' = traverseF' f evens' odds'' = traverseF' f odds' frozenEvens'' = traverseF' f frozenEvens' frozenOdds'' = traverseF' f frozenOdds' testEvens Nothing = True testEvens _ = null evens testOdds Nothing = False testOdds _ = True testTrie = testGroup "Trie" [ testProperty "Trie Insert" prop_TrieInsert ,testProperty "Trie Lookup Negative" prop_TrieLookupNegative ,testProperty "Trie Freeze" prop_TrieFreeze ,testProperty "Trie Thaw" prop_TrieThaw ,testProperty "Trie Delete" prop_TrieDelete ,testProperty "Trie Delete All" prop_TrieDeleteAll ,testProperty "Trie Replace" prop_TrieReplace ,testProperty "Trie Iterate" prop_TrieIterate ,testProperty "Trie Functor" prop_TrieFunctor ,testProperty "Trie Foldable" prop_TrieFoldable ,testProperty "Trie Traversable" prop_TrieTraversable ]
revnull/fixfile
tests/TestTrie.hs
lgpl-3.0
5,387
0
13
1,149
1,876
992
884
120
4
module Polymorphism where data Identity a = Identity a instance Eq a => Eq (Identity a) where (==) (Identity a1) (Identity a2) = a1 == a2
ocozalp/Haskellbook
chapter6/polymorphism.hs
unlicense
149
0
8
37
63
34
29
5
0
module QR.Beam where import Data.Char import Data.Sequence(Seq) import qualified Data.Sequence as S getMinChange :: String -> String getMinChange xs = let inputs = words xs totalDamage = read (head inputs)::Int program = last inputs shootCount = length $ filter (== 'S') program in if shootCount > totalDamage then "IMPOSSIBLE" else show (getChangeNum program totalDamage 0) toIntArr :: String -> [Int] toIntArr xs = map (\x -> if x=='C' then 1 else 0) xs getTotalDamage :: String -> Int -> Int -> Int getTotalDamage [] _ z = z getTotalDamage (x:xs) y z = if (x == 'S') then getTotalDamage xs y (z+y) else getTotalDamage xs (y*2) z getChangeNum :: String -> Int -> Int -> Int getChangeNum xs y z = let totalDamage = getTotalDamage xs 1 0 in if totalDamage > y then (getChangeNum (replaceFirst xs 'C' 'S') y (z+1)) else z replaceFirst :: String -> Char -> Char -> String replaceFirst (x:x':xs) y z = if x == y && x' == z then z:y:xs else x:(replaceFirst (x':xs) y z)
lihlcnkr/codejam
src/QR/Beam.hs
apache-2.0
1,077
0
11
283
441
235
206
28
2
module Beowulf.Style.Colors where import Beowulf.Style aliceBlue :: ColorT aliceBlue = Hex 0xF0F8FF antiqueWhite :: ColorT antiqueWhite = Hex 0xFAEBD7 aqua :: ColorT aqua = Hex 0x00FFFF aquamarine :: ColorT aquamarine = Hex 0x7FFFD4 azure :: ColorT azure = Hex 0xF0FFFF beige :: ColorT beige = Hex 0xF5F5DC bisque :: ColorT bisque = Hex 0xFFE4C4 black :: ColorT black = Hex 0x000000 blanchedAlmond :: ColorT blanchedAlmond = Hex 0xFFEBCD blue :: ColorT blue = Hex 0x0000FF blueViolet :: ColorT blueViolet = Hex 0x8A2BE2 brown :: ColorT brown = Hex 0xA52A2A burlyWood :: ColorT burlyWood = Hex 0xDEB887 cadetBlue :: ColorT cadetBlue = Hex 0x5F9EA0 chartreuse :: ColorT chartreuse = Hex 0x7FFF00 chocolate :: ColorT chocolate = Hex 0xD2691E coral :: ColorT coral = Hex 0xFF7F50 cornflowerBlue :: ColorT cornflowerBlue = Hex 0x6495ED cornsilk :: ColorT cornsilk = Hex 0xFFF8DC crimson :: ColorT crimson = Hex 0xDC143C cyan :: ColorT cyan = Hex 0x00FFFF darkBlue :: ColorT darkBlue = Hex 0x00008B darkCyan :: ColorT darkCyan = Hex 0x008B8B darkGoldenRod :: ColorT darkGoldenRod = Hex 0xB8860B darkGray :: ColorT darkGray = Hex 0xA9A9A9 darkGreen :: ColorT darkGreen = Hex 0x006400 darkKhaki :: ColorT darkKhaki = Hex 0xBDB76B darkMagenta :: ColorT darkMagenta = Hex 0x8B008B darkOliveGreen :: ColorT darkOliveGreen = Hex 0x556B2F darkOrange :: ColorT darkOrange = Hex 0xFF8C00 darkOrchid :: ColorT darkOrchid = Hex 0x9932CC darkRed :: ColorT darkRed = Hex 0x8B0000 darkSalmon :: ColorT darkSalmon = Hex 0xE9967A darkSeaGreen :: ColorT darkSeaGreen = Hex 0x8FBC8F darkSlateBlue :: ColorT darkSlateBlue = Hex 0x483D8B darkSlateGray :: ColorT darkSlateGray = Hex 0x2F4F4F darkTurquoise :: ColorT darkTurquoise = Hex 0x00CED1 darkViolet :: ColorT darkViolet = Hex 0x9400D3 deepPink :: ColorT deepPink = Hex 0xFF1493 deepSkyBlue :: ColorT deepSkyBlue = Hex 0x00BFFF dimGray :: ColorT dimGray = Hex 0x696969 dodgerBlue :: ColorT dodgerBlue = Hex 0x1E90FF fireBrick :: ColorT fireBrick = Hex 0xB22222 floralWhite :: ColorT floralWhite = Hex 0xFFFAF0 forestGreen :: ColorT forestGreen = Hex 0x228B22 fuchsia :: ColorT fuchsia = Hex 0xFF00FF gainsboro :: ColorT gainsboro = Hex 0xDCDCDC ghostWhite :: ColorT ghostWhite = Hex 0xF8F8FF gold :: ColorT gold = Hex 0xFFD700 goldenRod :: ColorT goldenRod = Hex 0xDAA520 gray :: ColorT gray = Hex 0x808080 green :: ColorT green = Hex 0x008000 greenYellow :: ColorT greenYellow = Hex 0xADFF2F honeyDew :: ColorT honeyDew = Hex 0xF0FFF0 hotPink :: ColorT hotPink = Hex 0xFF69B4 indianRed :: ColorT indianRed = Hex 0xCD5C5C indigo :: ColorT indigo = Hex 0x4B0082 ivory :: ColorT ivory = Hex 0xFFFFF0 khaki :: ColorT khaki = Hex 0xF0E68C lavender :: ColorT lavender = Hex 0xE6E6FA lavenderBlush :: ColorT lavenderBlush = Hex 0xFFF0F5 lawnGreen :: ColorT lawnGreen = Hex 0x7CFC00 lemonChiffon :: ColorT lemonChiffon = Hex 0xFFFACD lightBlue :: ColorT lightBlue = Hex 0xADD8E6 lightCoral :: ColorT lightCoral = Hex 0xF08080 lightCyan :: ColorT lightCyan = Hex 0xE0FFFF lightGoldenRodYellow :: ColorT lightGoldenRodYellow = Hex 0xFAFAD2 lightGray :: ColorT lightGray = Hex 0xD3D3D3 lightGreen :: ColorT lightGreen = Hex 0x90EE90 lightPink :: ColorT lightPink = Hex 0xFFB6C1 lightSalmon :: ColorT lightSalmon = Hex 0xFFA07A lightSeaGreen :: ColorT lightSeaGreen = Hex 0x20B2AA lightSkyBlue :: ColorT lightSkyBlue = Hex 0x87CEFA lightSlateGray :: ColorT lightSlateGray = Hex 0x778899 lightSteelBlue :: ColorT lightSteelBlue = Hex 0xB0C4DE lightYellow :: ColorT lightYellow = Hex 0xFFFFE0 lime :: ColorT lime = Hex 0x00FF00 limeGreen :: ColorT limeGreen = Hex 0x32CD32 linen :: ColorT linen = Hex 0xFAF0E6 magenta :: ColorT magenta = Hex 0xFF00FF maroon :: ColorT maroon = Hex 0x800000 mediumAquaMarine :: ColorT mediumAquaMarine = Hex 0x66CDAA mediumBlue :: ColorT mediumBlue = Hex 0x0000CD mediumOrchid :: ColorT mediumOrchid = Hex 0xBA55D3 mediumPurple :: ColorT mediumPurple = Hex 0x9370DB mediumSeaGreen :: ColorT mediumSeaGreen = Hex 0x3CB371 mediumSlateBlue :: ColorT mediumSlateBlue = Hex 0x7B68EE mediumSpringGreen :: ColorT mediumSpringGreen = Hex 0x00FA9A mediumTurquoise :: ColorT mediumTurquoise = Hex 0x48D1CC mediumVioletRed :: ColorT mediumVioletRed = Hex 0xC71585 midnightBlue :: ColorT midnightBlue = Hex 0x191970 mintCream :: ColorT mintCream = Hex 0xF5FFFA mistyRose :: ColorT mistyRose = Hex 0xFFE4E1 moccasin :: ColorT moccasin = Hex 0xFFE4B5 navajoWhite :: ColorT navajoWhite = Hex 0xFFDEAD navy :: ColorT navy = Hex 0x000080 oldLace :: ColorT oldLace = Hex 0xFDF5E6 olive :: ColorT olive = Hex 0x808000 oliveDrab :: ColorT oliveDrab = Hex 0x6B8E23 orange :: ColorT orange = Hex 0xFFA500 orangeRed :: ColorT orangeRed = Hex 0xFF4500 orchid :: ColorT orchid = Hex 0xDA70D6 paleGoldenRod :: ColorT paleGoldenRod = Hex 0xEEE8AA paleGreen :: ColorT paleGreen = Hex 0x98FB98 paleTurquoise :: ColorT paleTurquoise = Hex 0xAFEEEE paleVioletRed :: ColorT paleVioletRed = Hex 0xDB7093 papayaWhip :: ColorT papayaWhip = Hex 0xFFEFD5 peachPuff :: ColorT peachPuff = Hex 0xFFDAB9 peru :: ColorT peru = Hex 0xCD853F pink :: ColorT pink = Hex 0xFFC0CB plum :: ColorT plum = Hex 0xDDA0DD powderBlue :: ColorT powderBlue = Hex 0xB0E0E6 purple :: ColorT purple = Hex 0x800080 red :: ColorT red = Hex 0xFF0000 rosyBrown :: ColorT rosyBrown = Hex 0xBC8F8F royalBlue :: ColorT royalBlue = Hex 0x4169E1 saddleBrown :: ColorT saddleBrown = Hex 0x8B4513 salmon :: ColorT salmon = Hex 0xFA8072 sandyBrown :: ColorT sandyBrown = Hex 0xF4A460 seaGreen :: ColorT seaGreen = Hex 0x2E8B57 seaShell :: ColorT seaShell = Hex 0xFFF5EE sienna :: ColorT sienna = Hex 0xA0522D silver :: ColorT silver = Hex 0xC0C0C0 skyBlue :: ColorT skyBlue = Hex 0x87CEEB slateBlue :: ColorT slateBlue = Hex 0x6A5ACD slateGray :: ColorT slateGray = Hex 0x708090 snow :: ColorT snow = Hex 0xFFFAFA springGreen :: ColorT springGreen = Hex 0x00FF7F steelBlue :: ColorT steelBlue = Hex 0x4682B4 tan :: ColorT tan = Hex 0xD2B48C teal :: ColorT teal = Hex 0x008080 thistle :: ColorT thistle = Hex 0xD8BFD8 tomato :: ColorT tomato = Hex 0xFF6347 turquoise :: ColorT turquoise = Hex 0x40E0D0 violet :: ColorT violet = Hex 0xEE82EE wheat :: ColorT wheat = Hex 0xF5DEB3 white :: ColorT white = Hex 0xFFFFFF whiteSmoke :: ColorT whiteSmoke = Hex 0xF5F5F5 yellow :: ColorT yellow = Hex 0xFFFF00 yellowGreen :: ColorT yellowGreen = Hex 0x9ACD32
jrahm/Beowulf
Beowulf/Style/Colors.hs
bsd-2-clause
6,332
0
5
992
1,832
988
844
282
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} module Tests.Transform ( tests ) where import Data.Bits ((.&.), shiftL) import Data.Complex (Complex((:+))) import Data.Functor ((<$>)) import Statistics.Function (within) import Statistics.Transform import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck (Positive(..),Property,Arbitrary(..),Gen,choose,vectorOf, printTestCase, quickCheck) import Text.Printf import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import Tests.Helpers tests :: Test tests = testGroup "fft" [ testProperty "t_impulse" t_impulse , testProperty "t_impulse_offset" t_impulse_offset , testProperty "ifft . fft = id" (t_fftInverse $ ifft . fft) , testProperty "fft . ifft = id" (t_fftInverse $ fft . ifft) , testProperty "idct . dct = id [up to scale]" (t_fftInverse (\v -> U.map (/ (2 * fromIntegral (U.length v))) $ idct $ dct v)) , testProperty "dct . idct = id [up to scale]" (t_fftInverse (\v -> U.map (/ (2 * fromIntegral (U.length v))) $ idct $ dct v)) -- Exact small size DCT -- 2 , testDCT [1,0] $ map (*2) [1, cos (pi/4) ] , testDCT [0,1] $ map (*2) [1, cos (3*pi/4) ] -- 4 , testDCT [1,0,0,0] $ map (*2) [1, cos( pi/8), cos( 2*pi/8), cos( 3*pi/8)] , testDCT [0,1,0,0] $ map (*2) [1, cos(3*pi/8), cos( 6*pi/8), cos( 9*pi/8)] , testDCT [0,0,1,0] $ map (*2) [1, cos(5*pi/8), cos(10*pi/8), cos(15*pi/8)] , testDCT [0,0,0,1] $ map (*2) [1, cos(7*pi/8), cos(14*pi/8), cos(21*pi/8)] -- Exact small size IDCT -- 2 , testIDCT [1,0] [1, 1 ] , testIDCT [0,1] $ map (*2) [cos(pi/4), cos(3*pi/4)] -- 4 , testIDCT [1,0,0,0] [1, 1, 1, 1 ] , testIDCT [0,1,0,0] $ map (*2) [cos( pi/8), cos( 3*pi/8), cos( 5*pi/8), cos( 7*pi/8) ] , testIDCT [0,0,1,0] $ map (*2) [cos( 2*pi/8), cos( 6*pi/8), cos(10*pi/8), cos(14*pi/8) ] , testIDCT [0,0,0,1] $ map (*2) [cos( 3*pi/8), cos( 9*pi/8), cos(15*pi/8), cos(21*pi/8) ] ] -- A single real-valued impulse at the beginning of an otherwise zero -- vector should be replicated in every real component of the result, -- and all the imaginary components should be zero. t_impulse :: Double -> Positive Int -> Bool t_impulse k (Positive m) = G.all (c_near i) (fft v) where v = i `G.cons` G.replicate (n-1) 0 i = k :+ 0 n = 1 `shiftL` (m .&. 6) -- If a real-valued impulse is offset from the beginning of an -- otherwise zero vector, the sum-of-squares of each component of the -- result should equal the square of the impulse. t_impulse_offset :: Double -> Positive Int -> Positive Int -> Bool t_impulse_offset k (Positive x) (Positive m) = G.all ok (fft v) where v = G.concat [G.replicate xn 0, G.singleton i, G.replicate (n-xn-1) 0] ok (re :+ im) = within ulps (re*re + im*im) (k*k) i = k :+ 0 xn = x `rem` n n = 1 `shiftL` (m .&. 6) -- Test that (ifft . fft ≈ id) -- -- Approximate equality here is tricky. Smaller values of vector tend -- to have large relative error. Thus we should test that vectors as -- whole are approximate equal. t_fftInverse :: (HasNorm (U.Vector a), U.Unbox a, Num a, Show a, Arbitrary a) => (U.Vector a -> U.Vector a) -> Property t_fftInverse roundtrip = do x <- genFftVector let n = G.length x x' = roundtrip x d = G.zipWith (-) x x' nd = vectorNorm d nx = vectorNorm x id $ printTestCase "Original vector" $ printTestCase (show x ) $ printTestCase "Transformed one" $ printTestCase (show x') $ printTestCase (printf "Length = %i" n) $ printTestCase (printf "|x - x'| / |x| = %.6g" (nd / nx)) $ nd <= 3e-14 * nx -- Test discrete cosine transform testDCT :: [Double] -> [Double] -> Test testDCT (U.fromList -> vec) (U.fromList -> res) = testAssertion ("DCT test for " ++ show vec) $ vecEqual 3e-14 (dct vec) res -- Test inverse discrete cosine transform testIDCT :: [Double] -> [Double] -> Test testIDCT (U.fromList -> vec) (U.fromList -> res) = testAssertion ("IDCT test for " ++ show vec) $ vecEqual 3e-14 (idct vec) res ---------------------------------------------------------------- -- With an error tolerance of 8 ULPs, a million QuickCheck tests are -- likely to all succeed. With a tolerance of 7, we fail around the -- half million mark. ulps :: Int ulps = 8 c_near :: CD -> CD -> Bool c_near (a :+ b) (c :+ d) = within ulps a c && within ulps b d -- Arbitrary vector for FFT od DCT genFftVector :: (U.Unbox a, Arbitrary a) => Gen (U.Vector a) genFftVector = do n <- (2^) <$> choose (1,9::Int) -- Size of vector G.fromList <$> vectorOf n arbitrary -- Vector to transform -- Ad-hoc type class for calculation of vector norm class HasNorm a where vectorNorm :: a -> Double instance HasNorm (U.Vector Double) where vectorNorm = sqrt . U.sum . U.map (\x -> x*x) instance HasNorm (U.Vector CD) where vectorNorm = sqrt . U.sum . U.map (\(x :+ y) -> x*x + y*y) -- Approximate equality for vectors vecEqual :: Double -> U.Vector Double -> U.Vector Double -> Bool vecEqual ε v u = vectorNorm (U.zipWith (-) v u) < ε * vectorNorm v
00tau/statistics
tests/Tests/Transform.hs
bsd-2-clause
5,615
0
21
1,497
2,227
1,217
1,010
94
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} module LiuMS where import Control.Monad import Control.Monad.Reader import Control.Monad.Trans.Except import Control.Monad.IO.Class import System.Directory import Data.ByteString.Lazy.Char8 (pack) import Text.Blaze.Html (Html) import Text.Blaze.Internal (unsafeByteString) import Text.Pandoc.Options import Text.Pandoc.Readers.Markdown import Text.Pandoc.Writers.HTML import Servant hiding (Handler) import Servant.Utils.StaticFiles import System.FilePath (addTrailingPathSeparator) import Network.Wai import Network.Wai.Application.Static (staticApp, defaultFileServerSettings) import Servant.ContentType.PlainHtml import Servant.ContentType.Processable import LiuMS.Template.Basic import LiuMS.Config import LiuMS.CacheManager type Gets = Get '[PlainHtml :<- Basic] Html type SiteAPI = ConfiglessAPI :<|> ConfigfulAPI type ConfiglessAPI = "static" :> Raw type ConfigfulAPI = Gets :<|> "about" :> Gets type PostsAPI = Capture "year" Integer :> Capture "month" Integer :> (Gets :<|> Raw) type ProjectsAPI = Capture "project" String :> (Gets :<|> Raw) hostPage :: FilePath -> Handler Html hostPage page = do root <- askContentPath let pageDir = root ++ "/contents/" ++ page ++ "/" let textPath = pageDir ++ "index.md" exists <- liftIO $ doesFileExist textPath unless exists $ lift $ throwE fileNotFoundErr textFile <- liftIO $ readFile textPath let (Right markdown) = readMarkdown def textFile return $ writeHtml def markdown where fileNotFoundErr = err404 { errBody = pack $ page ++ " not found." } configfulServer :: ServerT ConfigfulAPI Handler configfulServer = load "index" :<|> load "about" where load :: FilePath -> Handler Html load path = do manager <- askCacheManager result <- lift $ loadResource "md" manager path return $ unsafeByteString result server :: Config -> Server SiteAPI server config = serveDirectory (contentPath config ++ "/static") :<|> enter (runHandlerNat config) configfulServer type Handler = ReaderT Config (ExceptT ServantErr IO) runHandlerNat :: Config -> (Handler :~> ExceptT ServantErr IO) runHandlerNat config = Nat (flip runReaderT config)
notcome/liu-ms-adult
src/LiuMS.hs
bsd-3-clause
2,373
0
12
452
623
335
288
62
1
----------------------------------------------------------------------------- -- -- Module : Code.Generating.Utils.Syntax.Exp -- Copyright : (c) 2011 Lars Corbijn -- License : BSD-style (see the file /LICENSE) -- -- Maintainer : -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Code.Generating.Utils.Syntax.Exp ( var', con', errorExp, otherwiseExp, var, con, (@@), (\->), (.$.), (...), (=@=), (/@=), (+@+), infixAppS, ) where ----------------------------------------------------------------------------- import Language.Haskell.Exts.Syntax import Code.Generating.Utils.No import Code.Generating.Utils.Syntax.Names ----------------------------------------------------------------------------- infixl 9 @@ infixr 8 ... infixr 5 +@+ infix 4 =@=, /@= infixr 0 .$. var' :: String -> Exp var' = Var . unQual' var :: Name -> Exp var = Var . UnQual con' :: String -> Exp con' = Con . unQual' con :: Name -> Exp con = Con . UnQual errorExp :: String -> Exp errorExp = App (var' "error") . Lit . String otherwiseExp :: Exp otherwiseExp = var' "otherwise" -- Opperators (@@) :: Exp -> Exp -> Exp (@@) = App (.$.) :: Exp -> Exp -> Exp (.$.) = infixAppS "$" (...) :: Exp -> Exp -> Exp (...) = infixAppS "." (=@=), (/@=) :: Exp -> Exp -> Exp (=@=) = infixAppS "==" (/@=) = infixAppS "/=" (+@+) :: Exp -> Exp -> Exp (+@+) = infixAppS "++" (\->) :: [Pat] -> Exp -> Exp (\->) = Lambda noSrcLoc infixAppS :: String -> Exp -> Exp -> Exp infixAppS inf ex1 ex2 = InfixApp ex1 (QVarOp $ unQualSym' inf) ex2 -----------------------------------------------------------------------------
Laar/CodeGenerating
src/Code/Generating/Utils/Syntax/Exp.hs
bsd-3-clause
1,715
0
9
307
461
288
173
44
1
module SMACCMPilot.GCS.Gateway.ByteString where import Data.ByteString (ByteString) import qualified Data.ByteString as B import Text.Printf import SMACCMPilot.GCS.Gateway.Monad bytestringPad :: Integer -> ByteString -> GW ByteString bytestringPad l bs = if B.length bs <= len then return $ bs `B.append` (B.pack $ replicate (len - B.length bs) 0) else writeErr "bytestringPad got oversized bytestring" >> return bs where len = fromInteger l bytestringDebugger :: String -> ByteString -> GW ByteString bytestringDebugger tag bs = writeDbg msg >> return bs where msg = printf "%s ByteString %d [%s]" tag (B.length bs) body body = fixup (unwords (map hexdig (B.unpack bs))) hexdig = printf "0x%0.2x," -- Drop last char because the above map/unwords is bad hack fixup = reverse . drop 1 . reverse bytestringDebugWhen :: (ByteString -> Bool) -> String -> ByteString -> GW ByteString bytestringDebugWhen p tag bs = case p bs of True -> writeDbg msg >> return bs False -> return bs where msg = printf "%s ByteString %d [%s]" tag (B.length bs) body body = fixup (unwords (map hexdig (B.unpack bs))) hexdig = printf "0x%0.2x," -- Drop last char because the above map/unwords is bad hack fixup = reverse . drop 1 . reverse
GaloisInc/smaccmpilot-gcs-gateway
SMACCMPilot/GCS/Gateway/ByteString.hs
bsd-3-clause
1,323
0
14
303
404
208
196
26
2
{-# LANGUAGE OverloadedStrings #-} module HStyle.Block.Tests ( tests ) where import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, (@?=)) import qualified Data.Text as T import HStyle.Block tests :: Test tests = testGroup "HStyle.Block.Tests" [ testCase "subBlock_01" subBlock_01 , testCase "updateSubBlock_01" updateSubBlock_01 ] subBlock_01 :: Assertion subBlock_01 = toLines (subBlock 2 3 poem) @?= ["A little man who wasn't there", "He wasn't there again today"] updateSubBlock_01 :: Assertion updateSubBlock_01 = toLines (updateSubBlock old new poem) @?= [ "Last night I saw upon the stair" , "A little man who wasn't there..." , "He wasn't there again today..." , "Oh, how I wish he'd go away" ] where old = subBlock 2 3 poem new = mapLines (`T.append` "...") old poem :: Block poem = fromText "Last night I saw upon the stair\n\ \A little man who wasn't there\n\ \He wasn't there again today\n\ \Oh, how I wish he'd go away"
mightybyte/hstyle
tests/HStyle/Block/Tests.hs
bsd-3-clause
1,079
0
8
233
214
125
89
26
1
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Main ( main ) where -------------------------------------------------------------------------------- import Control.Concurrent (forkIO) import Control.Monad (forever, unless) import Control.Monad.Trans (liftIO) import Data.Aeson import Network.Socket (withSocketsDo) import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import qualified Data.Text.IO as T import qualified Data.Set as S import qualified Network.WebSockets as WS -------------------------------------------------------------------------------- app :: WS.ClientApp () app conn = do putStrLn "Connected!" -- Fork a thread that writes WS data to stdout _ <- forkIO $ forever $ do msg <- WS.receiveData conn let msgLBS = LBS.fromStrict (encodeUtf8 msg) let eWorld = eitherDecode msgLBS :: Either String World liftIO $ T.putStrLn msg case eWorld of Left err -> liftIO $ print err Right world -> do liftIO $ print world let mDir = getNextMove world case mDir of Just dir -> do sendCommand conn DropBomb sendCommand conn (dirToCommand dir) Nothing -> return () sendCommand conn (SetName "Santa's Lazy Haskellers") -- Read from stdin and write to WS let loop = do line <- T.getLine let command = parseCommand line sendCommand conn command loop -- unless (T.null line) $ WS.sendTextData conn line >> loop loop WS.sendClose conn ("Bye!" :: Text) -------------------------------------------------------------------------------- main :: IO () main = withSocketsDo $ WS.runClient "10.112.155.244" 8080 "/" app data Command = Look | DropBomb | SetName String | MoveNorth | MoveSouth | MoveEast | MoveWest deriving Show instance ToJSON Command where toJSON com@(SetName name) = object ["command" .= ["SetName", name]] toJSON com = object ["command" .= show com] parseCommand :: T.Text -> Command parseCommand "h" = MoveWest parseCommand "j" = MoveSouth parseCommand "k" = MoveNorth parseCommand "l" = MoveEast parseCommand "b" = DropBomb parseCommand _ = Look sendCommand :: WS.Connection -> Command -> IO () sendCommand conn command = do let jsonCommand = encode command LBS.putStrLn jsonCommand WS.sendTextData conn jsonCommand data World = World { walls :: [Wall] , players :: [Player] , bombs :: [Bomb] } deriving Show instance FromJSON World where parseJSON (Object v) = World <$> v.: "walls" <*> v .: "players" <*> v .: "bombs" {- {"alive":true,"type":"Strong","position":{"x":0,"y":0} -} data Wall = Wall { wAlive :: Bool , wStrength :: WallStrength , wPosition :: Position } deriving Show instance FromJSON Wall where parseJSON (Object v) = Wall <$> v .: "alive" <*> v.: "type" <*> v.: "position" data WallStrength = Strong | Weak deriving Show instance FromJSON WallStrength where parseJSON (String s) = return $ toWallStrength s parseJSON e = error $ "wall strength error: " ++ show e toWallStrength :: T.Text -> WallStrength toWallStrength "Strong" = Strong toWallStrength "Weak" = Weak data Position = Position { posX :: Int , posY :: Int } deriving Show instance FromJSON Position where parseJSON (Object v) = Position <$> v .: "x" <*> v.: "y" {- {"alive":true,"score":-2,"name":"Pythonistas","id":"36242761-d09a-4010-8570-907798ae8945","position":{"x":1,"y":9}} -} data Player = Player { pAlive :: Bool , pScore :: Int , pName :: String , pID :: String , pPosition :: Position } deriving Show instance FromJSON Player where parseJSON (Object v) = Player <$> v .: "alive" <*> v .: "score" <*> v .: "name" <*> v .: "id" <*> v .: "position" {- {"blast":null,"position":{"x":1,"y":2}} -} data Bomb = Bomb { bBlast :: Maybe () , bPosition :: Position } deriving Show instance FromJSON Bomb where parseJSON (Object v) = Bomb <$> v .: "blast" <*> v .: "position" getMe :: [Player] -> Maybe Player getMe (p:ps) = if pName p == "Santa's Lazy Haskellers" then Just p else getMe ps getMe _ = Nothing dirToCommand :: Direction -> Command dirToCommand North = MoveNorth dirToCommand South = MoveSouth dirToCommand East = MoveEast dirToCommand West = MoveWest data Direction = North | East | South | West deriving (Eq, Ord, Show) getNextMove :: World -> Maybe Direction getNextMove world = case getMe (players world) of Nothing -> Nothing Just player -> Just $ nextMove player (walls world) nextMove :: Player -> [Wall] -> Direction nextMove player walls = head (S.toList (openMoves player walls)) openMoves :: Player -> [Wall] -> S.Set Direction openMoves player walls = S.fromList [North, East, South, West] `S.difference` closedDirs where closedDirs = closedMoves player walls closedMoves :: Player -> [Wall] -> S.Set Direction closedMoves _ [] = S.empty closedMoves player walls = go S.empty player walls where go dirs _ [] = dirs go dirs p (w:ws) = let newDirs = case p `nextTo` w of Just dir -> S.insert dir dirs Nothing -> dirs in go newDirs p ws nextTo :: Player -> Wall -> Maybe Direction nextTo player wall = let wX = posX (wPosition wall) wY = posY (wPosition wall) pX = posX (pPosition player) pY = posY (pPosition player) dX = pX - wX dY = pY - wY in dir dX dY where dir 1 0 = Just East dir (-1) 0 = Just West dir 0 1 = Just North dir 0 (-1) = Just South dir _ _ = Nothing
mattjbray/super-bomber-elf-haskell
app/Main.hs
bsd-3-clause
5,885
0
23
1,452
1,768
920
848
159
5
-- | -- Navigable tree structure which allow a program to traverse -- up the tree as well as down. -- copied and modified from HXML (<http://www.flightlab.com/~joe/hxml/>) -- module Yuuko.Data.NavTree ( module Yuuko.Data.NavTree , module Yuuko.Data.Tree.NTree.TypeDefs ) where import Yuuko.Data.Tree.NTree.TypeDefs -- ----------------------------------------------------------------------------- -- NavTree -- -- | navigable tree with nodes of type node -- -- a navigable tree consists of a n-ary tree for the current fragment tree, -- a navigable tree for all ancestors, and two n-ary trees for -- the previous- and following siblings data NavTree a = NT (NTree a) -- self [NavTree a] -- ancestors [NTree a] -- previous siblings (in reverse order) [NTree a] -- following siblings deriving (Show, Eq, Ord) -- ----------------------------------------------------------------------------- -- | -- converts a n-ary tree in a navigable tree ntree :: NTree a -> NavTree a ntree nd = NT nd [] [] [] -- | -- converts a navigable tree in a n-ary tree subtreeNT :: NavTree a -> NTree a subtreeNT (NT nd _ _ _) = nd -- | -- function for selecting the value of the current fragment tree dataNT :: NavTree a -> a dataNT (NT (NTree a _) _ _ _) = a -- ----------------------------------------------------------------------------- -- functions for traversing up, down, left and right in a navigable tree upNT , downNT , leftNT , rightNT :: NavTree a -> Maybe (NavTree a) upNT (NT _ (p:_) _ _) = Just p upNT (NT _ [] _ _) = Nothing downNT t@(NT (NTree _ (c:cs)) u _ _) = Just (NT c (t:u) [] cs) downNT (NT (NTree _ [] ) _ _ _) = Nothing leftNT (NT s u (l:ls) r) = Just (NT l u ls (s:r)) leftNT (NT _ _ [] _) = Nothing rightNT (NT s u l (r:rs)) = Just (NT r u (s:l) rs) rightNT (NT _ _ _ [] ) = Nothing -- preorderNT t = t : concatMap preorderNT (children t) -- where children = maybe [] (maybeStar rightNT) . downNT preorderNT :: NavTree a -> [NavTree a] preorderNT = visit [] where visit k t = t : maybe k (visit' k) (downNT t) visit' k t = visit (maybe k (visit' k) (rightNT t)) t revPreorderNT :: NavTree a -> [NavTree a] revPreorderNT t = t : concatMap revPreorderNT (reverse (children t)) where children = maybe [] (maybeStar rightNT) . downNT getChildrenNT :: NavTree a -> [NavTree a] getChildrenNT node = maybe [] follow (downNT node) where follow n = n : maybe [] follow (rightNT n) -- ----------------------------------------------------------------------------- -- Miscellaneous useful combinators -- | -- Kleisli composition: o' :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c) f `o'` g = \x -> g x >>= f -- Some useful anamorphisms: maybeStar, maybePlus :: (a -> Maybe a) -> a -> [a] maybeStar f a = a : maybe [] (maybeStar f) (f a) maybePlus f a = maybe [] (maybeStar f) (f a) -- -----------------------------------------------------------------------------
nfjinjing/yuuko
src/Yuuko/Data/NavTree.hs
bsd-3-clause
3,027
42
12
668
1,002
530
472
49
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} -- {-# LANGUAGE DataKinds #-} -- {-# LANGUAGE TypeOperators #-} module Ivory.Opts.CFG ( callGraphDot -- ** Generate a dot file of the control flow for a program. , SizeMap(..) -- ** Implementation-defined size map for stack elements. , defaultSizeMap , hasLoop -- ** Does the control-flow graph contain a loop? , WithTop , maxStack -- ** What is the maximum stack size of the program? ) where import qualified Ivory.Language.Array as I import qualified Ivory.Language.Syntax.AST as I import qualified Ivory.Language.Syntax.Type as I import qualified Data.Graph.Inductive as G import Prelude hiding (lookup) import Data.Monoid import System.FilePath import Data.Maybe import Data.List hiding (lookup) import Control.Applicative import qualified Data.IntMap as M import MonadLib (StateT, get, set, Id, StateM, runM) import MonadLib.Derive (derive_get, derive_set, Iso(..)) -- import Ivory.Language hiding (Top) -------------------------------------------------------------------------------- -- Types -- | Add Top to a type. data WithTop a = Top | Val a deriving (Eq, Functor) instance Show a => Show (WithTop a) where show Top = "Top" show (Val a) = show a instance Ord a => Ord (WithTop a) where compare Top (Val _) = GT compare (Val _) Top = LT compare Top Top = EQ compare (Val a) (Val b) = compare a b instance Applicative WithTop where pure a = Val a Val _ <*> Top = Top Val f <*> (Val a) = Val (f a) _ <*> _ = Top type Size = Integer type CallNm = String -- | We track those objects for which the size might be -- implementation-dependent. data StackType = TyStruct String -- ^ Name of struct | TyArr StackType Size -- ^ Array and size | Ptr -- ^ Pointer or ref type | TyVoid | TyInt IntSize | TyWord WordSize | TyBool | TyChar | TyFloat | TyDouble deriving (Show, Eq) data IntSize = Int8 | Int16 | Int32 | Int64 deriving (Show,Eq) data WordSize = Word8 | Word16 | Word32 | Word64 deriving (Show,Eq) data (Show a, Eq a) => Block a = Stmt a | Branch [Block a] [Block a] | Loop (Maybe Integer) [Block a] -- If we know how many loops we make, we -- store it. Otherwise, `Nothing`. deriving (Show, Eq) type Control = Block CallNm -- ^ Name of function being called type Alloc = Block StackType -- ^ Memory being allocated -- | Describes the CFG and memory usage for a single procedure. data ProcInfo = ProcInfo { procSym :: CallNm , params :: [StackType] -- ^ Parameters pushed onto the stack. , alloc :: [Alloc] -- ^ Allocated elements. , calls :: [Control] } deriving (Show, Eq) data ModuleInfo = ModuleInfo { modName :: String , procs :: [ProcInfo] } deriving (Show, Eq) -------------------------------------------------------------------------------- -- Procedure Analysis toStackTyped :: I.Typed a -> StackType toStackTyped ty = toStackType (I.tType ty) toStackType :: I.Type -> StackType toStackType ty = case ty of I.TyStruct nm -> TyStruct nm I.TyArr i t -> TyArr (toStackType t) (fromIntegral i) I.TyRef{} -> Ptr I.TyConstRef{} -> Ptr I.TyPtr{} -> Ptr I.TyVoid -> TyVoid I.TyInt i -> TyInt (toIntType i) I.TyWord w -> TyWord (toWordType w) I.TyIndex _n -> toStackType I.ixRep I.TyBool -> TyBool I.TyChar -> TyChar I.TyFloat -> TyFloat I.TyDouble -> TyDouble t -> error $ "Unhandled stack type: " ++ show t toIntType :: I.IntSize -> IntSize toIntType i = case i of I.Int8 -> Int8 I.Int16 -> Int16 I.Int32 -> Int32 I.Int64 -> Int64 toWordType :: I.WordSize -> WordSize toWordType i = case i of I.Word8 -> Word8 I.Word16 -> Word16 I.Word32 -> Word32 I.Word64 -> Word64 cfgProc :: I.Proc -> ProcInfo cfgProc proc = ProcInfo { procSym = I.procSym proc , params = map toStackTyped (I.procArgs proc) , alloc = concatMap toAlloc (I.procBody proc) , calls = concatMap toCall (I.procBody proc) } toAlloc :: I.Stmt -> [Alloc] toAlloc stmt = case stmt of I.Assign ty _ _ -> [Stmt $ toStackType ty] I.AllocRef ty _ _ -> [Stmt $ toStackType ty] I.Deref ty _ _ -> [Stmt $ toStackType ty] -- Descend into blocks I.IfTE _ blk0 blk1 -> [ Branch (concatMap toAlloc blk0) (concatMap toAlloc blk1) ] -- For the loop variable. I.Loop _ e _ blk -> let ty = I.ixRep in [Stmt (toStackType ty), Loop (getIdx e) (concatMap toAlloc blk)] I.Forever blk -> [Loop Nothing (concatMap toAlloc blk)] _ -> [] toCall :: I.Stmt -> [Control] toCall stmt = case stmt of I.IfTE _ blk0 blk1 -> [ Branch (concatMap toCall blk0) (concatMap toCall blk1) ] I.Call _ _ nm _ -> case nm of I.NameSym sym -> [Stmt sym] I.NameVar _ -> error $ "XXX need to implement function pointers." I.Loop _ e _ blk -> [Loop (getIdx e) (concatMap toCall blk)] _ -> [] getIdx :: I.Expr -> Maybe Integer getIdx e = case e of I.ExpLit (I.LitInteger i) -> Just i _ -> Nothing -------------------------------------------------------------------------------- -- Call-graph construction from a module. -- type Node = G.LNode ProcInfo -- | A call graph is a graph in which nodes are labeled by their procedure info -- and edges are unlabeled. type CFG = G.Gr ProcInfo () flattenControl :: Control -> [CallNm] flattenControl ctrl = case ctrl of Stmt str -> [str] Branch ctrl0 ctrl1 -> concatMap flattenControl ctrl0 ++ concatMap flattenControl ctrl1 Loop _ ctrl0 -> concatMap flattenControl ctrl0 cfgModule :: I.Module -> ModuleInfo cfgModule m = ModuleInfo { modName = I.modName m , procs = map cfgProc ps } where ps = I.public (I.modProcs m) ++ I.private (I.modProcs m) -- | Construct a control-flow graph from an Ivory module. cfg :: I.Module -> CFG cfg m = G.insEdges (concatMap go nodes) $ G.insNodes nodes G.empty where nodes :: [G.LNode ProcInfo] nodes = zip [0,1..] (procs $ cfgModule m) go :: (Int, ProcInfo) -> [G.LEdge ()] go (i,p) = let outCalls = concatMap flattenControl (calls p) in let outIdxs = catMaybes (map (lookup nodes) outCalls) in zip3 (repeat i) outIdxs (repeat ()) -- outboud edges lookup ls sym | [] <- ls = Nothing | ((i,p):_) <- ls , procSym p == sym = Just i | (_:ls') <- ls = lookup ls' sym | otherwise = error "Unreachable in cfg" -- To make GHC happy. -- | Just label the nodes with the function names. procSymGraph :: CFG -> G.Gr CallNm () procSymGraph = G.nmap procSym -- | Does the program have a loop in it? hasLoop :: CFG -> Bool hasLoop = G.hasLoop -------------------------------------------------------------------------------- -- Stack usage analysis. data SizeMap = SizeMap { stackElemMap :: StackType -> Size -- ^ Mapping from `StackType` to their -- implementation-dependent size. , retSize :: Size -- ^ Size of a return address. } -- | Maps everything to being size 1. Useful for testing. defaultSizeMap :: SizeMap defaultSizeMap = SizeMap { stackElemMap = const 1 , retSize = 1 } -- A mapping from `Node` (Ints) to the maximum stack usage for that function. type MaxMap = M.IntMap Size newtype MaxState a = MaxState { unSt :: StateT MaxMap Id a } deriving (Functor, Monad, Applicative) instance StateM MaxState MaxMap where get = derive_get (Iso MaxState unSt) set = derive_set (Iso MaxState unSt) emptyMaxSt :: MaxMap emptyMaxSt = M.empty getMaxMap :: MaxState MaxMap getMaxMap = return =<< get -- | Takes a procedure name, a control-flow graph, and a `SizeMap` and produces -- the maximum stack usage starting at the procedure give. Returns `Top` if -- there is an unanalyzable loop in the program (ie., non-constant loop) and -- @Val max@ otherwise. maxStack :: CallNm -> CFG -> SizeMap -> WithTop Size maxStack proc cf szmap = go proc where go p = fst $ runM (unSt (maxStack' cf szmap [] (findNode cf p))) emptyMaxSt -- Get the node from it's name. findNode :: CFG -> CallNm -> G.Node findNode cf proc = fst $ fromMaybe (error $ "Proc " ++ proc ++ " is not in the graph!") (find ((== proc) . procSym . snd) (G.labNodes cf)) maxStack' :: CFG -> SizeMap -> [G.Node] -> G.Node -> MaxState (WithTop Size) maxStack' cf szmap visited curr | curr `elem` visited = return Top -- A loop is detected. | otherwise = maxStackNode where -- Process the max stack for a single node. maxStackNode :: MaxState (WithTop Size) maxStackNode = do blkMax <- goBlks cf szmap visited curr alloc' calls' let sz = (topAllocSz + paramsSz + retSize szmap +) <$> blkMax return sz where cxt = G.context cf curr procInfo = G.lab' cxt alloc' = alloc procInfo calls' = calls procInfo -- Top-level allocation topAllocSz :: Size topAllocSz = getSize szmap (getBlock alloc') paramsSz :: Size paramsSz = getSize szmap (params procInfo) goBlks :: CFG -> SizeMap -> [G.Node] -> G.Node -> [Alloc] -> [Control] -> MaxState (WithTop Size) goBlks cf szmap visited curr acs cns = case (acs, cns) of -- Done with all blocks/statements in this function. ([] ,[]) -> return (Val 0) (Branch a0 a1:acs', Branch c0 c1:cns') -> do sz0 <- goBlks' a0 c0 sz1 <- goBlks' a1 c1 sz2 <- goBlks' acs' cns' return (liftA2 max sz0 sz1 <+> sz2) -- There's no new loop allocation, just assignments. So we assume that on -- each iteration, the stack usage doesn't change. (Loop _ a:acs', Loop _ c:cns') -> do sz0 <- goBlks' a c sz1 <- goBlks' acs' cns' return (sz0 <+> sz1) -- case idx of -- -- Unknown loop bound. -- Nothing -> if sz0 == Val 0 then return sz1 -- else return Top -- Did some allocation in the loop, so -- -- can't compute. -- Just _ -> -- There is either a straight-line call or assignment. _ -> do sz0 <- goBlk cf szmap visited curr (getBlock acs) (getBlock cns) sz1 <- goBlks' (nxtBlock acs) (nxtBlock cns) return (sz0 <+> sz1) where goBlks' = goBlks cf szmap visited curr goBlk :: CFG -> SizeMap -> [G.Node] -> G.Node -> [StackType] -> [CallNm] -> MaxState (WithTop Size) goBlk cf szmap visited curr acs cns = do maxMp <- getMaxMap let localAlloc = getSize szmap acs let callNodes = map (findNode cf) cns let allCalls = zip callNodes (map (flip M.lookup $ maxMp) callNodes) newMaxs <- mapM cachedCalls allCalls return $ Val localAlloc <+> if null newMaxs then Val 0 -- Depends on Top being >= all vals. else maximum newMaxs where cachedCalls :: (G.Node, Maybe Size) -> MaxState (WithTop Size) cachedCalls (n, msz) | Just sz <- msz = return (Val sz) | otherwise = maxStack' cf szmap (curr:visited) n (<+>) :: Num a => WithTop a -> WithTop a -> WithTop a (<+>) = liftA2 (+) -- Get the cumulative sizes of allocated things. getSize :: SizeMap -> [StackType] -> Size getSize szmap = sum . map (stackElemMap szmap) -- Get the prefix of a list of @[Block a] in the current block. getBlock :: (Show a, Eq a) => [Block a] -> [a] getBlock bls | (Stmt b:bs) <- bls = b : getBlock bs | otherwise = [] nxtBlock :: (Show a, Eq a) => [Block a] -> [Block a] nxtBlock bls | (Stmt _:bs) <- bls = nxtBlock bs | otherwise = bls -- | Call-graph output. Takes a start function foo, a filepath, and emits the -- graph named "foo.dot" in the filepath. callGraphDot :: CallNm -> FilePath -> [I.Module] -> IO CFG callGraphDot proc path mods = writeFile (path </> proc `addExtension` "dot") grOut >> return graph where m = mconcat mods grOut = graphviz filterG (I.modName m) filterG :: G.Gr CallNm () filterG = let closure = G.reachable (findNode graph proc) graph in G.delNodes (G.nodes graph \\ closure) (procSymGraph graph) graph = cfg m -------------------------------------------------------------------------------- -- Adapted from fgl (BSD3) to remove sizing info. graphviz :: (G.Graph g, Show a, Show b) => g a b -- ^ The graph to format -> String -- ^ The title of the graph -> String graphviz g t = let n = G.labNodes g e = G.labEdges g ns = concatMap sn n es = concatMap se e in "digraph "++t++" {\n" ++ ns ++ es ++"}" where sn (n, a) | sa == "" = "" | otherwise = '\t':(show n ++ sa ++ "\n") where sa = sl a se (n1, n2, b) = '\t':(show n1 ++ " -> " ++ show n2 ++ sl b ++ "\n") sl :: (Show a) => a -> String sl a = let l = sq (show a) in if (l /= "()") then (" [label = \""++l++"\"]") else "" sq :: String -> String sq s@[_] = s sq ('"':s) | last s == '"' = init s | otherwise = s sq ('\'':s) | last s == '\'' = init s | otherwise = s sq s = s -------------------------------------------------------------------------------- -- Testing {- fibCFG :: CFG fibCFG = cfg fibMod outGraph = writeFile "fib.dot" gr where gr = G.graphviz (procSymGraph fibCFG) "fib" (4,4) (4,4) G.Portrait ---------------------- fibMod :: Module fibMod = package "fib" $ do incl fib incl fib_aux fib :: Def ('[Uint32] :-> Uint64) fib = proc "fib" (\n -> body (ret =<< call fib_aux 0 1 n)) fib_aux :: Def ('[Uint32,Uint32,Uint32] :-> Uint64) fib_aux = proc "fib_aux" $ \ a b n -> body $ do ifte_ (n ==? 0) (ret (safeCast a)) (ret . safeCast =<< call fib_aux b (a + b) (n - 1)) fibSz = SizeMap { stackElemMap = \_ -> 1 , retSize = 1 } ------------------------------------- x :: G.Gr Int () x = G.insEdges edges gr where edges = [(0,1,()), (0,2,()), (2,1,()), (2,3,())] gr = G.insNodes nodes G.empty nodes = zip [0,1 ..] [2,3,4,1] y :: G.Gr Int () y = G.insEdges edges gr where edges = [(0,1,()), (0,2,()), (2,1,()), (1,3,())] gr = G.insNodes nodes G.empty nodes = zip [0,1 ..] [1,4,5,8] maxf :: G.Gr Int () -> G.Node -> Maybe Int maxf g n = maxf' [] n where maxf' :: [G.Node] -> G.Node -> Maybe Int maxf' visited curr | curr `elem` visited = Nothing -- We made a loop on this path! That's Top. | otherwise = liftA2 (+) (Just $ G.lab' cxt) go where cxt = G.context g curr res = map (maxf' (G.node' cxt : visited)) (G.suc' cxt) go | null (G.suc' cxt) = Just 0 -- No more successors to try | Nothing `elem` res = Nothing | otherwise = Just $ maximum (catMaybes res) -}
Hodapp87/ivory
ivory-opts/src/Ivory/Opts/CFG.hs
bsd-3-clause
15,612
31
18
4,589
4,028
2,139
1,889
298
14
{- Implements the judgement freshTy given in Chapter 5. Also defines the monad Mfresh in which these judgements can be expressed -} module HOCHC.Fresh(freshVar, freshVarx,freshRel,freshTy,freshEnv, Mfresh, lift, runStateT, runFresh) where import HOCHC.DataTypes import Control.Monad (liftM, ap) import Control.Applicative import Control.Monad.State import Control.Monad.Except type Mfresh = StateT Int (Either String) freshVar :: Mfresh Variable freshVar = state (\n->("x_"++show n,n+1)) freshVarx :: Variable -> Mfresh Variable freshVarx x = state (\n->(x++"_"++show n,n+1)) runFresh :: Monad m => StateT Int m a -> m a runFresh = flip evalStateT 0 freshRel :: DeltaEnv -> Sort -> Mfresh (Term,(Variable,Sort)) freshRel d rho = do x<-freshVar return (foldl (\ t y -> Apply t (Variable y)) (Variable x) ys, (x,iterate (Arrow Int) rho !! length ys)) where ys = map fst $ filter ((==Int).snd) d freshTy :: DeltaEnv -> Sort -> Mfresh (MonoType,DeltaEnv) freshTy d Bool = do (t,d) <- freshRel d Bool return (BoolT t,[d]) freshTy d Int = return (IntT,[]) freshTy d (Arrow Int s) = do z <- freshVar (ty,ds)<-freshTy ((z,Int):d) s return $ (ArrowT z IntT ty ,ds) freshTy d (Arrow s1 s2) = do (ty1,d1) <- freshTy d s1 (ty2,d2) <- freshTy d s2 return (ArrowT "_" ty1 ty2,d2++d1) freshEnv :: DeltaEnv -> Mfresh (Gamma,DeltaEnv) freshEnv delta = do (tys,ds) <- unzip <$> (sequence $ map (freshTy [] . snd) delta) return (zip (map fst delta) tys, concat ds)
penteract/HigherOrderHornRefinement
HOCHC/Fresh.hs
bsd-3-clause
1,553
0
15
336
697
366
331
36
1
-- The Compiler Toolkit: configuration switches -- -- Author : Manuel M. T. Chakravarty -- Created: 3 October 95 -- -- Version $Revision: 1.3 $ from $Date: 1999/09/27 08:44:42 $ -- -- Copyright (c) [1995...1999] Manuel M. T. Chakravarty -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Library General Public -- License as published by the Free Software Foundation; either -- version 2 of the License, or (at your option) any later version. -- -- This library 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 -- Library General Public License for more details. -- --- DESCRIPTION --------------------------------------------------------------- -- -- This modules is used to configure the toolkit. -- --- DOCU ---------------------------------------------------------------------- -- -- language: Haskell 98 -- -- * Must not import any other module. -- --- TODO ---------------------------------------------------------------------- -- module Text.CTK.Config (-- limits -- errorLimit, -- -- debuging -- assertEnabled) where -- compilation aborts with a fatal error, when the given number of errors -- has been raised (warnings do not count) -- errorLimit :: Int errorLimit = 20 -- specifies whether the internal consistency checks with `assert' should be -- made -- assertEnabled :: Bool assertEnabled = True
mwotton/ctkl
src/Text/CTK/Config.hs
bsd-3-clause
1,591
0
4
315
77
64
13
7
1
module Protocol.PeerSpec (spec) where import Protocol.Peer -- import Protocol.Types import Test.Hspec import qualified Data.ByteString as B -- import qualified Data.ByteString.Char8 as B8 spec :: Spec spec = do describe "buildBitField" $ do it "should build bitfield" $ do -- 1100 1000 => buildBitField 5 [0, 1, 4] `shouldBe` B.pack [200] -- 0001 0100 0100 0000 => buildBitField 12 [3, 5, 9] `shouldBe` B.pack [20, 64]
artems/FlashBit
specs/Protocol/PeerSpec.hs
bsd-3-clause
488
0
15
134
128
73
55
10
1
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-| Binary instances for the core datatypes -} module Idris.Core.Binary where import Control.Applicative ((<*>), (<$>)) import Control.Monad (liftM2) import Control.DeepSeq (($!!)) import Data.Binary import Data.Vector.Binary import qualified Data.Text as T import qualified Data.Text.Encoding as E import Idris.Core.TT instance Binary ErrorReportPart where put (TextPart msg) = do putWord8 0 ; put msg put (NamePart n) = do putWord8 1 ; put n put (TermPart t) = do putWord8 2 ; put t put (SubReport ps) = do putWord8 3 ; put ps put (RawPart r) = do putWord8 4 ; put r get = do i <- getWord8 case i of 0 -> fmap TextPart get 1 -> fmap NamePart get 2 -> fmap TermPart get 3 -> fmap SubReport get 4 -> fmap RawPart get _ -> error "Corrupted binary data for ErrorReportPart" instance Binary Provenance where put ExpectedType = putWord8 0 put (SourceTerm t) = do putWord8 1 put t put InferredVal = putWord8 2 put GivenVal = putWord8 3 put (TooManyArgs t) = do putWord8 4 put t get = do i <- getWord8 case i of 0 -> return ExpectedType 1 -> do x1 <- get return (SourceTerm x1) 2 -> return InferredVal 3 -> return GivenVal 4 -> do x1 <- get return (TooManyArgs x1) _ -> error "Corrupted binary data for Provenance" instance Binary UConstraint where put (ULT x1 x2) = putWord8 0 >> put x1 >> put x2 put (ULE x1 x2) = putWord8 1 >> put x1 >> put x2 get = do i <- getWord8 case i of 0 -> ULT <$> get <*> get 1 -> ULE <$> get <*> get _ -> error "Corrupted binary data for UConstraint" instance Binary ConstraintFC where put (ConstraintFC x1 x2) = putWord8 0 >> put x1 >> put x2 get = do i <- getWord8 case i of 0 -> liftM2 ConstraintFC get get _ -> error "Corrupted binary data for ConstraintFC" instance Binary a => Binary (Err' a) where put (Msg str) = do putWord8 0 put str put (InternalMsg str) = do putWord8 1 put str put (CantUnify x y z e ctxt i) = do putWord8 2 put x put y put z put e put ctxt put i put (InfiniteUnify n t ctxt) = do putWord8 3 put n put t put ctxt put (CantConvert x y ctxt) = do putWord8 4 put x put y put ctxt put (CantSolveGoal x ctxt) = do putWord8 5 put x put ctxt put (UnifyScope n1 n2 x ctxt) = do putWord8 6 put n1 put n2 put x put ctxt put (CantInferType str) = do putWord8 7 put str put (NonFunctionType t1 t2) = do putWord8 8 put t1 put t2 put (NotEquality t1 t2) = do putWord8 9 put t1 put t2 put (TooManyArguments n) = do putWord8 10 put n put (CantIntroduce t) = do putWord8 11 put t put (NoSuchVariable n) = do putWord8 12 put n put (NoTypeDecl n) = do putWord8 13 put n put (NotInjective x y z) = do putWord8 14 put x put y put z put (CantResolve _ t) = do putWord8 15 put t put (CantResolveAlts ns) = do putWord8 16 put ns put (IncompleteTerm t) = do putWord8 17 put t put (UniverseError x1 x2 x3 x4 x5) = do putWord8 18 put x1 put x2 put x3 put x4 put x5 put (UniqueError u n) = do putWord8 19 put u put n put (UniqueKindError u n) = do putWord8 20 put u put n put ProgramLineComment = putWord8 21 put (Inaccessible n) = do putWord8 22 put n put (NonCollapsiblePostulate n) = do putWord8 23 put n put (AlreadyDefined n) = do putWord8 24 put n put (ProofSearchFail e) = do putWord8 25 put e put (NoRewriting t) = do putWord8 26 put t put (At fc e) = do putWord8 27 put fc put e put (Elaborating str n e) = do putWord8 28 put str put n put e put (ElaboratingArg n1 n2 ns e) = do putWord8 29 put n1 put n2 put ns put e put (ProviderError str) = do putWord8 30 put str put (LoadingFailed str e) = do putWord8 31 put str put e put (ReflectionError parts e) = do putWord8 32 put parts put e put (ReflectionFailed str e) = do putWord8 33 put str put e put (WithFnType t) = do putWord8 34 put t put (CantMatch t) = do putWord8 35 put t put (ElabScriptDebug x1 x2 x3) = do putWord8 36 put x1 put x2 put x3 put (NoEliminator s t) = do putWord8 37 put s put t put (InvalidTCArg n t) = do putWord8 38 put n put t put (ElabScriptStuck x1) = do putWord8 39 put x1 put (UnknownImplicit n f) = do putWord8 40 put n put f put (NoValidAlts ns) = do putWord8 41 put ns get = do i <- getWord8 case i of 0 -> fmap Msg get 1 -> fmap InternalMsg get 2 -> do x <- get ; y <- get ; z <- get ; e <- get ; ctxt <- get ; i <- get return $ CantUnify x y z e ctxt i 3 -> do x <- get ; y <- get ; z <- get return $ InfiniteUnify x y z 4 -> do x <- get ; y <- get ; z <- get return $ CantConvert x y z 5 -> do x <- get ; y <- get return $ CantSolveGoal x y 6 -> do w <- get ; x <- get ; y <- get ; z <- get return $ UnifyScope w x y z 7 -> fmap CantInferType get 8 -> do x <- get ; y <- get return $ NonFunctionType x y 9 -> do x <- get ; y <- get return $ NotEquality x y 10 -> fmap TooManyArguments get 11 -> fmap CantIntroduce get 12 -> fmap NoSuchVariable get 13 -> fmap NoTypeDecl get 14 -> do x <- get ; y <- get ; z <- get return $ NotInjective x y z 15 -> fmap (CantResolve False) get 16 -> fmap CantResolveAlts get 17 -> fmap IncompleteTerm get 18 -> UniverseError <$> get <*> get <*> get <*> get <*> get 19 -> do x <- get ; y <- get return $ UniqueError x y 20 -> do x <- get ; y <- get return $ UniqueKindError x y 21 -> return ProgramLineComment 22 -> fmap Inaccessible get 23 -> fmap NonCollapsiblePostulate get 24 -> fmap AlreadyDefined get 25 -> fmap ProofSearchFail get 26 -> fmap NoRewriting get 27 -> do x <- get ; y <- get return $ At x y 28 -> do x <- get ; y <- get ; z <- get return $ Elaborating x y z 29 -> do w <- get ; x <- get ; y <- get ; z <- get return $ ElaboratingArg w x y z 30 -> fmap ProviderError get 31 -> do x <- get ; y <- get return $ LoadingFailed x y 32 -> do x <- get ; y <- get return $ ReflectionError x y 33 -> do x <- get ; y <- get return $ ReflectionFailed x y 34 -> fmap WithFnType get 35 -> fmap CantMatch get 36 -> do x1 <- get x2 <- get x3 <- get return (ElabScriptDebug x1 x2 x3) 37 -> do x1 <- get x2 <- get return (NoEliminator x1 x2) 38 -> do x1 <- get x2 <- get return (InvalidTCArg x1 x2) 39 -> do x1 <- get return (ElabScriptStuck x1) 40 -> do x <- get ; y <- get return $ UnknownImplicit x y 41 -> fmap NoValidAlts get _ -> error "Corrupted binary data for Err'" ----- Generated by 'derive' instance Binary FC where put x = case x of (FC x1 (x2, x3) (x4, x5)) -> do putWord8 0 put x1 put (x2 * 65536 + x3) put (x4 * 65536 + x5) NoFC -> putWord8 1 FileFC x1 -> do putWord8 2 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2x3 <- get x4x5 <- get return (FC x1 (x2x3 `div` 65536, x2x3 `mod` 65536) (x4x5 `div` 65536, x4x5 `mod` 65536)) 1 -> return NoFC 2 -> do x1 <- get return (FileFC x1) _ -> error "Corrupted binary data for FC" instance Binary Name where put x = case x of UN x1 -> do putWord8 0 put x1 NS x1 x2 -> do putWord8 1 put x1 put x2 MN x1 x2 -> do putWord8 2 put x1 put x2 NErased -> putWord8 3 SN x1 -> do putWord8 4 put x1 SymRef x1 -> do putWord8 5 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (UN x1) 1 -> do x1 <- get x2 <- get return (NS x1 x2) 2 -> do x1 <- get x2 <- get return (MN x1 x2) 3 -> return NErased 4 -> do x1 <- get return (SN x1) 5 -> do x1 <- get return (SymRef x1) _ -> error "Corrupted binary data for Name" instance Binary SpecialName where put x = case x of WhereN x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 InstanceN x1 x2 -> do putWord8 1 put x1 put x2 ParentN x1 x2 -> do putWord8 2 put x1 put x2 MethodN x1 -> do putWord8 3 put x1 CaseN x1 -> do putWord8 4; put x1 ElimN x1 -> do putWord8 5; put x1 InstanceCtorN x1 -> do putWord8 6; put x1 WithN x1 x2 -> do putWord8 7 put x1 put x2 MetaN x1 x2 -> do putWord8 8 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (WhereN x1 x2 x3) 1 -> do x1 <- get x2 <- get return (InstanceN x1 x2) 2 -> do x1 <- get x2 <- get return (ParentN x1 x2) 3 -> do x1 <- get return (MethodN x1) 4 -> do x1 <- get return (CaseN x1) 5 -> do x1 <- get return (ElimN x1) 6 -> do x1 <- get return (InstanceCtorN x1) 7 -> do x1 <- get x2 <- get return (WithN x1 x2) 8 -> do x1 <- get x2 <- get return (MetaN x1 x2) _ -> error "Corrupted binary data for SpecialName" instance Binary Const where put x = case x of I x1 -> do putWord8 0 put x1 BI x1 -> do putWord8 1 put x1 Fl x1 -> do putWord8 2 put x1 Ch x1 -> do putWord8 3 put x1 Str x1 -> do putWord8 4 put x1 B8 x1 -> putWord8 5 >> put x1 B16 x1 -> putWord8 6 >> put x1 B32 x1 -> putWord8 7 >> put x1 B64 x1 -> putWord8 8 >> put x1 (AType (ATInt ITNative)) -> putWord8 9 (AType (ATInt ITBig)) -> putWord8 10 (AType ATFloat) -> putWord8 11 (AType (ATInt ITChar)) -> putWord8 12 StrType -> putWord8 13 Forgot -> putWord8 15 (AType (ATInt (ITFixed ity))) -> putWord8 (fromIntegral (16 + fromEnum ity)) -- 16-19 inclusive VoidType -> putWord8 27 WorldType -> putWord8 28 TheWorld -> putWord8 29 get = do i <- getWord8 case i of 0 -> do x1 <- get return (I x1) 1 -> do x1 <- get return (BI x1) 2 -> do x1 <- get return (Fl x1) 3 -> do x1 <- get return (Ch x1) 4 -> do x1 <- get return (Str x1) 5 -> fmap B8 get 6 -> fmap B16 get 7 -> fmap B32 get 8 -> fmap B64 get 9 -> return (AType (ATInt ITNative)) 10 -> return (AType (ATInt ITBig)) 11 -> return (AType ATFloat) 12 -> return (AType (ATInt ITChar)) 13 -> return StrType 15 -> return Forgot 16 -> return (AType (ATInt (ITFixed IT8))) 17 -> return (AType (ATInt (ITFixed IT16))) 18 -> return (AType (ATInt (ITFixed IT32))) 19 -> return (AType (ATInt (ITFixed IT64))) 27 -> return VoidType 28 -> return WorldType 29 -> return TheWorld _ -> error "Corrupted binary data for Const" instance Binary Raw where put x = case x of Var x1 -> do putWord8 0 put x1 RBind x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 RApp x1 x2 -> do putWord8 2 put x1 put x2 RType -> putWord8 3 RConstant x1 -> do putWord8 4 put x1 RForce x1 -> do putWord8 5 put x1 RUType x1 -> do putWord8 6 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Var x1) 1 -> do x1 <- get x2 <- get x3 <- get return (RBind x1 x2 x3) 2 -> do x1 <- get x2 <- get return (RApp x1 x2) 3 -> return RType 4 -> do x1 <- get return (RConstant x1) 5 -> do x1 <- get return (RForce x1) 6 -> do x1 <- get return (RUType x1) _ -> error "Corrupted binary data for Raw" instance Binary ImplicitInfo where put x = case x of Impl x1 -> put x1 get = do x1 <- get return (Impl x1) instance (Binary b) => Binary (Binder b) where put x = case x of Lam x1 -> do putWord8 0 put x1 Pi x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 Let x1 x2 -> do putWord8 2 put x1 put x2 NLet x1 x2 -> do putWord8 3 put x1 put x2 Hole x1 -> do putWord8 4 put x1 GHole x1 x2 -> do putWord8 5 put x1 put x2 Guess x1 x2 -> do putWord8 6 put x1 put x2 PVar x1 -> do putWord8 7 put x1 PVTy x1 -> do putWord8 8 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Lam x1) 1 -> do x1 <- get x2 <- get x3 <- get return (Pi x1 x2 x3) 2 -> do x1 <- get x2 <- get return (Let x1 x2) 3 -> do x1 <- get x2 <- get return (NLet x1 x2) 4 -> do x1 <- get return (Hole x1) 5 -> do x1 <- get x2 <- get return (GHole x1 x2) 6 -> do x1 <- get x2 <- get return (Guess x1 x2) 7 -> do x1 <- get return (PVar x1) 8 -> do x1 <- get return (PVTy x1) _ -> error "Corrupted binary data for Binder" instance Binary Universe where put x = case x of UniqueType -> putWord8 0 AllTypes -> putWord8 1 NullType -> putWord8 2 get = do i <- getWord8 case i of 0 -> return UniqueType 1 -> return AllTypes 2 -> return NullType _ -> error "Corrupted binary data for Universe" instance Binary NameType where put x = case x of Bound -> putWord8 0 Ref -> putWord8 1 DCon x1 x2 x3 -> do putWord8 2 put (x1 * 65536 + x2) put x3 TCon x1 x2 -> do putWord8 3 put (x1 * 65536 + x2) get = do i <- getWord8 case i of 0 -> return Bound 1 -> return Ref 2 -> do x1x2 <- get x3 <- get return (DCon (x1x2 `div` 65536) (x1x2 `mod` 65536) x3) 3 -> do x1x2 <- get return (TCon (x1x2 `div` 65536) (x1x2 `mod` 65536)) _ -> error "Corrupted binary data for NameType" -- record concrete levels only, for now instance Binary UExp where put x = case x of UVar t -> do putWord8 0 put ((-1) :: Int) -- TMP HACK! UVal t -> do putWord8 1 put t get = do i <- getWord8 case i of 0 -> do x1 <- get return (UVar x1) 1 -> do x1 <- get return (UVal x1) _ -> error "Corrupted binary data for UExp" instance {- (Binary n) => -} Binary (TT Name) where put x = {-# SCC "putTT" #-} case x of P x1 x2 x3 -> do putWord8 0 put x1 put x2 -- put x3 V x1 -> if (x1 >= 0 && x1 < 256) then do putWord8 1 putWord8 (toEnum (x1 + 1)) else do putWord8 9 put x1 Bind x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 App _ x1 x2 -> do putWord8 3 put x1 put x2 Constant x1 -> do putWord8 4 put x1 Proj x1 x2 -> do putWord8 5 put x1 putWord8 (toEnum (x2 + 1)) Erased -> putWord8 6 TType x1 -> do putWord8 7 put x1 Impossible -> putWord8 8 UType x1 -> do putWord8 10 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get -- x3 <- get return (P x1 x2 Erased) 1 -> do x1 <- getWord8 return (V ((fromEnum x1) - 1)) 2 -> do x1 <- get x2 <- get x3 <- get return (Bind x1 x2 x3) 3 -> do x1 <- get x2 <- get return (App Complete x1 x2) 4 -> do x1 <- get return (Constant x1) 5 -> do x1 <- get x2 <- getWord8 return (Proj x1 ((fromEnum x2)-1)) 6 -> return Erased 7 -> do x1 <- get return (TType x1) 8 -> return Impossible 9 -> do x1 <- get return (V x1) 10 -> do x1 <- get return (UType x1) _ -> error "Corrupted binary data for TT"
athanclark/Idris-dev
src/Idris/Core/Binary.hs
bsd-3-clause
25,274
0
19
15,013
7,377
3,264
4,113
616
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.VertexAttribBinding -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/vertex_attrib_binding.txt ARB_vertex_attrib_binding> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.VertexAttribBinding ( -- * Enums gl_MAX_VERTEX_ATTRIB_BINDINGS, gl_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET, gl_VERTEX_ATTRIB_BINDING, gl_VERTEX_ATTRIB_RELATIVE_OFFSET, gl_VERTEX_BINDING_DIVISOR, gl_VERTEX_BINDING_OFFSET, gl_VERTEX_BINDING_STRIDE, -- * Functions glBindVertexBuffer, glVertexAttribBinding, glVertexAttribFormat, glVertexAttribIFormat, glVertexAttribLFormat, glVertexBindingDivisor ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/VertexAttribBinding.hs
bsd-3-clause
1,088
0
4
121
82
62
20
16
0
{-# LANGUAGE ViewPatterns, PatternGuards, TupleSections #-} module Input.Set(setStackage, setPlatform, setGHC) where import Control.Applicative import Data.List.Extra setStackage :: IO [String] setStackage = f . lines <$> readFile "input/stackage.txt" where f (x:xs) | Just x <- stripPrefix "constraints:" x = map (fst . word1) $ takeWhile (" " `isPrefixOf`) $ (' ':x) : xs | otherwise = f xs f [] = [] setPlatform :: IO [String] setPlatform = setPlatformWith ["incGHCLib","incLib"] setPlatformWith :: [String] -> IO [String] setPlatformWith names = do src <- lines <$> readFile "input/platform.txt" return [read lib | ",":name:lib:_ <- map words src, name `elem` names] setGHC :: IO [String] setGHC = setPlatformWith ["incGHCLib"]
ndmitchell/hogle-dead
src/Input/Set.hs
bsd-3-clause
805
0
13
178
287
150
137
18
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Dense.TH -- Copyright : (c) Christopher Chalmers -- License : BSD3 -- -- Maintainer : Christopher Chalmers -- Stability : experimental -- Portability : non-portable -- -- Contains QuasiQuotes and TemplateHaskell utilities for creating dense -- arrays, stencils and fixed length vectors. -- -- The parser for the QuasiQuotes is still a work in progress. ----------------------------------------------------------------------------- module Data.Dense.TH ( -- * Creating dense arrays dense -- * Fixed length vector , v -- * Stencils , stencil -- ** Stencils from lists , ShapeLift (..) , mkStencilTH , mkStencilTHBy ) where import Control.Applicative hiding (many, empty) import Control.Lens import Control.Monad import Data.Char import Data.Foldable as F import Data.Function (on) import qualified Data.List as List import Data.Maybe import Data.Monoid (Endo) import qualified Data.Vector as Vector import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax import Linear import qualified Linear.V as V import Text.ParserCombinators.ReadP import qualified Text.Read.Lex as Lex import Data.Dense.Generic (empty, fromListInto_) import Data.Dense.Index import Data.Dense.Stencil tupe :: [Exp] -> Exp #if __GLASGOW_HASKELL__ <= 808 tupe = TupE #else tupe = TupE . map Just #endif -- | QuasiQuoter for producing a dense arrays using a custom parser. -- Values are space separated, while also allowing infix expressions -- (like @5/7@). If you want to apply a function, it should be done in -- brackets. Supports 1D, 2D and 3D arrays. -- -- The number of rows/columns must be consistent thought out the -- array. -- -- === __Examples__ -- -- - 1D arrays are of the following form form. Note these can be -- used as 'V1', 'V2' or 'V3' arrays. -- -- @ -- ['dense'| 5 -3 1 -3 5 |] :: ('R1' f, 'Vector.Vector' v a, 'Num' a) => 'Data.Dense.Array' v f a -- @ -- -- -- - 2D arrays are of the following form. Note these can be used as -- 'V2' or 'V3' arrays. -- -- @ -- chars :: 'Data.Dense.UArray' 'V2' 'Char' -- chars :: ['dense'| -- \'a\' \'b\' \'c\' -- \'d\' \'e\' \'f\' -- \'g\' \'h\' \'i\' -- |] -- @ -- -- - 3D arrays are of the following form. Note the order in which -- 'dense' formats the array. The array @a@ is such that @a ! 'V3' -- x y z = "xyz"@ -- -- @ -- a :: 'Data.Dense.BArray' 'V3' 'String' -- a = ['dense'| -- "000" "100" "200" -- "010" "110" "210" -- "020" "120" "220" -- -- "001" "101" "201" -- "011" "111" "211" -- "021" "121" "221" -- -- "002" "102" "202" -- "012" "112" "212" -- "022" "122" "222" -- |] -- @ -- dense :: QuasiQuoter dense = QuasiQuoter { quoteExp = parseDense , quotePat = error "dense can't be used in pattern" , quoteType = error "dense can't be used in type" , quoteDec = error "dense can't be used in dec" } -- | List of expressions forming a stencil. To be either turned into -- either a real list or an unfolded stencil. parseDense :: String -> Q Exp parseDense str = case mapM (mapM parseLine) (map lines ps) of Left err -> fail err Right [] -> [| empty |] Right [[as]] -> uncurry mkArray $ parse1D as Right [ass] -> uncurry mkArray $ parse2D ass Right asss -> uncurry mkArray $ parse3D asss where ps = paragraphs str -- | Split a string up into paragraphs separated by a new line. Extra -- newlines inbetween paragraphs are stripped. paragraphs :: String -> [String] paragraphs = go [] . strip where go ps ('\n':'\n':xs) = [reverse ps] ++ go [] (strip xs) go ps (x:xs) = go (x:ps) xs go [] [] = [] go ps [] = [reverse $ strip ps] strip = dropWhile (\x -> x == '\n' || x == ' ') -- Creating arrays ----------------------------------------------------- mkArray :: ShapeLift f => Layout f -> [Exp] -> Q Exp mkArray l as = do lE <- liftShape' l let fromListE = AppE (VarE 'fromListInto_) lE pure $ AppE fromListE (ListE as) ------------------------------------------------------------------------ -- V n a ------------------------------------------------------------------------ -- | Type safe 'QuasiQuoter' for fixed length vectors 'V.V'. Values are -- space separated. Can be used as expressions or patterns. -- -- @ -- [v| x y z w q r |] :: 'V.V' 6 a -- @ -- -- Note this requires @DataKinds@. Also requires @ViewPatterns@ if 'v' -- is used as a pattern. -- -- === __Examples__ -- -- @ -- >>> let a = [v| 1 2 3 4 5 |] -- >>> :t a -- a :: Num a => V 5 a -- >>> a -- V {toVector = [1,2,3,4,5]} -- >>> let f [v| a b c d e |] = (a,b,c,d,e) -- >>> :t f -- f :: V 5 t -> (t, t, t, t, t) -- >>> f a -- (1,2,3,4,5) -- @ -- -- Variables and infix expressions are also allowed. Negative values can -- be expressed by a leading @-@ with a space before but no space -- after. -- -- @ -- >>> let b x = [v| 1\/x 2 \/ x (succ x)**2 x-2 x - 3 -x |] -- >>> b Debug.SimpleReflect.a -- V {toVector = [1 \/ a,2 \/ a,succ a**2,a - 2,a - 3,negate a]} -- @ v :: QuasiQuoter v = QuasiQuoter { quoteExp = parseV , quotePat = patternV , quoteType = error "v can't be used as type" , quoteDec = error "v can't be used as dec" } parseV :: String -> Q Exp parseV s = case parseLine s of Right as -> let e = pure $ ListE as n = pure . LitT $ NumTyLit (toInteger $ length as) in [| (V.V :: Vector.Vector a -> V.V $n a) (Vector.fromList $e) |] Left err -> fail $ "v: " ++ err ------------------------------------------------------------------------ -- Stencils ------------------------------------------------------------------------ parseStencilLine :: String -> Either String [Maybe Exp] parseStencilLine s = case List.sortBy (compare `on` (length . snd)) rs of (xs,"") : _ -> Right xs (_ , x) : _ -> Left $ "parse error on input " ++ head (words x) _ -> Left "no parse" where rs = readP_to_S (many $ mExp <* skipSpaces) s mExp = fmap Just noAppExpression <|> skip skip = do Lex.Ident "_" <- Lex.lex pure Nothing -- | List of expressions forming a stencil. To be either turned into -- either a real list or an unfolded stencil. parseStencil :: String -> Q Exp parseStencil str = case mapM (mapM parseStencilLine) (map lines ps) of Left err -> fail err Right [] -> [| mkStencil [] |] Right [[as]] -> uncurry mkStencilE $ parse1D as Right [ass] -> uncurry mkStencilE $ parse2D ass Right asss -> uncurry mkStencilE $ parse3D asss where ps = paragraphs str mkStencilE :: ShapeLift f => Layout f -> [Maybe Exp] -> Q Exp mkStencilE l as = do when (F.any even l) $ reportWarning "stencil has an even size in some dimension, the centre element may be incorrect" let ixes = map (^-^ fmap (`div` 2) l) (toListOf shapeIndexes l) -- indexes zipped with expressions, discarding 'Nothing's xs = mapMaybe (sequenceOf _2) (zip ixes as) mkStencilTHBy pure xs -- | QuasiQuoter for producing a static stencil definition. This is a -- versatile parser for 1D, 2D and 3D stencils. The parsing is similar -- to 'dense' but 'stencil' also supports @_@, which means ignore this -- element. Also, stencils should have an odd length in all dimensions -- so there is always a center element (which is used as 'zero'). -- -- === __Examples__ -- -- - 1D stencils are of the form -- -- @ -- ['stencil'| 5 -3 1 -3 5 |] :: 'Num' a => 'Stencil' 'V1' a -- @ -- -- - 2D stencils are of the form -- -- @ -- myStencil2 :: 'Num' a => 'Stencil' 'V2' a -- myStencil2 = ['stencil'| -- 0 1 0 -- 1 0 1 -- 0 1 0 -- |] -- @ -- -- - 3D stencils have gaps between planes. -- -- @ -- myStencil3 :: 'Fractional' a => 'Stencil' 'V3' a -- myStencil3 :: ['stencil'| -- 1\/20 3\/10 1\/20 -- 3\/10 1 3\/10 -- 1\/20 3\/10 1\/20 -- -- 3\/10 1 3\/10 -- 1 _ 1 -- 3\/10 1 3\/10 -- -- 1\/20 3\/10 1\/20 -- 3\/10 1 3\/10 -- 1\/20 3\/10 1\/20 -- |] -- @ -- -- Variables can also be used -- -- @ -- myStencil2' :: a -> a -> a -> 'Stencil' 'V2' a -- myStencil2' a b c = ['stencil'| -- c b c -- b a b -- c b c -- |] -- @ -- -- stencil :: QuasiQuoter stencil = QuasiQuoter { quoteExp = parseStencil , quotePat = error "stencil can't be used in pattern" , quoteType = error "stencil can't be used in type" , quoteDec = error "stencil can't be used in dec" } -- | Construct a 'Stencil' by unrolling the list at compile time. For -- example -- -- @ -- 'ifoldr' f b $('mkStencilTH' [('V1' (-1), 5), ('V1' 0, 3), ('V1' 1, 5)]) -- @ -- -- will be get turned into -- -- @ -- f ('V1' (-1)) 5 (f ('V1' 0) 3 (f ('V1' 1) 5 b)) -- @ -- -- at compile time. Since there are no loops and all target indexes -- are known at compile time, this can lead to more optimisations and -- faster execution times. This can lead to around a 2x speed up -- compared to folding over unboxed vectors. -- -- @ -- myStencil = $('mkStencilTH' (as :: [(f 'Int', a)])) :: 'Stencil' f a -- @ mkStencilTH :: (ShapeLift f, Lift a) => [(f Int, a)] -> Q Exp mkStencilTH = mkStencilTHBy lift -- | 'mkStencilTH' with a custom 'lift' function for @a@. mkStencilTHBy :: ShapeLift f => (a -> Q Exp) -> [(f Int, a)] -> Q Exp mkStencilTHBy aLift as = do -- See Note [mkName-capturing] f <- newName "mkStencilTHBy_f" b <- newName "mkStencilTHBy_b" let appF (i,a) e = do iE <- liftShape' i aE <- aLift a pure $ AppE (AppE (AppE (VarE f) iE) aE) e e <- foldrM appF (VarE b) as pure $ AppE (ConE 'Stencil) (LamE [VarP f,VarP b] e) {- ~~~~ Note [mkName-capturing] Since 'newName' will capture any other names below it with the same name. So if we simply used @newName "b"@, [stencil| a b c |] where a=1; b=2; c=3 would convert @b@ to @b_a5y0@ (or w/e the top level b is) and fail. To prevent this I've used a name that's unlikely conflict. Another solution would be to use lookupValueName on all variables. But this would either require traversing over all 'Name's in every 'Exp' (shown below) or parse in the Q monad. -- | Lookup and replace all names made with 'mkName' using -- 'lookupValueName'; failing if not in scope. replaceMkName :: Exp -> Q Exp replaceMkName = template f where f (Name (OccName s) NameS) = lookupValueName s >>= \case Just nm -> pure nm -- Sometimes a variable may not be in scope yet because it's -- generated in a TH splice that hasn't been run yet. Nothing -> fail $ "Not in scope: ‘" ++ s ++ "’" f nm = pure nm -} ------------------------------------------------------------------------ -- Parsing expressions ------------------------------------------------------------------------ parseLine :: String -> Either String [Exp] parseLine s = case List.sortBy (compare `on` (length . snd)) rs of (xs,"") : _ -> Right xs (_ , x) : _ -> Left $ "parse error on input " ++ head (words x) _ -> Left "no parse" where rs = readP_to_S (many noAppExpression <* skipSpaces) s -- | Fail the parser if the next non-space is a @-@ directly followed by -- a non-space. closeNegateFail :: ReadP () closeNegateFail = do s <- look case s of ' ' : s' -> case dropWhile isSpace s' of '-' : c : _ -> if isSpace c then pure () else pfail _ -> pure () _ -> pure () -- | If there is a space before but not after a @-@, it is treated as a -- separate expression. -- -- @ -- "1 2 -3 4" -> [1, 2, -3, 4] -- "1 2 - 3 4" -> [1, -1, 4] -- "1 2-3 4" -> [1, -1, 4] -- "11 -3/2 -3/2 4" -> [1, -1, 4] -- "1 -3/2 4" -> [1.0,-1.5,4.0] -- @ noAppExpression :: ReadP Exp noAppExpression = do aE <- anExpr True option aE $ do closeNegateFail i <- infixExp bE <- noAppExpression pure $ UInfixE aE i bE -- | Parse an express without any top level application. Infix functions -- are still permitted. -- -- This is only a small subset of the full haskell syntax. The -- following syntax is supported: -- -- - Variables/constructors: @a@, @'Just'@ etc. -- - Numbers: @3@, @-6@, @7.8@, @1e-6@, @0x583fa@ -- - Parenthesis/tuples: @()@ @(f a)@, @(a,b)@ -- - Lists -- - Strings -- - Function application -- - Infix operators: symbols (@+@, @/@ etc.) and blackticked (like @`mod`@) -- -- More advanced haskell syntax are not yet supported: -- -- - let bindings -- - lambdas -- - partial infix application (+) (1+) (+2) -- - type signatures -- - comments -- -- This could be replaced by haskell-src-meta but since I want a -- custom parser for 'noAppExpression' it doesn't seem worth the extra -- dependencies. expression :: ReadP Exp expression = do f <- anExpr True args <- many (anExpr False) let aE = F.foldl AppE f args option aE $ do -- if the next lex isn't a symbol, we move on to the next statement i <- infixExp bE <- expression pure $ UInfixE aE i bE -- | Parse an infix expression. Either a symbol or a name wrapped in @`@. infixExp :: ReadP Exp infixExp = do a <- Lex.lex case a of Lex.Symbol s -> pure $ symbol s Lex.Punc "`" -> do Lex.Ident x <- Lex.lex Lex.Punc "`" <- Lex.lex ident x _ -> pfail -- Lexing -------------------------------------------------------------- -- | Parse a single expression. anExpr :: Bool -- ^ Allow a leading @-@ to mean 'negate' -> ReadP Exp anExpr new = do a <- Lex.lex case a of Lex.Char c -> pure $ LitE (CharL c) Lex.String s -> pure $ LitE (StringL s) Lex.Punc s -> punc s Lex.Ident s -> ident s Lex.Symbol s -> if new then prefix s else pfail Lex.Number n -> pure $ LitE (number n) Lex.EOF -> pfail -- | Convert a name to an expression. ident :: String -> ReadP Exp ident "_" = pfail ident s@(x:_) | isUpper x = pure $ ConE (mkName s) ident s = pure $ VarE (mkName s) -- | Convert a symbol to an expression. symbol :: String -> Exp symbol s@(':':_) = ConE (mkName s) symbol s = VarE (mkName s) -- | Parse from some punctuation. punc :: String -> ReadP Exp punc = \case -- parenthesis / tuples "(" -> do as <- expression `sepBy` comma Lex.Punc ")" <- Lex.lex pure $ tupe as -- lists "[" -> do as <- expression `sepBy` comma Lex.Punc "]" <- Lex.lex pure $ ListE as _ -> pfail prefix :: String -> ReadP Exp prefix "-" = do e <- anExpr False pure $ AppE (VarE 'negate) e prefix _ = pfail comma :: ReadP () comma = do Lex.Punc "," <- Lex.lex pure () -- | Turn a 'Number' into a literal 'Integer' if possible, otherwise -- make a literal `Rational`. number :: Lex.Number -> Lit number n = maybe (RationalL $ Lex.numberToRational n) IntegerL (Lex.numberToInteger n) ------------------------------------------------------------------------ -- Parsing patterns ------------------------------------------------------------------------ patternV :: String -> Q Pat patternV s = do case parsePattern s of Left err -> fail err Right pats -> do fE <- vTuple (length pats) pure $ ViewP fE (TupP pats) parsePattern :: String -> Either String [Pat] parsePattern s = case List.sortBy (compare `on` (length . snd)) rs of (xs,"") : _ -> Right xs (_ , x) : _ -> Left $ "parse error on input " ++ head (words x) _ -> Left "no parse" where rs = readP_to_S (many pattern <* skipSpaces) s pattern :: ReadP Pat pattern = do a <- Lex.lex case a of Lex.Char c -> pure $ LitP (CharL c) Lex.String s -> pure $ LitP (StringL s) Lex.Punc s -> puncP s Lex.Ident n -> pure $ identP n Lex.Symbol s -> prefixP s Lex.Number n -> pure $ LitP (number n) Lex.EOF -> pfail -- | Convert a name to an expression. identP :: String -> Pat identP "_" = WildP identP s@(x:_) | isUpper x = ConP (mkName s) [] identP s = VarP (mkName s) -- | Parse from some punctuation. puncP :: String -> ReadP Pat puncP = \case "~" -> TildeP <$> pattern "(" -> do as <- pattern `sepBy` comma Lex.Punc ")" <- Lex.lex pure $ TupP as "[" -> do as <- pattern `sepBy` comma Lex.Punc "]" <- Lex.lex pure $ ListP as _ -> pfail prefixP :: String -> ReadP Pat prefixP "!" = do c:_ <- look when (isSpace c) pfail BangP <$> pattern prefixP "~" = TildeP <$> pattern prefixP _ = pfail -- | Create an expression for converting a (V n a) to an n-tuple. vTuple :: Int -> Q Exp vTuple n | n > 62 = error "max supported length is 62 for v pattern" | otherwise = do vN <- newName "v" let idx i = AppE (AppE (VarE 'Vector.unsafeIndex) (VarE vN)) (intE i) let xs = tupe $ map idx [0..n-1] a <- newName "a" let tup = iterate (\x -> AppT x (VarT a)) (TupleT n) !! n typ = ForallT [PlainTV a] [] (AppT (AppT ArrowT (AppT (AppT (ConT ''V.V) (intT n)) (VarT a))) tup) [| (\(V.V $(pure $ VarP vN)) -> $(pure xs)) :: $(pure typ) |] where intE = LitE . IntegerL . toInteger intT = LitT . NumTyLit . toInteger -- Parsing specific dimensions ----------------------------------------- -- | Parse a 1D list. If the system is not valid, return a string -- with error message. parse1D :: [a] -> (V1 Int, [a]) parse1D as = (V1 x, as) where x = length as -- | Parse a 2D list of lists. If the system is not valid, returns an -- error parse2D :: [[a]] -> (V2 Int, [a]) parse2D as | Just e <- badX = error ("parse2D: " ++ errMsg e) | otherwise = (V2 x y, F.concat $ List.transpose as) where x = head xs y = length as xs = map length as badX = ifind (const (/= x)) xs errMsg (i,j) = "row " ++ show i ++ " has " ++ show j ++ " columns but the first" ++ " row has " ++ show x ++ " columns" -- | Parse a 3D list of list of lists. If the system is not valid, -- return a string with error message. -- -- The element are reordered in the appropriate way for the array: -- -- @ -- >>> parse3D [["abc","def","ghi"],["jkl","mno","pqr"],["stu","vwx","yz!"]] -- ((V3 3 3 3), "ajsdmvgpybktenwhqzclufoxir!") -- @ -- parse3D :: [[[a]]] -> (V3 Int, [a]) parse3D as | nullOf (each.each.each) as = (zero, []) | Just e <- badX = error $ errorCol e | Just e <- badY = error $ errorRow e | otherwise = (V3 x y z, as') where z = length as y = length (head as) x = length (head (head as)) -- reorder and concatenate so it's the correct order for the array as' = F.concatMap F.concat (List.transpose $ map List.transpose $ List.transpose as) -- check for inconsistencies badY = ifind (const (/= y)) (map length as) badX = ifindOf' (traversed <.> traversed <. to length) (const (/= x)) as -- error messages for inconsistent rows/columns errorCol ((k,j),i) = "plane " ++ show k ++ ", row " ++ show j ++ " has " ++ show i ++ " columns" ++ ", but the first row has " ++ show x ++ " columns" errorRow (k,j) = "plane " ++ show k ++ " has " ++ show j ++ " rows but the first" ++ " plane has " ++ show x ++ " rows" -- | Version of ifindOf which is consistent with ifind (in that it also returns the index). ifindOf' :: IndexedGetting i (Endo (Maybe (i, a))) s a -> (i -> a -> Bool) -> s -> Maybe (i, a) ifindOf' l p = ifoldrOf l (\i a y -> if p i a then Just (i, a) else y) Nothing {-# INLINE ifindOf' #-} -- Shape lift class ---------------------------------------------------- -- | Class of shapes that can be 'lift'ed. -- -- This is to prevent orphans for the 'Lift' class. class Shape f => ShapeLift f where -- | 'lift' for 'Shape's. liftShape :: Lift a => f a -> Q Exp -- | Polymorphic 'lift' for a 'Shape's. liftShape' :: Lift a => f a -> Q Exp instance ShapeLift V1 where liftShape (V1 x) = [| V1 x |] liftShape' (V1 x) = [| v1 x |] instance ShapeLift V2 where liftShape (V2 x y) = [| V2 x y |] liftShape' (V2 x y) = [| v2 x y |] instance ShapeLift V3 where liftShape (V3 x y z) = [| V3 x y z |] liftShape' (V3 x y z) = [| v3 x y z |] instance ShapeLift V4 where liftShape (V4 x y z w) = [| V4 x y z w |] liftShape' (V4 x y z w) = [| v4 x y z w |] v1 :: (R1 f, Shape f, Num a) => a -> f a v1 x = set _x x one {-# INLINE [0] v1 #-} v2 :: (R2 f, Shape f, Num a) => a -> a -> f a v2 x y = set _xy (V2 x y) one {-# INLINE [0] v2 #-} v3 :: (R3 f, Shape f, Num a) => a -> a -> a -> f a v3 x y z = set _xyz (V3 x y z) one {-# INLINE [0] v3 #-} v4 :: (R4 f, Shape f, Num a) => a -> a -> a -> a -> f a v4 x y z w = set _xyzw (V4 x y z w) one {-# INLINE [0] v4 #-} one :: (Shape f, Num a) => f a one = 1 <$ (zero :: Additive f => f Int) -- are these nessesary? {-# RULES "v1/V1" v1 = V1; "v1/V2" forall a. v1 a = V2 a 1; "v1/V3" forall a. v1 a = V3 a 1 1; "v2/V2" v2 = V2; "v2/V3" forall a b. v2 a b = V3 a b 1; "v3/V3" v3 = V3; "v4/V4" v4 = V4 #-}
cchalmers/dense
src/Data/Dense/TH.hs
bsd-3-clause
21,747
11
23
5,797
5,015
2,677
2,338
340
8
import Data.List (unfoldr, reverse) import Data.Char (chr, ord) decToBin :: Int -> String decToBin x = reverse $ unfoldr helper x where helper 0 = Nothing helper x = Just (chr ((ord '0') + (x `mod` 2)), x `div` 2) palindromic xs = xs == reverse xs main = print $ sum $ [ x | x <- [1 .. 999999], palindromic (show x), palindromic (decToBin x) ]
foreverbell/project-euler-solutions
src/36.hs
bsd-3-clause
355
0
13
79
182
97
85
8
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Main (main) where import Client.Connection import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar, MVar) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TChan (newTChan, readTChan) import Control.Concurrent.STM.TVar (newTVar, readTVar, writeTVar) import Control.Monad (when, forever) import Data.Binary import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 (putStrLn, getLine, pack, dropWhile, words, getLine) import qualified Data.ByteString.Lazy as L (toStrict, fromStrict, null, hGetContents) import Data.CertificateStore import Data.Char (isSpace) import qualified Data.Map as Map (empty) import Data.Maybe (fromMaybe, fromJust, isNothing) import Data.Monoid ((<>)) import Network.Simple.TCP.TLS import Network.TLS import Network.TLS.Extra (fileReadPrivateKey, fileReadCertificate) import System.Certificate.X509.Unix import System.Console.Haskeline (runInputT, getPassword, defaultSettings) import System.Environment (getArgs) import System.IO (hSetBuffering, BufferMode(..), IOMode(..), stdout, withFile) import Tools import Types import System.Exit (exitFailure) {- | hpt main function. Start the client and the server parts of hpt. -} main :: IO () main = getArgs >>= go where -- long options go ("--version":_) = putStrLn version go ("--help":_) = putStrLn usage go ("--start":hostname:_) = hpt hostname -- short options go ("-v":_) = go ["--version"] go ("-h":_) = go ["--help"] go ("-s":hostname:_) = go ["--start", hostname] go _ = putStrLn ("Wrong argument.\n" ++ usage) -- | Start client and server parts hpt :: String -> IO () hpt hostname = withSocketsDo $ do -- Construct credential information putStr "Loading certificate..." certificate <- fileReadCertificate "/home/nschoe/.hpt-dispatcher/cacert.pem" success "success\n" -- Get certificate store putStr "Getting client's system certificate store..." cStore <- getSystemCertificateStore success "success\n" -- TEMPORARY -- Create artificial certificate store to recognize dispatcher's certificate let certificateStore = makeCertificateStore [certificate] -- Create client SSL settings putStr "Creating client SSL settings..." let clientSettings = makeClientSettings [] (Just hostname) (certificateStore <> cStore) success "success.\n" -- Create internal state putStr "Initializing internal state..." conversations <- atomically $ newTVar (Map.empty) contactList <- atomically $ newTVar [] chanCommands <- atomically $ newTChan currentChat <- atomically $ newTVar Nothing contactListDb <- atomically $ newTVar "" let state = ClientState { csConversations = conversations , csContactList = contactList , csCommands = chanCommands , csCurrentChat = currentChat , csContactListDb = contactListDb } success "success\n" -- Connecting to the dispatcher hSetBuffering stdout NoBuffering -- for the output to appear in the correct order authSuccess <- newEmptyMVar -- create sync mvar : will be put to True when 'connect' successfully authenticated putStr "Connecting to dispatcher..." talkDispatcher_tId <- forkIO $ connect clientSettings hostname port (talkDispatcher state authSuccess) isAuthSuccessful <- takeMVar authSuccess -- When we successfully reached the Dispatcher and logged in, continue when isAuthSuccessful $ loop state -- Exit when auth was not successfull putStrLn "Authentification was not successful" putStrLn "\nClient exiting.\n" where loop state = do -- ask for a command putStr "Input command (try '/help') : " cmd <- (words . dropWhile isSpace) `fmap` getLine -- just remove leading spaces -- parse command case cmd of ("/help":_) -> do putStrLn ("Must display help") ("/list":_) -> do contactList <- atomically $ readTVar (csContactList state) let output1 = "\nContact list (" ++ show (length contactList) ++ " contacts) : [unread messages]\n" let output2 = output1 ++ (replicate (length output1 - 2) '=') ++ "\n" let list = map ((++ " [not implemented]") . contactUserName) contactList let output = output2 ++ (unlines list) putStrLn output loop state ("/start":who:_) -> do putStrLn ("Must start conversation with " ++ who) loop state ("/stop":"all":_) -> do putStrLn ("Must stop all conversations") loop state ("/stop":who:_) -> do putStrLn ("Must stop conversation with " ++ who) loop state ("/ping":who:_) -> do putStrLn ("Must ping " ++ who) loop state ("/add":who:_) -> do contactList <- atomically $ readTVar (csContactList state) let mContact = contactLookup who contactList if (isNothing mContact) then do -- create "empty" contact to be filled by the next Alive request let newContact = Contact { contactUserName = who , contactStatus = NotAvailable , contactIpAddr = "" } atomically $ writeTVar (csContactList state) (newContact : contactList) -- save contact list to file _ <- forkIO $ saveContactList state (newContact : contactList) putStrLn (who ++ " was added to contact list.") else putStrLn (who ++ " is already is your contact list !") loop state ("/del":who:_) -> do contactList <- atomically $ readTVar (csContactList state) let mContact = contactLookup who contactList if (isNothing mContact) then putStrLn (who ++ " is not in your contact list !") else do let newContactList = filter ((/= who) . contactUserName) contactList atomically $ writeTVar (csContactList state) newContactList _ <- forkIO $ saveContactList state newContactList putStrLn (who ++ " has been removed from your contact list !") loop state ("/switchto":who:_) -> do putStrLn ("Must switch active conversation to : " ++ who) loop state ("/quit":_) -> do putStrLn ("Must quit") loop state (('/':cmd'):_) -> do putStrLn ("Unknow command : \"/" ++ cmd' ++ "\"") loop state _ -> do putStrLn ("Must write message (check active conversation first) : " ++ unwords cmd) loop state talkDispatcher :: ClientState -> MVar Bool -> (Context, SockAddr) -> IO () talkDispatcher state authSuccess (context, servaddr) = do success "success\n\n" -- Sending Born request putStr "Please identify.\nUsername : " username <- getLine password <- (B8.pack . fromMaybe "") `fmap` runInputT defaultSettings (getPassword Nothing "Password : ") -- Parse contact list putStr "Reading contact list..." db <- getContactListDb username contactListDb <- case db of Left err -> do failed ("failed\n" ++ err ++ "\n") exitFailure Right file -> return file success "success\n" -- Creating contact list from file putStr "Building contact list..." raw <- withFile contactListDb ReadMode $ \h -> do !contents <- L.hGetContents h return contents let list = case L.null raw of True -> [] False -> decode raw :: ContactList -- Modifying state to take contact list into account atomically $ do writeTVar (csContactList state) list writeTVar (csContactListDb state) contactListDb success "success\n" putStrLn "\nIdentifying to dispatcher..." send context (L.toStrict $ encode (Born username password)) -- Parsing dispatcher's answer mbs <- recv context case mbs of Nothing -> failed "Lost contact with server.\n" Just bs -> do let answer = decode (L.fromStrict bs) :: DispatcherAnswer case answer of -- Auth was okay BornOK str -> -- Print success message do success "Identification successful.\n" when (not $ isNothing str) (putStrLn ("Dispatcher notice : " ++ fromJust str)) success "You are now connected !\n" -- Put sync variable to True so that 'main' can start listening on user's input putMVar authSuccess True -- fork thread to keep alive putStr "Starting keep-alive routine..." keepAlive_tId <- forkIO $ do threadDelay ((10^6) :: Int) forever $ do keepAlive context state threadDelay ((9 * 10^6) :: Int) success "success\n" -- loop to handle client's input (e.g. log out requests) loop state context -- Auth failed BornKO str -> do failed "Identification failed " when (not $ isNothing str) (putStrLn (": " ++ fromJust str)) putMVar authSuccess False -- put sync to False so the 'main' knows not to listen to user's input _ -> error "Error : disptacher returned wrong type of answer\n" where loop state context = do -- parse commands to send to the dispatcher command <- atomically $ readTChan (csCommands state) case command of ChangeStatus newStatus -> do putStrLn ("TODO : send dispatcher : " ++ show command) loop state context AddContact username -> do putStrLn ("TODO : send dispatcher : " ++ show command) loop state context Quit -> do putStrLn ("TODO : send dispatcher : " ++ show command) loop state context _ -> do failed ("Error : unknown command received : " ++ show command ++ "\n") loop state context
nschoe/hpt
src/Main.hs
bsd-3-clause
12,318
32
28
5,002
2,264
1,183
1,081
201
14
module Ghazan.Speed ( ) where
Cortlandd/ConversionFormulas
src/Ghazan/Speed.hs
bsd-3-clause
35
0
3
10
9
6
3
1
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} -- | Symbolic evaluation for the 'Numerical' subset of expressions of the -- 'Core' language shared by all three languages: 'Term', 'Prop', and -- 'Invariant'. module Pact.Analyze.Eval.Numerical where import Data.Coerce (Coercible) import Data.SBV (EqSymbolic ((.==)), complement, sDiv, sMod, shift, unliteral, xor, (.&.), (.<), (.|.)) import Pact.Analyze.Errors import Pact.Analyze.Types import Pact.Analyze.Types.Eval -- When doing binary arithmetic involving: -- * decimal x decimal -- * integer x decimal -- * decimal x integer -- -- We widen / downcast the integer to be a decimal. This just requires shifting -- the number left 255 decimal digits in the case of an integer. class DecimalRepresentable a where widenToDecimal :: S a -> S Decimal instance DecimalRepresentable Integer where widenToDecimal = lShift255D . coerceS instance DecimalRepresentable Decimal where widenToDecimal = id -- This module handles evaluation of unary and binary integers and decimals. -- Two tricky details to watch out for: -- -- 1. See Note [Rounding] -- -- 2. Errors. Division can fail if the denominator is 0. Rounding can fail if -- the precision is negative. In either case we mark failure via -- @markFailure@. Thus our codomain is extended with failure. -- -- Note [Rounding] -- -- The key is this quote from "Data.Decimal": -- -- "Decimal numbers are represented as m*10^(-e) where m and e are integers. The -- exponent e is an unsigned Word8. Hence the smallest value that can be -- represented is 10^-255." evalNumerical :: Analyzer m => Numerical (TermOf m) a -> m (S (Concrete a)) evalNumerical (IntArithOp op x y) = evalIntArithOp op x y evalNumerical (DecArithOp op x y) = evalDecArithOp op x y evalNumerical (IntDecArithOp op x y) = evalDecArithOp op x y evalNumerical (DecIntArithOp op x y) = evalDecArithOp op x y evalNumerical (IntUnaryArithOp op x) = evalUnaryArithOp op x evalNumerical (DecUnaryArithOp op x) = evalUnaryArithOp op x evalNumerical (ModOp x y) = evalModOp x y evalNumerical (RoundingLikeOp1 op x) = evalRoundingLikeOp1 op x evalNumerical (RoundingLikeOp2 op x p) = evalRoundingLikeOp2 op x p evalNumerical (BitwiseOp op args) = evalBitwiseOp op args -- In principle this could share an implementation with evalDecArithOp. In -- practice, evaluation can be slower because you're multiplying both inputs by -- (10 ^ 255), so we stick to this more efficient implementation. evalIntArithOp :: Analyzer m => ArithOp -> TermOf m 'TyInteger -> TermOf m 'TyInteger -> m (S Integer) evalIntArithOp op xT yT = do x <- eval xT y <- eval yT case op of Add -> pure $ x + y Sub -> pure $ x - y Mul -> pure $ x * y Div -> do markFailure $ y .== 0 pure $ x `sDiv` y Pow -> throwErrorNoLoc $ UnsupportedDecArithOp op Log -> throwErrorNoLoc $ UnsupportedDecArithOp op evalDecArithOp :: ( Analyzer m , SingI a , SingI b , DecimalRepresentable (Concrete a) , DecimalRepresentable (Concrete b) ) => ArithOp -> TermOf m a -> TermOf m b -> m (S Decimal) evalDecArithOp op xT yT = do x <- widenToDecimal <$> eval xT y <- widenToDecimal <$> eval yT coerceS <$> case op of Add -> pure $ x + y Sub -> pure $ x - y Mul -> pure $ x * y Div -> do markFailure $ y .== 0 pure $ x / y Pow -> throwErrorNoLoc $ UnsupportedDecArithOp op Log -> throwErrorNoLoc $ UnsupportedDecArithOp op -- In practice (a ~ Decimal) or (a ~ Integer). evalUnaryArithOp :: forall m a a' . ( Analyzer m , a' ~ Concrete a , Coercible a' Integer , SingI a ) => UnaryArithOp -> TermOf m a -> m (S a') evalUnaryArithOp op term = do x <- coerceS @a' @Integer <$> eval term coerceS @Integer @a' <$> case op of Negate -> pure $ negate x Sqrt -> throwErrorNoLoc $ UnsupportedUnaryOp op Ln -> throwErrorNoLoc $ UnsupportedUnaryOp op Exp -> throwErrorNoLoc $ UnsupportedUnaryOp op -- TODO: use svExp Abs -> pure $ abs x Signum -> pure $ signum x evalModOp :: Analyzer m => TermOf m 'TyInteger -> TermOf m 'TyInteger -> m (S Integer) evalModOp xT yT = do x <- eval xT y <- eval yT markFailure $ y .== 0 pure $ sMod x y evalRoundingLikeOp1 :: Analyzer m => RoundingLikeOp -> TermOf m 'TyDecimal -> m (S Integer) evalRoundingLikeOp1 op xT = do x <- eval xT pure $ case op of Floor -> floorD x -- For ceiling we use the identity: -- ceil(x) = -floor(-x) Ceiling -> negate (floorD (negate x)) -- Round is much more complicated because pact uses the banker's method, -- where a real exactly between two integers (_.5) is rounded to the -- nearest even. Round -> banker'sMethodS x -- In the decimal rounding operations we shift the number left by `precision` -- digits, round using the integer method, and shift back right. -- -- x: SReal := -100.15234 -- precision: SInteger := 2 -- return: SReal := -100.15 evalRoundingLikeOp2 :: forall m . Analyzer m => RoundingLikeOp -> TermOf m 'TyDecimal -> TermOf m 'TyInteger -> m (S Decimal) evalRoundingLikeOp2 op xT precisionT = do x <- eval @_ @'TyDecimal xT precision <- eval precisionT -- Precision must be >= 0 markFailure (precision .< 0) rShiftD' precision . fromInteger' <$> evalRoundingLikeOp1 op (inject' (lShiftD' precision x)) -- Round a real exactly between two integers (_.5) to the nearest even banker'sMethodS :: S Decimal -> S Integer banker'sMethodS (S prov x) = S prov $ banker'sMethod x evalBitwiseOp :: Analyzer m => BitwiseOp -> [TermOf m 'TyInteger] -> m (S Integer) evalBitwiseOp BitwiseAnd [xT, yT] = do S _ x <- eval xT S _ y <- eval yT pure $ sansProv $ x .&. y evalBitwiseOp BitwiseOr [xT, yT] = do S _ x <- eval xT S _ y <- eval yT pure $ sansProv $ x .|. y evalBitwiseOp Xor [xT, yT] = do S _ x <- eval xT S _ y <- eval yT pure $ sansProv $ x `xor` y evalBitwiseOp Complement [xT] = do S _ x <- eval xT pure $ sansProv $ complement x evalBitwiseOp Shift [xT, yT] = do S _ x <- eval xT S _ y <- eval yT case unliteral y of Just y' -> pure $ sansProv $ shift x $ fromIntegral y' Nothing -> throwErrorNoLoc $ UnhandledTerm "shift currently requires a statically determined shift size" evalBitwiseOp op terms = throwErrorNoLoc $ MalformedBitwiseOp op $ length terms
kadena-io/pact
src-tool/Pact/Analyze/Eval/Numerical.hs
bsd-3-clause
6,973
0
15
1,769
1,846
916
930
160
6
{-- snippet lend --} lend amount balance = let reserve = 100 newBalance = balance - amount in if balance < reserve then Nothing else Just newBalance {-- /snippet lend --} {-- snippet lend2 --} lend2 amount balance = if amount < reserve * 0.5 then Just newBalance else Nothing where reserve = 100 newBalance = balance - amount {-- /snippet lend2 --} {-- snippet lend3 --} lend3 amount balance | amount <= 0 = Nothing | amount > reserve * 0.5 = Nothing | otherwise = Just newBalance where reserve = 100 newBalance = balance - amount {-- /snippet lend3 --}
binesiyu/ifl
examples/ch03/Lending.hs
mit
776
0
9
324
162
84
78
16
2
{-# OPTIONS_GHC -Wno-missing-import-lists #-} -- | Optional parameters for actions. module Strive.Options ( module Strive.Options.Activities , module Strive.Options.Athletes , module Strive.Options.Authentication , module Strive.Options.Clubs , module Strive.Options.Comments , module Strive.Options.Friends , module Strive.Options.Kudos , module Strive.Options.Segments , module Strive.Options.Streams , module Strive.Options.Uploads ) where import Strive.Options.Activities import Strive.Options.Athletes import Strive.Options.Authentication import Strive.Options.Clubs import Strive.Options.Comments import Strive.Options.Friends import Strive.Options.Kudos import Strive.Options.Segments import Strive.Options.Streams import Strive.Options.Uploads
tfausak/strive
source/library/Strive/Options.hs
mit
776
0
5
88
140
97
43
22
0
{-# LANGUAGE OverloadedStrings #-} module Ketchup.Auth ( basicAuth ) where import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Base64 as B64 import Ketchup.Httpd import Ketchup.Utils -- |Performs HTTP Basic Auth basicAuth :: [(B.ByteString, B.ByteString)] -- ^ List of (Username, Password) -> B.ByteString -- ^ Authentication Realm -> Handler -- ^ Success Handler -> Handler basicAuth couples realm success hnd req = case authHead of Nothing -> send401 Just x -> case authData `elem` couples of False -> send401 True -> success hnd req where authData = parseAuth $ x !! 0 where authHead = lookup "Authorization" $ headers req authField = B.concat ["Basic realm=\"",realm,"\""] send401 = sendReply hnd 401 [("WWW-Authenticate", [authField]) ,("Content-Type", ["text/html"])] "<h1>401 Unauthorized</h1>" parseAuth :: B.ByteString -> (B.ByteString, B.ByteString) parseAuth authStr = breakBS ":" $ B64.decodeLenient authData where authData = snd parts parts = breakBS " " authStr
silverweed/ketchup
Ketchup/Auth.hs
mit
1,333
0
11
471
288
162
126
28
3
module Lamdu.GUI.Expr.InjectEdit ( make, makeNullary ) where import qualified Control.Lens as Lens import GUI.Momentu ((/|/)) import qualified GUI.Momentu as M import qualified GUI.Momentu.EventMap as E import qualified GUI.Momentu.I18N as MomentuTexts import GUI.Momentu.Responsive (Responsive) import qualified GUI.Momentu.Responsive as Responsive import qualified GUI.Momentu.Responsive.Expression as ResponsiveExpr import qualified GUI.Momentu.State as GuiState import qualified GUI.Momentu.Widget as Widget import qualified Lamdu.Config as Config import qualified Lamdu.Config.Theme.TextColors as TextColors import qualified Lamdu.GUI.Expr.EventMap as EventMap import qualified Lamdu.GUI.Expr.RecordEdit as RecordEdit import Lamdu.GUI.Monad (GuiM) import Lamdu.GUI.Styled (text, grammar, withColor) import qualified Lamdu.GUI.TagView as TagView import qualified Lamdu.GUI.Types as ExprGui import qualified Lamdu.GUI.WidgetIds as WidgetIds import qualified Lamdu.GUI.Wrap as Wrap import qualified Lamdu.I18N.Code as Texts import qualified Lamdu.I18N.CodeUI as Texts import qualified Lamdu.I18N.Navigation as Texts import Lamdu.Name (Name) import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude injectTag :: _ => Sugar.TagRef Name i o -> GuiM env i o (M.WithTextPos M.View) injectTag tag = grammar (text ["injectIndicator"] Texts.injectSymbol) /|/ withColor TextColors.caseTagColor (TagView.make (tag ^. Sugar.tagRefTag)) make :: _ => Annotated (ExprGui.Payload i o) # Const (Sugar.TagRef Name i o) -> GuiM env i o (Responsive o) make (Ann (Const pl) (Const tag)) = (Widget.makeFocusableWidget ?? myId <&> (Widget.widget %~)) <*> ( maybe (pure id) (ResponsiveExpr.addParens ??) (ExprGui.mParensId pl) <*> (injectTag tag <&> Lens.mapped %~ Widget.fromView) <&> Responsive.fromWithTextPos ) & Wrap.stdWrap pl where myId = WidgetIds.fromExprPayload pl data NullaryRecord o = HiddenNullaryRecord (E.EventMap (o GuiState.Update)) -- enter it | FocusedNullaryRecord (Responsive o) enterSubexpr :: _ => Widget.Id -> f (E.EventMap (o GuiState.Update)) enterSubexpr myId = Lens.view id <&> \env -> E.keysEventMapMovesCursor (env ^. has . Config.enterSubexpressionKeys) (E.toDoc env [has . MomentuTexts.navigation, has . Texts.enterSubexpression]) (pure myId) leaveSubexpr :: _ => Widget.Id -> f (E.EventMap (o GuiState.Update)) leaveSubexpr myId = Lens.view id <&> \env -> E.keysEventMapMovesCursor (env ^. has . Config.leaveSubexpressionKeys) (E.toDoc env [has . MomentuTexts.navigation, has . Texts.leaveSubexpression]) (pure myId) nullaryRecord :: _ => Annotated (ExprGui.Payload i o) # Const (i (Sugar.TagChoice Name o)) -> GuiM env i o (NullaryRecord o) nullaryRecord x = do isActive <- GuiState.isSubCursor ?? myId if isActive then RecordEdit.makeEmpty x <&> FocusedNullaryRecord else enterSubexpr myId <&> HiddenNullaryRecord where myId = x ^. annotation & WidgetIds.fromExprPayload makeNullary :: _ => Annotated (ExprGui.Payload i o) # Sugar.NullaryInject Name i o -> GuiM env i o (Responsive o) makeNullary (Ann (Const pl) (Sugar.NullaryInject tag r)) = do makeFocusable <- Widget.makeFocusableView nullary <- nullaryRecord r parenEvent <- EventMap.parenKeysEvent rawInjectEdit <- injectTag (tag ^. hVal . Lens._Wrapped) <&> M.tValue %~ makeFocusable myId <&> Responsive.fromWithTextPos <&> case tag ^. annotation . Sugar.plActions . Sugar.mReplaceParent of Nothing -> id Just act -> M.weakerEvents (parenEvent [has . MomentuTexts.edit, has . Texts.injectSection] (act <&> GuiState.updateCursor . WidgetIds.fromEntityId)) widgets <- case nullary of HiddenNullaryRecord enterNullary -> pure [ rawInjectEdit & Widget.widget %~ M.weakerEvents enterNullary ] FocusedNullaryRecord w -> leaveSubexpr myId <&> \leaveEventMap -> [rawInjectEdit, Widget.weakerEvents leaveEventMap w] valEventMap <- case r ^. annotation . Sugar.plActions . Sugar.delete of Sugar.SetToHole a -> Lens.view id <&> \env -> E.keysEventMapMovesCursor (env ^. has . Config.injectValueKeys) (E.toDoc env [has . MomentuTexts.edit, has . Texts.injectValue]) (a <&> WidgetIds.fromEntityId) _ -> error "cannot set injected empty record to hole??" ResponsiveExpr.boxSpacedMDisamb ?? ExprGui.mParensId pl ?? widgets <&> M.weakerEvents valEventMap & Wrap.stdWrap pl where myId = WidgetIds.fromExprPayload pl
lamdu/lamdu
src/Lamdu/GUI/Expr/InjectEdit.hs
gpl-3.0
5,025
0
19
1,270
1,427
769
658
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-| This module defines the type constraint closure operation. -} module Language.K3.TypeSystem.Closure ( calculateClosure ) where import Control.Monad import qualified Data.Map as Map import qualified Data.Set as Set import Language.K3.Utils.Pretty import Language.K3.TypeSystem.Data import Language.K3.TypeSystem.Utils import Language.K3.Utils.Logger $(loggingFunctions) -- * Closure routine -- |Performs transitive constraint closure on a given constraint set. calculateClosure :: ConstraintSet -> ConstraintSet calculateClosure cs = _debugI (boxToString $ ["Closing constraints: "] %$ indent 2 (prettyLines cs)) $ let (cs',cont) = calculateClosureStep cs in if cont then calculateClosure cs' else _debugIPretty "Finished closure: " cs' -- |Performs a single transitive constraint closure step on a given constraint -- set. Returns the resulting constraint set and a flag indicating whether or -- not any changes were made during this step. calculateClosureStep :: ConstraintSet -> (ConstraintSet, Bool) calculateClosureStep cs = let newCs = csUnions $ map applyClosureFunction closureFunctions in (cs `csUnion` newCs, not $ newCs `csSubset` cs) where closureFunctions = [ (closeTransitivity, "Transitivity") , (closeImmediate, "Immediate Type") , (closeLowerBoundingExtendedRecord, "Close Lower Ext. Record") , (closeUpperBoundingExtendedRecord, "Close Upper Ext. Record") , (closeQualifiedTransitivity, "Qual Transitivity") , (closeQualifiedRead, "Qualified Read") , (closeQualifiedWrite, "Qualified Write") , (closeMonomorphicTransitivity, "Monomorphic Transitivity") , (closeMonomorphicBounding, "Monomorphic Bounding") , (opaqueLowerBound, "Opaque Lower Bound") , (opaqueUpperBound, "Opaque Upper Bound") ] applyClosureFunction (fn, name) = let cs' = fn cs in let learned = csFromSet $ csToSet cs' Set.\\ csToSet cs in if csNull learned then cs' else flip _debugI cs' $ boxToString $ ["Constraint closure (" ++ name ++ ") learned: "] %$ indent 2 (prettyLines learned) -- * Closure rules -- Each of these functions generates a constraint set which represents the -- new additions to the constraint set *only*; the result does not necessarily -- include constraints from the original constraint set. -- |Performs closure for transitivity. closeTransitivity :: ConstraintSet -> ConstraintSet closeTransitivity cs = csFromList $ (do (t,sa) <- csQuery cs $ QueryAllTypesLowerBoundingAnyVars () bnd <- csQuery cs $ QueryTypeOrAnyVarByAnyVarLowerBound sa return $ case bnd of CLeft ta -> t <: ta CRight qa -> t <: qa ) ++ (do (sa,t) <- csQuery cs $ QueryAllTypesUpperBoundingAnyVars () bnd <- csQuery cs $ QueryTypeOrAnyVarByAnyVarUpperBound sa return $ case bnd of CLeft ta -> ta <: t CRight qa -> qa <: t ) -- |Performs immediate type closure. This routine calculates the closure for -- all immediate type-to-type constraints. closeImmediate :: ConstraintSet -> ConstraintSet closeImmediate cs = csUnions $ do (t1,t2) <- csQuery cs $ QueryAllTypesLowerBoundingTypes () case (t1,t2) of (SFunction a1 a2, SFunction a3 a4) -> give [a2 <: a4, a3 <: a1] (STrigger a1, STrigger a2) -> give [a2 <: a1] (SOption qa1, SOption qa2) -> give [qa1 <: qa2] (SIndirection qa1, SIndirection qa2) -> give [qa1 <: qa2] (STuple qas1, STuple qas2) | length qas1 == length qas2 -> give $ zipWith (<:) qas1 qas2 (SRecord m1 oas1 _, SRecord m2 oas2 _) | Set.null oas1 && Set.null oas2 && Map.keysSet m2 `Set.isSubsetOf` Map.keysSet m1 -> give $ Map.elems $ Map.intersectionWith (<:) m1 m2 _ -> mzero where give = return . csFromList -- |Performs closure for opaque-extended records in a lower-bounding position. closeLowerBoundingExtendedRecord :: ConstraintSet -> ConstraintSet closeLowerBoundingExtendedRecord cs = csUnions $ do (SRecord m oas ctOpt, t) <- csQuery cs $ QueryAllTypesLowerBoundingTypes () case t of SOpaque oa -> guard $ not $ oa `Set.member` oas _ -> return () oa' <- Set.toList oas (_, ta_U) <- csQuery cs $ QueryOpaqueBounds oa' t_U <- getUpperBoundsOf cs ta_U case recordConcat [t_U, SRecord m (Set.delete oa' oas) ctOpt] of Left _ -> -- In this situation, there is an inherent conflict in the record type. -- We'll detect this in inconsistency (to keep the closure function -- simple); for now, just bail on the rule. mzero Right t' -> return $ csSing $ t' <: t -- |Performs closure for opaque-extended records in an upper-bounding position. closeUpperBoundingExtendedRecord :: ConstraintSet -> ConstraintSet closeUpperBoundingExtendedRecord cs = csUnions $ do (t,SRecord m oas ctOpt) <- csQuery cs $ QueryAllTypesLowerBoundingTypes () moa <- Nothing : map Just (Set.toList oas) {- Nothing adds base record -} case moa of Nothing -> {-Default case-} return $ csSing $ t <: SRecord m Set.empty ctOpt Just oa -> {-Opaque case -} return $ csSing $ t <: SOpaque oa closeQualifiedTransitivity :: ConstraintSet -> ConstraintSet closeQualifiedTransitivity cs = csFromList $ do (qv1,qa2) <- csQuery cs $ QueryAllQualOrVarLowerBoundingQVar () qv3 <- csQuery cs $ QueryQualOrVarByQVarLowerBound qa2 return $ qv1 <: qv3 closeQualifiedRead :: ConstraintSet -> ConstraintSet closeQualifiedRead cs = csFromList $ do (ta,qa) <- csQuery cs $ QueryAllTypeOrVarLowerBoundingQVar () ta' <- csQuery cs $ QueryTypeOrVarByQVarLowerBound qa return $ ta <: ta' closeQualifiedWrite :: ConstraintSet -> ConstraintSet closeQualifiedWrite cs = csFromList $ do (qa1,qa2) <- csQuery cs $ QueryAllQVarLowerBoundingQVar () ta <- csQuery cs $ QueryTypeOrVarByQVarUpperBound qa2 return $ ta <: qa1 closeMonomorphicTransitivity :: ConstraintSet -> ConstraintSet closeMonomorphicTransitivity cs = csFromList $ do (qa2,qs) <- csQuery cs $ QueryAllMonomorphicQualifiedUpperConstraint () qa1 <- csQuery cs $ QueryPolyLineageByOrigin qa2 return $ MonomorphicQualifiedUpperConstraint qa1 qs closeMonomorphicBounding :: ConstraintSet -> ConstraintSet closeMonomorphicBounding cs = csFromList $ do (qa2,qs) <- csQuery cs $ QueryAllMonomorphicQualifiedUpperConstraint () return $ qa2 <: qs opaqueLowerBound :: ConstraintSet -> ConstraintSet opaqueLowerBound cs = csFromList $ do (oa,t) <- csQuery cs $ QueryAllOpaqueLowerBoundedConstraints () guard $ SOpaque oa /= t guard $ SRecord Map.empty (Set.singleton oa) Nothing /= t (_,ub) <- csQuery cs $ QueryOpaqueBounds oa t_U <- getUpperBoundsOf cs ub return $ t_U <: t opaqueUpperBound :: ConstraintSet -> ConstraintSet opaqueUpperBound cs = csFromList $ do (t,oa) <- csQuery cs $ QueryAllOpaqueUpperBoundedConstraints () guard $ SOpaque oa /= t case t of SRecord _ oas _ -> guard $ not $ Set.member oa oas _ -> return () (lb,_) <- csQuery cs $ QueryOpaqueBounds oa t_L <- getLowerBoundsOf cs lb return $ t <: t_L
DaMSL/K3
src/Language/K3/TypeSystem/Closure.hs
apache-2.0
7,097
0
18
1,399
1,958
988
970
137
7
{- Copyright 2013 Google Inc. All Rights Reserved. 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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# Language RecordWildCards #-} module Plush.Job.StdIO ( RunningIO(..), StdIOParts, makeStdIOParts, stdIOChildPrep, stdIOMasterPrep, stdIOLocalPrep, stdIOCloseMasters, ) where import Control.Applicative ((<$>), (<*>)) import Data.Aeson (Value) import System.Posix import qualified System.Posix.Missing as PM import Plush.Job.Output import Plush.Run.Posix (stdJsonOutput) -- | These are the parent side of the pipes and terminals to a running job. -- Note that the sense is inverted for the parent. That is: The parent writes -- to 'rioStdIn' to have the child read from 'stdInput'. The parent reads from -- 'rioStdOut' to read what the child has written to 'stdOutput'. data RunningIO = RIO { rioStdIn :: Fd , rioStdOut :: OutputStream Char , rioStdErr :: OutputStream Char , rioJsonOut :: OutputStream Value } -- | An opaque type holding the file descriptors used when setting up the -- standard IO environment for command execuction. data StdIOParts = StdIOParts { master1, master2, masterJ, slave1, slave2, slaveJ :: Fd } -- | Allocate the pieces needed for a standard IO execution environment. makeStdIOParts :: IO StdIOParts makeStdIOParts = do (m1, s1) <- openPseudoTerminal (m2, s2) <- openPseudoTerminal (mJ, sJ) <- createPipe mapM_ (\fd -> setFdOption fd CloseOnExec True) [m1, m2, mJ] return $ StdIOParts m1 m2 mJ s1 s2 sJ -- | Prepare a child process for standard IO. Note that this will also set up -- a the controlling terminal and session. Call this in the child side of a -- fork. stdIOChildPrep :: StdIOParts -> IO () stdIOChildPrep sp@StdIOParts {..} = do stdIOCloseMasters sp _ <- createSession PM.setControllingTerminal slave1 stdIOInstallSlaves sp -- | Prepare the master process for communicating with the child. Call this in -- the parent side of a fork. stdIOMasterPrep :: StdIOParts -> IO RunningIO stdIOMasterPrep sp@StdIOParts {..} = do stdIOCloseSlaves sp stdIOBuildRio sp -- | Prepare a standard IO environment for the master process itself. Unlike, -- 'stdIOChildPrep' the controlling terminal and session are not altered. stdIOLocalPrep :: StdIOParts -> IO RunningIO stdIOLocalPrep sp = do stdIOInstallSlaves sp stdIOBuildRio sp stdIOInstallSlaves :: StdIOParts -> IO () stdIOInstallSlaves sp@StdIOParts {..} = do _ <- dupTo slave1 stdInput _ <- dupTo slave1 stdOutput _ <- dupTo slave2 stdError _ <- dupTo slaveJ stdJsonOutput stdIOCloseSlaves sp stdIOBuildRio :: StdIOParts -> IO RunningIO stdIOBuildRio StdIOParts {..} = do RIO master1 <$> outputStreamUtf8 master1 <*> outputStreamUtf8 master2 <*> outputStreamJson masterJ stdIOCloseSlaves :: StdIOParts -> IO () stdIOCloseSlaves StdIOParts {..} = do closeFd slave1 closeFd slave2 closeFd slaveJ stdIOCloseMasters :: StdIOParts -> IO () stdIOCloseMasters StdIOParts {..} = do closeFd master1 closeFd master2 closeFd masterJ
mzero/plush
src/Plush/Job/StdIO.hs
apache-2.0
3,591
0
10
713
641
337
304
66
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Program : ashellogl.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:43 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Main where import Qtc.Enums.Classes.Core import Qtc.Classes.Qccs import Qtc.Classes.Qccs_h import Qtc.Classes.Core import Qtc.Classes.Gui import Qtc.Classes.Opengl import Qtc.ClassTypes.Opengl import Qtc.ClassTypes.Gui import Qtc.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QSlider import Qtc.Core.Base import Qtc.Gui.Base import Qtc.Core.QCoreApplication import Qtc.Core.QSize import Qtc.Gui.QApplication import Qtc.Gui.QLayout import Qtc.Gui.QBoxLayout import Qtc.Gui.QHBoxLayout import Qtc.Gui.QVBoxLayout import Qtc.Gui.QLabel import Qtc.Gui.QWidget import Qtc.Gui.QGroupBox import Qtc.Gui.QColor import Qtc.Gui.QMouseEvent import Qtc.Gui.QAbstractSlider import Qtc.Gui.QSlider import Qtc.Opengl.QGLWidget import Qtc.Opengl.QGLWidget_h import Data.IORef import Data.List import Data.Bits import Array import Graphics.Rendering.OpenGL as GL import Qtc.Enums.Gui.QSizePolicy import Qt.Arthur.Style type MyQWidget = QWidgetSc (CMyQWidget) data CMyQWidget = CMyQWidget myQWidget :: IO (MyQWidget) myQWidget = qSubClass (qWidget ()) type GLWidget = QGLWidgetSc (CGLWidget) data CGLWidget = CGLWidget gLWidget :: IO (GLWidget) gLWidget = qSubClass (qGLWidget ()) trolltechGreen :: IO (QColor ()) trolltechGreen = qColorFromCmykF (0.40::Double, 0.0::Double, 1.0::Double, 0.0::Double) trolltechPurple :: IO (QColor ()) trolltechPurple = qColorFromCmykF (0.39::Double, 0.39::Double, 0.0::Double, 0.0::Double) main :: IO () main = do app <- qApplication () w <- myQWidget glw <- gLWidget rot <- newIORef (0, 0, 0) pos <- newIORef (0, 0) setHandler glw "initializeGL()" $ initgl rot setHandler glw "(QSize)minimumSizeHint()" $ minSizeHint setHandler glw "(QSize)sizeHint()" $ szHint setHandler glw "mousePressEvent(QMouseEvent*)" $ msPressEvent pos setHandler glw "mouseMoveEvent(QMouseEvent*)" $ msMoveEvent pos rot mainGroup <- qGroupBox w setTitle mainGroup "Controls" xSliderGroup <- qGroupBox mainGroup setAttribute xSliderGroup eWA_ContentsPropagated setTitle xSliderGroup "X" xSlider <- createSlider xSliderGroup ySliderGroup <- qGroupBox mainGroup setAttribute ySliderGroup eWA_ContentsPropagated setTitle ySliderGroup "Y" ySlider <- createSlider ySliderGroup zSliderGroup <- qGroupBox mainGroup setAttribute zSliderGroup eWA_ContentsPropagated setTitle zSliderGroup "Z" zSlider <- createSlider zSliderGroup setFixedWidth mainGroup 206 mainGroupLayout <- qHBoxLayout mainGroup addWidget mainGroupLayout xSliderGroup addWidget mainGroupLayout ySliderGroup addWidget mainGroupLayout zSliderGroup xSliderGroupLayout <- qHBoxLayout xSliderGroup addWidget xSliderGroupLayout xSlider ySliderGroupLayout <- qHBoxLayout ySliderGroup addWidget ySliderGroupLayout ySlider zSliderGroupLayout <- qHBoxLayout zSliderGroup addWidget zSliderGroupLayout zSlider connectSlot xSlider "valueChanged(int)" glw "setXRotation(int)" $ setXRotation rot connectSlot glw "xRotationChanged(int)" xSlider "setValue(int)" () connectSlot ySlider "valueChanged(int)" glw "setYRotation(int)" $ setYRotation rot connectSlot glw "yRotationChanged(int)" ySlider "setValue(int)" () connectSlot zSlider "valueChanged(int)" glw "setZRotation(int)" $ setZRotation rot connectSlot glw "zRotationChanged(int)" zSlider "setValue(int)" () glGroup <- qGroupBox w glGroupLayout <- qVBoxLayout glGroup addWidget glGroupLayout glw layout <- qHBoxLayout () addWidget layout glGroup addWidget layout mainGroup setLayout w layout setStyleChildren w =<< arthurStyle qshow w () ok <- qApplicationExec () returnGC msPressEvent :: IORef (Int, Int) -> GLWidget -> QMouseEvent () -> IO () msPressEvent pos this mev = do mx <- qx mev () my <- qy mev () modifyIORef pos (\(p_x, p_y) -> (mx, my)) msMoveEvent :: IORef (Int, Int) -> IORef (Int, Int, Int) -> GLWidget -> QMouseEvent () -> IO () msMoveEvent pos rot this mev = do mx <- qx mev () my <- qy mev () buttons <- buttons mev () (r_x, r_y) <- readIORef pos let mdx = r_x - mx let mdy = r_y - my let alb = (qFlags_toInt buttons) .&. (qFlags_toInt fLeftButton) let arb = (qFlags_toInt buttons) .&. (qFlags_toInt fRightButton) (r_x, r_y, r_z) <- readIORef rot do if (alb > 0) then do setXRotation rot this $ r_x + 8 * mdy setYRotation rot this $ r_y + 8 * mdx else return () if (arb > 0) then do setXRotation rot this $ r_x + 8 * mdy setZRotation rot this $ r_z + 8 * mdx else return () modifyIORef pos (\(p_x, p_y) -> (mx, my)) return () createSlider :: QGroupBox () -> IO (QSlider ()) createSlider gb = do slider <- qSlider (eVertical::QtOrientation, gb) setRange slider (0::Int, (360 * 16)::Int) setSingleStep slider (16::Int) setPageStep slider $ ((15 * 16)::Int) setTickInterval slider $ ((15 * 16)::Int) setTickPosition slider eTicksRight return slider initgl :: IORef (Int, Int, Int) -> GLWidget -> IO () initgl rot this = do tp <- trolltechPurple cd <- dark tp () qglClearColor this cd dl <- makeObject this shadeModel $= Flat depthFunc $= Just Less cullFace $= Just Back setHandler this "resizeGL(int,int)" rsz setHandler this "paintGL()" $ dsply rot dl return () setXRotation :: IORef (Int, Int, Int) -> GLWidget -> Int -> IO () setXRotation rot this angle = do nang <- normalizeAngle angle (r_x, r_y, r_z) <- readIORef rot return () if (nang /= r_x) then do modifyIORef rot (\(r_x, r_y, r_z) -> (nang, r_y , r_z)) emitSignal this "xRotationChanged(int)" nang updateGL this () else return () setYRotation :: IORef (Int, Int, Int) -> GLWidget -> Int -> IO () setYRotation rot this angle = do nang <- normalizeAngle angle (r_x, r_y, r_z) <- readIORef rot return () if (nang /= r_y) then do modifyIORef rot (\(r_x, r_y, r_z) -> (r_x, nang , r_z)) emitSignal this "yRotationChanged(int)" nang updateGL this () else return () setZRotation :: IORef (Int, Int, Int) -> GLWidget -> Int -> IO () setZRotation rot this angle = do nang <- normalizeAngle angle (r_x, r_y, r_z) <- readIORef rot return () if (nang /= r_z) then do modifyIORef rot (\(r_x, r_y, r_z) -> (r_x, r_y , nang)) emitSignal this "zRotationChanged(int)" nang updateGL this () else return () normalizeAngle :: Int -> IO (Int) normalizeAngle ang = do let a1 = normUp ang let a2 = normDown a1 return a2 normUp :: Int -> Int normUp a | a >= 0 = a normUp a = normUp $ a + (360 * 16) normDown :: Int -> Int normDown a | a <= (360 * 16) = a normDown a = normDown $ a - (360 * 16) minSizeHint :: GLWidget -> IO (QSize ()) minSizeHint this = do qSize (100::Int, 100::Int) szHint :: GLWidget -> IO (QSize ()) szHint this = do qSize (400::Int, 400::Int) dsply :: IORef (Int, Int, Int) -> DisplayList -> GLWidget -> IO () dsply rot dl this = do (r_x, r_y, r_z) <- readIORef rot GL.clear [ ColorBuffer, DepthBuffer ] loadIdentity GL.translate $ Vector3 0 0 (-10.0::GLdouble) GL.rotate ((fromIntegral r_x)/16.0) $ Vector3 (1.0::GLfloat) 0.0 0.0 GL.rotate ((fromIntegral r_y)/16.0) $ Vector3 (0.0::GLfloat) 1.0 0.0 GL.rotate ((fromIntegral r_z)/16.0) $ Vector3 (0.0::GLfloat) 0.0 1.0 callList dl returnGC rsz :: GLWidget -> Int -> Int -> IO () rsz this x y = do let side = min x y let p1 = round $ (fromIntegral $ x - side) / 2.0 let p2 = round $ (fromIntegral $ y - side) / 2.0 GL.viewport $= (Position (fromIntegral p1) (fromIntegral p2), GL.Size (fromIntegral side) (fromIntegral side)) matrixMode $= Projection loadIdentity ortho (-0.5::GLdouble) 0.5 0.5 (-0.5) 4.0 15.0 matrixMode $= Modelview 0 return () makeObject :: QGLWidget a -> IO (DisplayList) makeObject glw = defineNewList Compile $ do let x1 = 0.06 let y1 = -0.14 let x2 = 0.14 let y2 = -0.06 let x3 = 0.08 let y3 = 0.00 let x4 = 0.30 let y4 = 0.22 let pi = 3.14159265358979323846 renderPrimitive Quads $ do quad glw x1 y1 x2 y2 y2 x2 y1 x1 quad glw x3 y3 x4 y4 y4 x4 y3 x3 extrude glw x1 y1 x2 y2 extrude glw x2 y2 y2 x2 extrude glw y2 x2 y1 x1 extrude glw y1 x1 x1 y1 extrude glw x3 y3 x4 y4 extrude glw x4 y4 y4 x4 extrude glw y4 x4 y3 x3 do_NumSectors glw 0 pi 200 return () do_NumSectors :: QGLWidget a -> Int -> Double -> Int -> IO () do_NumSectors _ i _ ns | i >= ns = return () do_NumSectors glw i pi ns = do let fns = fromIntegral ns let angle1 = ((fromIntegral (i * 2)) * pi) / fns let x5 = realToFrac (0.30 * (sin angle1)) :: GLdouble let y5 = realToFrac (0.30 * (cos angle1)) :: GLdouble let x6 = realToFrac (0.20 * (sin angle1)) :: GLdouble let y6 = realToFrac (0.20 * (cos angle1)) :: GLdouble let angle2 = ((fromIntegral ((i + 1) * 2)) * pi) / fns let x7 = realToFrac (0.20 * sin(angle2)) :: GLdouble let y7 = realToFrac (0.20 * cos(angle2)) :: GLdouble let x8 = realToFrac (0.30 * sin(angle2)) :: GLdouble let y8 = realToFrac (0.30 * cos(angle2)) :: GLdouble quad glw x5 y5 x6 y6 x7 y7 x8 y8 extrude glw x6 y6 x7 y7 extrude glw x8 y8 x5 y5 do_NumSectors glw (i + 1) pi ns return () quad :: QGLWidget a -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO () quad glw x1 y1 x2 y2 x3 y3 x4 y4 = do qglColor glw =<< trolltechGreen vertex $ Vertex3 x1 y1 (-0.05) vertex $ Vertex3 x2 y2 (-0.05) vertex $ Vertex3 x3 y3 (-0.05) vertex $ Vertex3 x4 y4 (-0.05) vertex $ Vertex3 x4 y4 0.05 vertex $ Vertex3 x3 y3 0.05 vertex $ Vertex3 x2 y2 0.05 vertex $ Vertex3 x1 y1 0.05 return () extrude :: QGLWidget a -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO () extrude glw x1 y1 x2 y2 = do tg <- trolltechGreen let xrp = truncate $ x1 * 100.0 dc <- darker tg $ (xrp::Int) + 250 qglColor glw dc vertex $ Vertex3 x1 y1 0.05 vertex $ Vertex3 x2 y2 0.05 vertex $ Vertex3 x2 y2 (-0.05) vertex $ Vertex3 x1 y1 (-0.05) return ()
uduki/hsQt
examples/ashellogl.hs
bsd-2-clause
10,811
0
18
2,526
4,096
1,997
2,099
311
3
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} -- | -- Module : Statistics.Distribution.FDistribution -- Copyright : (c) 2011 Aleksey Khudyakov -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Fisher F distribution module Statistics.Distribution.FDistribution ( FDistribution , fDistribution , fDistributionNDF1 , fDistributionNDF2 ) where import Data.Aeson (FromJSON, ToJSON) import Data.Binary (Binary) import Data.Data (Data, Typeable) import Numeric.MathFunctions.Constants (m_neg_inf) import GHC.Generics (Generic) import qualified Statistics.Distribution as D import Statistics.Function (square) import Numeric.SpecFunctions ( logBeta, incompleteBeta, invIncompleteBeta, digamma) import Data.Binary (put, get) import Control.Applicative ((<$>), (<*>)) -- | F distribution data FDistribution = F { fDistributionNDF1 :: {-# UNPACK #-} !Double , fDistributionNDF2 :: {-# UNPACK #-} !Double , _pdfFactor :: {-# UNPACK #-} !Double } deriving (Eq, Show, Read, Typeable, Data, Generic) instance FromJSON FDistribution instance ToJSON FDistribution instance Binary FDistribution where get = F <$> get <*> get <*> get put (F x y z) = put x >> put y >> put z fDistribution :: Int -> Int -> FDistribution fDistribution n m | n > 0 && m > 0 = let n' = fromIntegral n m' = fromIntegral m f' = 0.5 * (log m' * m' + log n' * n') - logBeta (0.5*n') (0.5*m') in F n' m' f' | otherwise = error "Statistics.Distribution.FDistribution.fDistribution: non-positive number of degrees of freedom" instance D.Distribution FDistribution where cumulative = cumulative instance D.ContDistr FDistribution where density d x | x <= 0 = 0 | otherwise = exp $ logDensity d x logDensity d x | x <= 0 = m_neg_inf | otherwise = logDensity d x quantile = quantile cumulative :: FDistribution -> Double -> Double cumulative (F n m _) x | x <= 0 = 0 | isInfinite x = 1 -- Only matches +∞ | otherwise = let y = n*x in incompleteBeta (0.5 * n) (0.5 * m) (y / (m + y)) logDensity :: FDistribution -> Double -> Double logDensity (F n m fac) x = fac + log x * (0.5 * n - 1) - log(m + n*x) * 0.5 * (n + m) quantile :: FDistribution -> Double -> Double quantile (F n m _) p | p >= 0 && p <= 1 = let x = invIncompleteBeta (0.5 * n) (0.5 * m) p in m * x / (n * (1 - x)) | otherwise = error $ "Statistics.Distribution.Uniform.quantile: p must be in [0,1] range. Got: "++show p instance D.MaybeMean FDistribution where maybeMean (F _ m _) | m > 2 = Just $ m / (m - 2) | otherwise = Nothing instance D.MaybeVariance FDistribution where maybeStdDev (F n m _) | m > 4 = Just $ 2 * square m * (m + n - 2) / (n * square (m - 2) * (m - 4)) | otherwise = Nothing instance D.Entropy FDistribution where entropy (F n m _) = let nHalf = 0.5 * n mHalf = 0.5 * m in log (n/m) + logBeta nHalf mHalf + (1 - nHalf) * digamma nHalf - (1 + mHalf) * digamma mHalf + (nHalf + mHalf) * digamma (nHalf + mHalf) instance D.MaybeEntropy FDistribution where maybeEntropy = Just . D.entropy instance D.ContGen FDistribution where genContVar = D.genContinous
fpco/statistics
Statistics/Distribution/FDistribution.hs
bsd-2-clause
3,389
0
17
869
1,193
619
574
80
1
{-# LANGUAGE DeriveDataTypeable #-} module Network.Bluetooth.Exception (BluetoothException(..)) where import Control.Exception import Data.Typeable import Network.Bluetooth.Protocol data BluetoothException = BluetoothPortException BluetoothProtocol BluetoothPort deriving Typeable instance Show BluetoothException where showsPrec _ (BluetoothPortException L2CAP port) = showString "L2CAP port " . shows port . showString " is not an odd number between 4,097 and 32,767." showsPrec _ (BluetoothPortException RFCOMM port) = showString "RFCOMM port " . shows port . showString " is not between 1 and 30." instance Exception BluetoothException
bneijt/bluetooth
src/Network/Bluetooth/Exception.hs
bsd-3-clause
654
0
8
90
132
69
63
11
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Server and client game state types and operations. module Game.LambdaHack.Client.State ( StateClient(..), defStateClient, defaultHistory , updateTarget, getTarget, updateLeader, sside , PathEtc, TgtMode(..), RunParams(..), LastRecord, EscAI(..) , toggleMarkVision, toggleMarkSmell, toggleMarkSuspect ) where import Control.Exception.Assert.Sugar import Data.Binary import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import Data.Text (Text) import qualified Data.Text as T import qualified NLP.Miniutter.English as MU import qualified System.Random as R import System.Time import Game.LambdaHack.Atomic import Game.LambdaHack.Client.Bfs import Game.LambdaHack.Client.ItemSlot import qualified Game.LambdaHack.Client.Key as K import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.ClientOptions import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.Msg import Game.LambdaHack.Common.Perception import Game.LambdaHack.Common.Point import qualified Game.LambdaHack.Common.PointArray as PointArray import Game.LambdaHack.Common.State import Game.LambdaHack.Common.Time import Game.LambdaHack.Common.Vector -- | Client state, belonging to a single faction. -- Some of the data, e.g, the history, carries over -- from game to game, even across playing sessions. -- Data invariant: if @_sleader@ is @Nothing@ then so is @srunning@. data StateClient = StateClient { stgtMode :: !(Maybe TgtMode) -- ^ targeting mode , scursor :: !Target -- ^ the common, cursor target , seps :: !Int -- ^ a parameter of the tgt digital line , stargetD :: !(EM.EnumMap ActorId (Target, Maybe PathEtc)) -- ^ targets of our actors in the dungeon , sexplored :: !(ES.EnumSet LevelId) -- ^ the set of fully explored levels , sbfsD :: !(EM.EnumMap ActorId ( Bool, PointArray.Array BfsDistance , Point, Int, Maybe [Point]) ) -- ^ pathfinding distances for our actors -- and paths to their targets, if any , sselected :: !(ES.EnumSet ActorId) -- ^ the set of currently selected actors , srunning :: !(Maybe RunParams) -- ^ parameters of the current run, if any , sreport :: !Report -- ^ current messages , shistory :: !History -- ^ history of messages , sdisplayed :: !(EM.EnumMap LevelId Time) -- ^ moves are displayed up to this time , sundo :: ![CmdAtomic] -- ^ atomic commands performed to date , sdiscoKind :: !DiscoveryKind -- ^ remembered item discoveries , sdiscoEffect :: !DiscoveryEffect -- ^ remembered effects&Co of items , sfper :: !FactionPers -- ^ faction perception indexed by levels , srandom :: !R.StdGen -- ^ current random generator , slastKM :: !K.KM -- ^ last issued key command , slastRecord :: !LastRecord -- ^ state of key sequence recording , slastPlay :: ![K.KM] -- ^ state of key sequence playback , slastLost :: !(ES.EnumSet ActorId) -- ^ actors that just got out of sight , swaitTimes :: !Int -- ^ player just waited this many times , _sleader :: !(Maybe ActorId) -- ^ current picked party leader , _sside :: !FactionId -- ^ faction controlled by the client , squit :: !Bool -- ^ exit the game loop , sisAI :: !Bool -- ^ whether it's an AI client , smarkVision :: !Bool -- ^ mark leader and party FOV , smarkSmell :: !Bool -- ^ mark smell, if the leader can smell , smarkSuspect :: !Bool -- ^ mark suspect features , scurDiff :: !Int -- ^ current game difficulty level , snxtDiff :: !Int -- ^ next game difficulty level , sslots :: !ItemSlots -- ^ map from slots to items , slastSlot :: !SlotChar -- ^ last used slot , slastStore :: !CStore -- ^ last used store , sescAI :: !EscAI -- ^ just canceled AI control with ESC , sdebugCli :: !DebugModeCli -- ^ client debugging mode } deriving Show type PathEtc = ([Point], (Point, Int)) -- | Current targeting mode of a client. newtype TgtMode = TgtMode { tgtLevelId :: LevelId } deriving (Show, Eq, Binary) -- | Parameters of the current run. data RunParams = RunParams { runLeader :: !ActorId -- ^ the original leader from run start , runMembers :: ![ActorId] -- ^ the list of actors that take part , runInitial :: !Bool -- ^ initial run continuation by any -- run participant, including run leader , runStopMsg :: !(Maybe Text) -- ^ message with the next stop reason , runWaiting :: !Int -- ^ waiting for others to move out of the way } deriving (Show) type LastRecord = ( [K.KM] -- accumulated keys of the current command , [K.KM] -- keys of the rest of the recorded command batch , Int -- commands left to record for this batch ) data EscAI = EscAINothing | EscAIStarted | EscAIMenu | EscAIExited deriving (Show, Eq) -- | Initial game client state. defStateClient :: History -> Report -> FactionId -> Bool -> StateClient defStateClient shistory sreport _sside sisAI = StateClient { stgtMode = Nothing , scursor = if sisAI then TVector $ Vector 30000 30000 -- invalid else TVector $ Vector 1 1 -- a step south-east , seps = fromEnum _sside , stargetD = EM.empty , sexplored = ES.empty , sbfsD = EM.empty , sselected = ES.empty , srunning = Nothing , sreport , shistory , sdisplayed = EM.empty , sundo = [] , sdiscoKind = EM.empty , sdiscoEffect = EM.empty , sfper = EM.empty , srandom = R.mkStdGen 42 -- will be set later , slastKM = K.escKM , slastRecord = ([], [], 0) , slastPlay = [] , slastLost = ES.empty , swaitTimes = 0 , _sleader = Nothing -- no heroes yet alive , _sside , squit = False , sisAI , smarkVision = False , smarkSmell = True , smarkSuspect = False , scurDiff = difficultyDefault , snxtDiff = difficultyDefault , sslots = (EM.empty, EM.empty) , slastSlot = SlotChar 0 'Z' , slastStore = CInv , sescAI = EscAINothing , sdebugCli = defDebugModeCli } defaultHistory :: Int -> IO History defaultHistory configHistoryMax = do dateTime <- getClockTime let curDate = MU.Text $ T.pack $ calendarTimeToString $ toUTCTime dateTime let emptyHist = emptyHistory configHistoryMax return $! addReport emptyHist timeZero $! singletonReport $! makeSentence ["Human history log started on", curDate] -- | Update target parameters within client state. updateTarget :: ActorId -> (Maybe Target -> Maybe Target) -> StateClient -> StateClient updateTarget aid f cli = let f2 tp = case f $ fmap fst tp of Nothing -> Nothing Just tgt -> Just (tgt, Nothing) -- reset path in cli {stargetD = EM.alter f2 aid (stargetD cli)} -- | Get target parameters from client state. getTarget :: ActorId -> StateClient -> Maybe Target getTarget aid cli = fmap fst $ EM.lookup aid $ stargetD cli -- | Update picked leader within state. Verify actor's faction. updateLeader :: ActorId -> State -> StateClient -> StateClient updateLeader leader s cli = let side1 = bfid $ getActorBody leader s side2 = sside cli in assert (side1 == side2 `blame` "enemy actor becomes our leader" `twith` (side1, side2, leader, s)) $ cli {_sleader = Just leader} sside :: StateClient -> FactionId sside = _sside toggleMarkVision :: StateClient -> StateClient toggleMarkVision s@StateClient{smarkVision} = s {smarkVision = not smarkVision} toggleMarkSmell :: StateClient -> StateClient toggleMarkSmell s@StateClient{smarkSmell} = s {smarkSmell = not smarkSmell} toggleMarkSuspect :: StateClient -> StateClient toggleMarkSuspect s@StateClient{smarkSuspect} = s {smarkSuspect = not smarkSuspect} instance Binary StateClient where put StateClient{..} = do put stgtMode put scursor put seps put stargetD put sexplored put sselected put srunning put sreport put shistory put sundo put sdisplayed put sdiscoKind put sdiscoEffect put (show srandom) put _sleader put _sside put sisAI put smarkVision put smarkSmell put smarkSuspect put scurDiff put snxtDiff put sslots put slastSlot put slastStore put sdebugCli -- TODO: this is overwritten at once get = do stgtMode <- get scursor <- get seps <- get stargetD <- get sexplored <- get sselected <- get srunning <- get sreport <- get shistory <- get sundo <- get sdisplayed <- get sdiscoKind <- get sdiscoEffect <- get g <- get _sleader <- get _sside <- get sisAI <- get smarkVision <- get smarkSmell <- get smarkSuspect <- get scurDiff <- get snxtDiff <- get sslots <- get slastSlot <- get slastStore <- get sdebugCli <- get let sbfsD = EM.empty sfper = EM.empty srandom = read g slastKM = K.escKM slastRecord = ([], [], 0) slastPlay = [] slastLost = ES.empty swaitTimes = 0 squit = False sescAI = EscAINothing return $! StateClient{..} instance Binary RunParams where put RunParams{..} = do put runLeader put runMembers put runInitial put runStopMsg put runWaiting get = do runLeader <- get runMembers <- get runInitial <- get runStopMsg <- get runWaiting <- get return $! RunParams{..}
Concomitant/LambdaHack
Game/LambdaHack/Client/State.hs
bsd-3-clause
10,273
0
14
2,968
2,247
1,249
998
-1
-1
-- Copyright (c) 2015 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. {-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-} {-# LANGUAGE MultiParamTypeClasses #-} -- | A class of monads for outputting compiler messages. module Control.Monad.TypeErrors.Class( MonadTypeErrors(..) ) where import Data.Pos import Language.Salt.Core.Syntax -- | Monad class representing the different kinds of compiler error -- messages that can be generated. class Monad m => MonadTypeErrors sym m where -- | Log a type mismatch error, when a term's actual type is not a -- subtype of its expected type. typeMismatch :: Term sym sym -- ^ The term from which this originates. -> Term sym sym -- ^ The expected type. -> Term sym sym -- ^ The actual type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an error when a term with a particular type was expected, -- but the term wasn't of the right form. formMismatch :: Term sym sym -- ^ The term whose form is incorrect. -> Term sym sym -- ^ The term's expected type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an error when term with a function type is expected, but -- the actual type is something else expectedFunction :: Term sym sym -- ^ The term from which this originates. -> Term sym sym -- ^ The term's actual type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an error for an unbounded-rank type. infiniteType :: Term sym sym -- ^ The illegal type. -> Term sym sym -- ^ The term's actual type. -> m (Term sym sym) -- ^ A type to return instead of the expected type. -- | Log an undefined symbol error. undefSym :: sym -- ^ The symbol that is not defined. -> Pos -- ^ The position at which this occurred. -> m (Term sym sym) -- ^ A type representing the type of undefined symbols.
emc2/saltlang
src/salt/Control/Monad/TypeErrors/Class.hs
bsd-3-clause
3,765
0
12
1,051
274
166
108
23
0
-- Utility functions for dealing with the conversion of Output to Xml module Util.Xml.Output ( outputToXmlString, stringToXmlString, xmlStringToOutput ) where import qualified Util.Xml.OutputDTD as X import qualified Autolib.Output as O import Text.XML.HaXml hiding (o, txt) import Text.XML.HaXml.Pretty import Text.XML.HaXml.XmlContent import Text.PrettyPrint.HughesPJ hiding (style) import qualified Autolib.Multilingual.Doc as D import qualified Codec.Binary.Base64 as C import qualified Data.ByteString as B import System.FilePath import Control.Applicative import Data.Maybe import Util.Png outputToXOutput :: O.Output -> IO X.Output outputToXOutput o = case o of O.Empty -> return $ X.OBeside $ X.Beside [] O.Doc doc -> outputToXOutput $ O.Pre doc O.Text txt -> return $ X.OText $ X.Text txt O.Pre txt -> return $ X.OPre $ X.Pre (show txt) O.Image file contents -> do let ext = drop 1 $ snd $ splitExtension file contents' <- contents let (w, h) = case ext of "png" -> (pngSize contents') _ -> (0, 0) img = C.encode (B.unpack contents') return $ X.OImage $ X.Image (X.Image_Attrs { X.imageType = ext, X.imageAlt = "<image>", X.imageUnit = "px", X.imageWidth = show w, X.imageHeight = show h }) img O.Link uri -> outputToXOutput (O.Named_Link uri uri) O.Named_Link txt uri -> return $ X.OLink $ X.Link (X.Link_Attrs { X.linkHref = uri }) txt O.Above o1 o2 -> X.OAbove . X.Above <$> mapM outputToXOutput (aboves o1 ++ aboves o2) O.Beside o1 o2 -> X.OBeside . X.Beside <$> mapM outputToXOutput (besides o1 ++ besides o2) O.Itemize os -> X.OItemize . X.Itemize <$> mapM outputToXOutput os O.Nest o' -> X.OBeside . X.Beside <$> sequence [return nestSpacing, outputToXOutput o'] O.Figure a b -> X.OFigure <$> (X.Figure <$> outputToXOutput a <*> outputToXOutput b) xoutputToOutput :: X.Output -> O.Output xoutputToOutput o = case o of X.OPre (X.Pre txt) -> O.Pre (D.text txt) X.OText (X.Text txt) -> O.Text txt X.OImage (X.Image _ img) -> O.Image (mkData img) (return $ B.pack $ fromJust $ C.decode img) X.OLink (X.Link (X.Link_Attrs { X.linkHref = uri }) txt) -> O.Named_Link txt uri X.OAbove (X.Above []) -> O.Empty X.OAbove (X.Above xs) -> foldl1 O.Above $ map xoutputToOutput xs X.OBeside (X.Beside []) -> O.Empty X.OBeside (X.Beside xs) -> foldl1 O.Beside $ map xoutputToOutput xs X.OItemize (X.Itemize xs) -> O.Itemize $ map xoutputToOutput xs X.OSpace _ -> O.Empty -- FIXME X.OFigure (X.Figure a b) -> O.Figure (xoutputToOutput a) (xoutputToOutput b) mkData = ("data:image/png;base64," ++) wrapXOutput :: X.Output -> Document () wrapXOutput o = let [CElem e _] = toContents o in Document (Prolog (Just (XMLDecl "1.0" Nothing Nothing)) [] Nothing []) emptyST e [] xmlToString :: Document () -> String xmlToString = renderStyle style . document where style = Style OneLineMode 0 0 outputToXmlString :: O.Output -> IO String outputToXmlString = fmap (xmlToString . wrapXOutput) . outputToXOutput xmlStringToOutput :: String -> O.Output xmlStringToOutput = xoutputToOutput . either error id . readXml stringToXmlString :: String -> String stringToXmlString = xmlToString . wrapXOutput . X.OText . X.Text -- helpers for outputToXOutput nestSpacing :: X.Output nestSpacing = X.OSpace $ X.Space { X.spaceWidth = "4", X.spaceHeight = "0", X.spaceUnit = "em" } besides :: O.Output -> [O.Output] besides (O.Beside a b) = besides a ++ besides b besides a = [a] aboves :: O.Output -> [O.Output] aboves (O.Above a b) = aboves a ++ aboves b aboves a = [a]
Erdwolf/autotool-bonn
server/src/Util/Xml/Output.hs
gpl-2.0
3,955
0
17
1,035
1,456
743
713
95
13
#if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Safe #-} #endif -- | Produces XHTML 1.0 Frameset. module Text.XHtml.Frameset ( -- * Data types Html, HtmlAttr, -- * Classes HTML(..), ADDATTRS(..), CHANGEATTRS(..), -- * Primitives and basic combinators (<<), concatHtml, (+++), noHtml, isNoHtml, tag, itag, htmlAttrPair, emptyAttr, intAttr, strAttr, htmlAttr, primHtml, -- * Rendering showHtml, renderHtml, prettyHtml, showHtmlFragment, renderHtmlFragment, prettyHtmlFragment, module Text.XHtml.Strict.Elements, module Text.XHtml.Frameset.Elements, module Text.XHtml.Strict.Attributes, module Text.XHtml.Frameset.Attributes, module Text.XHtml.Extras ) where import Text.XHtml.Internals import Text.XHtml.Strict.Elements import Text.XHtml.Frameset.Elements import Text.XHtml.Strict.Attributes import Text.XHtml.Frameset.Attributes import Text.XHtml.Extras docType :: String docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\"" ++ " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">" -- | Output the HTML without adding newlines or spaces within the markup. -- This should be the most time and space efficient way to -- render HTML, though the ouput is quite unreadable. showHtml :: HTML html => html -> String showHtml = showHtmlInternal docType -- | Outputs indented HTML. Because space matters in -- HTML, the output is quite messy. renderHtml :: HTML html => html -> String renderHtml = renderHtmlInternal docType -- | Outputs indented HTML, with indentation inside elements. -- This can change the meaning of the HTML document, and -- is mostly useful for debugging the HTML output. -- The implementation is inefficient, and you are normally -- better off using 'showHtml' or 'renderHtml'. prettyHtml :: HTML html => html -> String prettyHtml = prettyHtmlInternal docType
DavidAlphaFox/ghc
libraries/xhtml/Text/XHtml/Frameset.hs
bsd-3-clause
1,920
0
6
352
280
186
94
30
1
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable {-# LANGUAGE PatternGuards #-} module Cryptol.TypeCheck ( tcModule , tcExpr , tcDecls , InferInput(..) , InferOutput(..) , SolverConfig(..) , NameSeeds , nameSeeds , Error(..) , Warning(..) , ppWarning , ppError ) where import qualified Cryptol.Parser.AST as P import Cryptol.Parser.Position(Range) import Cryptol.TypeCheck.AST import Cryptol.TypeCheck.Depends (FromDecl) import Cryptol.TypeCheck.Monad ( runInferM , InferInput(..) , InferOutput(..) , NameSeeds , nameSeeds , lookupVar ) import Cryptol.TypeCheck.Infer (inferModule, inferBinds, inferDs) import Cryptol.TypeCheck.InferTypes(Error(..),Warning(..),VarType(..), SolverConfig(..)) import Cryptol.TypeCheck.Solve(simplifyAllConstraints) import Cryptol.Utils.PP import Cryptol.Utils.Panic(panic) tcModule :: P.Module -> InferInput -> IO (InferOutput Module) tcModule m inp = runInferM inp $ do x <- inferModule m simplifyAllConstraints return x tcExpr :: P.Expr -> InferInput -> IO (InferOutput (Expr,Schema)) tcExpr e0 inp = runInferM inp $ do x <- go e0 simplifyAllConstraints return x where go expr = case expr of P.ELocated e _ -> go e P.EVar x -> do res <- lookupVar x case res of ExtVar s -> return (EVar x, s) CurSCC e' t -> panic "Cryptol.TypeCheck.tcExpr" [ "CurSCC outside binder checkig:" , show e' , show t ] _ -> do res <- inferBinds True False [ P.Bind { P.bName = P.Located (inpRange inp) $ mkUnqual (P.mkName "(expression)") , P.bParams = [] , P.bDef = P.Located (inpRange inp) (P.DExpr expr) , P.bPragmas = [] , P.bSignature = Nothing , P.bMono = False , P.bInfix = False , P.bFixity = Nothing , P.bDoc = Nothing } ] case res of [d] | DExpr e <- dDefinition d -> return (e, dSignature d) | otherwise -> panic "Cryptol.TypeCheck.tcExpr" [ "Expected an expression in definition" , show d ] _ -> panic "Cryptol.TypeCheck.tcExpr" ( "Multiple declarations when check expression:" : map show res ) tcDecls :: FromDecl d => [d] -> InferInput -> IO (InferOutput [DeclGroup]) tcDecls ds inp = runInferM inp $ inferDs ds $ \dgs -> do simplifyAllConstraints return dgs ppWarning :: (Range,Warning) -> Doc ppWarning (r,w) = text "[warning] at" <+> pp r <> colon $$ nest 2 (pp w) ppError :: (Range,Error) -> Doc ppError (r,w) = text "[error] at" <+> pp r <> colon $$ nest 2 (pp w)
iblumenfeld/cryptol
src/Cryptol/TypeCheck.hs
bsd-3-clause
3,563
0
21
1,516
889
482
407
80
5
module PackageTests.BuildDeps.InternalLibrary1.Check where import PackageTests.PackageTester import System.FilePath import Test.HUnit suite :: FilePath -> Test suite ghcPath = TestCase $ do let spec = PackageSpec ("PackageTests" </> "BuildDeps" </> "InternalLibrary1") [] result <- cabal_build spec ghcPath assertBuildSucceeded result
jwiegley/ghc-release
libraries/Cabal/cabal/tests/PackageTests/BuildDeps/InternalLibrary1/Check.hs
gpl-3.0
350
0
14
52
89
46
43
9
1
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE DataKinds, PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module T14369 where data family Sing (a :: k) data instance Sing (z :: Maybe a) where SNothing :: Sing Nothing SJust :: Sing x -> Sing (Just x) class SingKind k where type Demote k = r | r -> k fromSing :: Sing (a :: k) -> Demote k instance SingKind a => SingKind (Maybe a) where type Demote (Maybe a) = Maybe (Demote a) fromSing SNothing = Nothing fromSing (SJust x) = Just (fromSing x) f :: forall (x :: forall a. Maybe a) a. SingKind a => Sing x -> Maybe (Demote a) f = fromSing
sdiehl/ghc
testsuite/tests/indexed-types/should_fail/T14369.hs
bsd-3-clause
808
1
11
157
247
132
115
-1
-1
-- (c) The University of Glasgow 2012 {-# LANGUAGE CPP, DataKinds, DeriveDataTypeable, GADTs, KindSignatures, ScopedTypeVariables, StandaloneDeriving #-} -- | Module for coercion axioms, used to represent type family instances -- and newtypes module CoAxiom ( BranchFlag, Branched, Unbranched, BranchIndex, BranchList(..), toBranchList, fromBranchList, toBranchedList, toUnbranchedList, brFromUnbranchedSingleton, brListLength, brListNth, brListMap, brListFoldr, brListMapM, brListFoldlM_, brListZipWith, CoAxiom(..), CoAxBranch(..), toBranchedAxiom, toUnbranchedAxiom, coAxiomName, coAxiomArity, coAxiomBranches, coAxiomTyCon, isImplicitCoAxiom, coAxiomNumPats, coAxiomNthBranch, coAxiomSingleBranch_maybe, coAxiomRole, coAxiomSingleBranch, coAxBranchTyVars, coAxBranchRoles, coAxBranchLHS, coAxBranchRHS, coAxBranchSpan, coAxBranchIncomps, placeHolderIncomps, Role(..), fsFromRole, CoAxiomRule(..), Eqn, BuiltInSynFamily(..), trivialBuiltInFamily ) where import {-# SOURCE #-} TypeRep ( Type ) import {-# SOURCE #-} TyCon ( TyCon ) import Outputable import FastString import Name import Unique import Var import Util import Binary import Pair import BasicTypes import Data.Typeable ( Typeable ) import SrcLoc import qualified Data.Data as Data #include "HsVersions.h" {- Note [Coercion axiom branches] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to allow type family instance groups, an axiom needs to contain an ordered list of alternatives, called branches. The kind of the coercion built from an axiom is determined by which index is used when building the coercion from the axiom. For example, consider the axiom derived from the following declaration: type family F a where F [Int] = Bool F [a] = Double F (a b) = Char This will give rise to this axiom: axF :: { F [Int] ~ Bool ; forall (a :: *). F [a] ~ Double ; forall (k :: BOX) (a :: k -> *) (b :: k). F (a b) ~ Char } The axiom is used with the AxiomInstCo constructor of Coercion. If we wish to have a coercion showing that F (Maybe Int) ~ Char, it will look like axF[2] <*> <Maybe> <Int> :: F (Maybe Int) ~ Char -- or, written using concrete-ish syntax -- AxiomInstCo axF 2 [Refl *, Refl Maybe, Refl Int] Note that the index is 0-based. For type-checking, it is also necessary to check that no previous pattern can unify with the supplied arguments. After all, it is possible that some of the type arguments are lambda-bound type variables whose instantiation may cause an earlier match among the branches. We wish to prohibit this behavior, so the type checker rules out the choice of a branch where a previous branch can unify. See also [Apartness] in FamInstEnv.hs. For example, the following is malformed, where 'a' is a lambda-bound type variable: axF[2] <*> <a> <Bool> :: F (a Bool) ~ Char Why? Because a might be instantiated with [], meaning that branch 1 should apply, not branch 2. This is a vital consistency check; without it, we could derive Int ~ Bool, and that is a Bad Thing. Note [Branched axioms] ~~~~~~~~~~~~~~~~~~~~~~ Although a CoAxiom has the capacity to store many branches, in certain cases, we want only one. These cases are in data/newtype family instances, newtype coercions, and type family instances declared with "type instance ...", not "type instance where". Furthermore, these unbranched axioms are used in a variety of places throughout GHC, and it would difficult to generalize all of that code to deal with branched axioms, especially when the code can be sure of the fact that an axiom is indeed a singleton. At the same time, it seems dangerous to assume singlehood in various places through GHC. The solution to this is to label a CoAxiom with a phantom type variable declaring whether it is known to be a singleton or not. The list of branches is stored using a special form of list, declared below, that ensures that the type variable is accurate. ************************************************************************ * * Branch lists * * ************************************************************************ -} type BranchIndex = Int -- The index of the branch in the list of branches -- Counting from zero -- promoted data type data BranchFlag = Branched | Unbranched type Branched = 'Branched deriving instance Typeable 'Branched type Unbranched = 'Unbranched deriving instance Typeable 'Unbranched -- By using type synonyms for the promoted constructors, we avoid needing -- DataKinds and the promotion quote in client modules. This also means that -- we don't need to export the term-level constructors, which should never be used. data BranchList a (br :: BranchFlag) where FirstBranch :: a -> BranchList a br NextBranch :: a -> BranchList a br -> BranchList a Branched deriving instance Typeable BranchList -- convert to/from lists toBranchList :: [a] -> BranchList a Branched toBranchList [] = pprPanic "toBranchList" empty toBranchList [b] = FirstBranch b toBranchList (h:t) = NextBranch h (toBranchList t) fromBranchList :: BranchList a br -> [a] fromBranchList (FirstBranch b) = [b] fromBranchList (NextBranch h t) = h : (fromBranchList t) -- convert from any BranchList to a Branched BranchList toBranchedList :: BranchList a br -> BranchList a Branched toBranchedList (FirstBranch b) = FirstBranch b toBranchedList (NextBranch h t) = NextBranch h t -- convert from any BranchList to an Unbranched BranchList toUnbranchedList :: BranchList a br -> BranchList a Unbranched toUnbranchedList (FirstBranch b) = FirstBranch b toUnbranchedList _ = pprPanic "toUnbranchedList" empty -- Extract a singleton axiom from Unbranched BranchList brFromUnbranchedSingleton :: BranchList a Unbranched -> a brFromUnbranchedSingleton (FirstBranch b) = b -- length brListLength :: BranchList a br -> Int brListLength (FirstBranch _) = 1 brListLength (NextBranch _ t) = 1 + brListLength t -- lookup brListNth :: BranchList a br -> BranchIndex -> a brListNth (FirstBranch b) 0 = b brListNth (NextBranch h _) 0 = h brListNth (NextBranch _ t) n = brListNth t (n-1) brListNth _ _ = pprPanic "brListNth" empty -- map, fold brListMap :: (a -> b) -> BranchList a br -> [b] brListMap f (FirstBranch b) = [f b] brListMap f (NextBranch h t) = f h : (brListMap f t) brListFoldr :: (a -> b -> b) -> b -> BranchList a br -> b brListFoldr f x (FirstBranch b) = f b x brListFoldr f x (NextBranch h t) = f h (brListFoldr f x t) brListMapM :: Monad m => (a -> m b) -> BranchList a br -> m [b] brListMapM f (FirstBranch b) = f b >>= \fb -> return [fb] brListMapM f (NextBranch h t) = do { fh <- f h ; ft <- brListMapM f t ; return (fh : ft) } brListFoldlM_ :: forall a b m br. Monad m => (a -> b -> m a) -> a -> BranchList b br -> m () brListFoldlM_ f z brs = do { _ <- go z brs ; return () } where go :: forall br'. a -> BranchList b br' -> m a go acc (FirstBranch b) = f acc b go acc (NextBranch h t) = do { fh <- f acc h ; go fh t } -- zipWith brListZipWith :: (a -> b -> c) -> BranchList a br1 -> BranchList b br2 -> [c] brListZipWith f (FirstBranch a) (FirstBranch b) = [f a b] brListZipWith f (FirstBranch a) (NextBranch b _) = [f a b] brListZipWith f (NextBranch a _) (FirstBranch b) = [f a b] brListZipWith f (NextBranch a ta) (NextBranch b tb) = f a b : brListZipWith f ta tb -- pretty-printing instance Outputable a => Outputable (BranchList a br) where ppr = ppr . fromBranchList {- ************************************************************************ * * Coercion axioms * * ************************************************************************ Note [Storing compatibility] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ During axiom application, we need to be aware of which branches are compatible with which others. The full explanation is in Note [Compatibility] in FamInstEnv. (The code is placed there to avoid a dependency from CoAxiom on the unification algorithm.) Although we could theoretically compute compatibility on the fly, this is silly, so we store it in a CoAxiom. Specifically, each branch refers to all other branches with which it is incompatible. This list might well be empty, and it will always be for the first branch of any axiom. CoAxBranches that do not (yet) belong to a CoAxiom should have a panic thunk stored in cab_incomps. The incompatibilities are properly a property of the axiom as a whole, and they are computed only when the final axiom is built. During serialization, the list is converted into a list of the indices of the branches. -} -- | A 'CoAxiom' is a \"coercion constructor\", i.e. a named equality axiom. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data CoAxiom br = CoAxiom -- Type equality axiom. { co_ax_unique :: Unique -- unique identifier , co_ax_name :: Name -- name for pretty-printing , co_ax_role :: Role -- role of the axiom's equality , co_ax_tc :: TyCon -- the head of the LHS patterns , co_ax_branches :: BranchList CoAxBranch br -- the branches that form this axiom , co_ax_implicit :: Bool -- True <=> the axiom is "implicit" -- See Note [Implicit axioms] -- INVARIANT: co_ax_implicit == True implies length co_ax_branches == 1. } deriving Typeable data CoAxBranch = CoAxBranch { cab_loc :: SrcSpan -- Location of the defining equation -- See Note [CoAxiom locations] , cab_tvs :: [TyVar] -- Bound type variables; not necessarily fresh -- See Note [CoAxBranch type variables] , cab_roles :: [Role] -- See Note [CoAxBranch roles] , cab_lhs :: [Type] -- Type patterns to match against , cab_rhs :: Type -- Right-hand side of the equality , cab_incomps :: [CoAxBranch] -- The previous incompatible branches -- See Note [Storing compatibility] } deriving ( Data.Data, Data.Typeable ) toBranchedAxiom :: CoAxiom br -> CoAxiom Branched toBranchedAxiom (CoAxiom unique name role tc branches implicit) = CoAxiom unique name role tc (toBranchedList branches) implicit toUnbranchedAxiom :: CoAxiom br -> CoAxiom Unbranched toUnbranchedAxiom (CoAxiom unique name role tc branches implicit) = CoAxiom unique name role tc (toUnbranchedList branches) implicit coAxiomNumPats :: CoAxiom br -> Int coAxiomNumPats = length . coAxBranchLHS . (flip coAxiomNthBranch 0) coAxiomNthBranch :: CoAxiom br -> BranchIndex -> CoAxBranch coAxiomNthBranch (CoAxiom { co_ax_branches = bs }) index = brListNth bs index coAxiomArity :: CoAxiom br -> BranchIndex -> Arity coAxiomArity ax index = length $ cab_tvs $ coAxiomNthBranch ax index coAxiomName :: CoAxiom br -> Name coAxiomName = co_ax_name coAxiomRole :: CoAxiom br -> Role coAxiomRole = co_ax_role coAxiomBranches :: CoAxiom br -> BranchList CoAxBranch br coAxiomBranches = co_ax_branches coAxiomSingleBranch_maybe :: CoAxiom br -> Maybe CoAxBranch coAxiomSingleBranch_maybe (CoAxiom { co_ax_branches = branches }) | FirstBranch br <- branches = Just br | otherwise = Nothing coAxiomSingleBranch :: CoAxiom Unbranched -> CoAxBranch coAxiomSingleBranch (CoAxiom { co_ax_branches = FirstBranch br }) = br coAxiomTyCon :: CoAxiom br -> TyCon coAxiomTyCon = co_ax_tc coAxBranchTyVars :: CoAxBranch -> [TyVar] coAxBranchTyVars = cab_tvs coAxBranchLHS :: CoAxBranch -> [Type] coAxBranchLHS = cab_lhs coAxBranchRHS :: CoAxBranch -> Type coAxBranchRHS = cab_rhs coAxBranchRoles :: CoAxBranch -> [Role] coAxBranchRoles = cab_roles coAxBranchSpan :: CoAxBranch -> SrcSpan coAxBranchSpan = cab_loc isImplicitCoAxiom :: CoAxiom br -> Bool isImplicitCoAxiom = co_ax_implicit coAxBranchIncomps :: CoAxBranch -> [CoAxBranch] coAxBranchIncomps = cab_incomps -- See Note [Compatibility checking] in FamInstEnv placeHolderIncomps :: [CoAxBranch] placeHolderIncomps = panic "placeHolderIncomps" {- Note [CoAxBranch type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the case of a CoAxBranch of an associated type-family instance, we use the *same* type variables (where possible) as the enclosing class or instance. Consider class C a b where type F x b type F [y] b = ... -- Second param must be b instance C Int [z] where type F Int [z] = ... -- Second param must be [z] In the CoAxBranch in the instance decl (F Int [z]) we use the same 'z', so that it's easy to check that that type is the same as that in the instance header. Similarly in the CoAxBranch for the default decl for F in the class decl, we use the same 'b' to make the same check easy. So, unlike FamInsts, there is no expectation that the cab_tvs are fresh wrt each other, or any other CoAxBranch. Note [CoAxBranch roles] ~~~~~~~~~~~~~~~~~~~~~~~ Consider this code: newtype Age = MkAge Int newtype Wrap a = MkWrap a convert :: Wrap Age -> Int convert (MkWrap (MkAge i)) = i We want this to compile to: NTCo:Wrap :: forall a. Wrap a ~R a NTCo:Age :: Age ~R Int convert = \x -> x |> (NTCo:Wrap[0] NTCo:Age[0]) But, note that NTCo:Age is at role R. Thus, we need to be able to pass coercions at role R into axioms. However, we don't *always* want to be able to do this, as it would be disastrous with type families. The solution is to annotate the arguments to the axiom with roles, much like we annotate tycon tyvars. Where do these roles get set? Newtype axioms inherit their roles from the newtype tycon; family axioms are all at role N. Note [CoAxiom locations] ~~~~~~~~~~~~~~~~~~~~~~~~ The source location of a CoAxiom is stored in two places in the datatype tree. * The first is in the location info buried in the Name of the CoAxiom. This span includes all of the branches of a branched CoAxiom. * The second is in the cab_loc fields of the CoAxBranches. In the case of a single branch, we can extract the source location of the branch from the name of the CoAxiom. In other cases, we need an explicit SrcSpan to correctly store the location of the equation giving rise to the FamInstBranch. Note [Implicit axioms] ~~~~~~~~~~~~~~~~~~~~~~ See also Note [Implicit TyThings] in HscTypes * A CoAxiom arising from data/type family instances is not "implicit". That is, it has its own IfaceAxiom declaration in an interface file * The CoAxiom arising from a newtype declaration *is* "implicit". That is, it does not have its own IfaceAxiom declaration in an interface file; instead the CoAxiom is generated by type-checking the newtype declaration -} instance Eq (CoAxiom br) where a == b = case (a `compare` b) of { EQ -> True; _ -> False } a /= b = case (a `compare` b) of { EQ -> False; _ -> True } instance Ord (CoAxiom br) where a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False } a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False } a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True } a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True } compare a b = getUnique a `compare` getUnique b instance Uniquable (CoAxiom br) where getUnique = co_ax_unique instance Outputable (CoAxiom br) where ppr = ppr . getName instance NamedThing (CoAxiom br) where getName = co_ax_name instance Typeable br => Data.Data (CoAxiom br) where -- don't traverse? toConstr _ = abstractConstr "CoAxiom" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "CoAxiom" {- ************************************************************************ * * Roles * * ************************************************************************ Roles are defined here to avoid circular dependencies. -} -- See Note [Roles] in Coercion -- defined here to avoid cyclic dependency with Coercion data Role = Nominal | Representational | Phantom deriving (Eq, Data.Data, Data.Typeable) -- These names are slurped into the parser code. Changing these strings -- will change the **surface syntax** that GHC accepts! If you want to -- change only the pretty-printing, do some replumbing. See -- mkRoleAnnotDecl in RdrHsSyn fsFromRole :: Role -> FastString fsFromRole Nominal = fsLit "nominal" fsFromRole Representational = fsLit "representational" fsFromRole Phantom = fsLit "phantom" instance Outputable Role where ppr = ftext . fsFromRole instance Binary Role where put_ bh Nominal = putByte bh 1 put_ bh Representational = putByte bh 2 put_ bh Phantom = putByte bh 3 get bh = do tag <- getByte bh case tag of 1 -> return Nominal 2 -> return Representational 3 -> return Phantom _ -> panic ("get Role " ++ show tag) {- ************************************************************************ * * CoAxiomRule Rules for building Evidence * * ************************************************************************ Conditional axioms. The general idea is that a `CoAxiomRule` looks like this: forall as. (r1 ~ r2, s1 ~ s2) => t1 ~ t2 My intention is to reuse these for both (~) and (~#). The short-term plan is to use this datatype to represent the type-nat axioms. In the longer run, it may be good to unify this and `CoAxiom`, as `CoAxiom` is the special case when there are no assumptions. -} -- | A more explicit representation for `t1 ~ t2`. type Eqn = Pair Type -- | For now, we work only with nominal equality. data CoAxiomRule = CoAxiomRule { coaxrName :: FastString , coaxrTypeArity :: Int -- number of type argumentInts , coaxrAsmpRoles :: [Role] -- roles of parameter equations , coaxrRole :: Role -- role of resulting equation , coaxrProves :: [Type] -> [Eqn] -> Maybe Eqn -- ^ coaxrProves returns @Nothing@ when it doesn't like -- the supplied arguments. When this happens in a coercion -- that means that the coercion is ill-formed, and Core Lint -- checks for that. } deriving Typeable instance Data.Data CoAxiomRule where -- don't traverse? toConstr _ = abstractConstr "CoAxiomRule" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "CoAxiomRule" instance Uniquable CoAxiomRule where getUnique = getUnique . coaxrName instance Eq CoAxiomRule where x == y = coaxrName x == coaxrName y instance Ord CoAxiomRule where compare x y = compare (coaxrName x) (coaxrName y) instance Outputable CoAxiomRule where ppr = ppr . coaxrName -- Type checking of built-in families data BuiltInSynFamily = BuiltInSynFamily { sfMatchFam :: [Type] -> Maybe (CoAxiomRule, [Type], Type) , sfInteractTop :: [Type] -> Type -> [Eqn] , sfInteractInert :: [Type] -> Type -> [Type] -> Type -> [Eqn] } -- Provides default implementations that do nothing. trivialBuiltInFamily :: BuiltInSynFamily trivialBuiltInFamily = BuiltInSynFamily { sfMatchFam = \_ -> Nothing , sfInteractTop = \_ _ -> [] , sfInteractInert = \_ _ _ _ -> [] }
anton-dessiatov/ghc
compiler/types/CoAxiom.hs
bsd-3-clause
20,190
0
14
4,975
3,180
1,720
1,460
223
2
module Abs () where absN :: (Num a, Ord a) => a -> a absN x = if x > 0 then x else (-x) absI :: Int -> Int absI x = if x > 0 then x else (-x) --incI :: Int -> Int --incI = (+) 1 x0 = absN 4 x1 = absI (-5) --x2 = absI (incI 2) -- x3 = absI (-3)
mightymoose/liquidhaskell
tests/pos/Abs.hs
bsd-3-clause
254
0
7
78
115
66
49
7
2
-- -- Derived from a program believed to be originally written by John -- Launchbury, and incorporating the RSA algorithm which is in the -- public domain. -- import System.Environment import Data.List import qualified Data.ByteString.Lazy.Char8 as B import Data.ByteString.Lazy.Char8 (ByteString) import ByteStringCompat import Control.Monad.Par.Scheds.Trace import Stream main = do [f] <- getArgs text <- case f of "-" -> B.getContents _ -> B.readFile f B.putStr (pipeline n e d text) -- example keys, created by makeKey below n, d, e :: Integer (n,d,e) = (3539517541822645630044332546732747854710141643130106075585179940882036712515975698104695392573887034788933523673604280427152984392565826058380509963039612419361429882234327760449752708861159361414595229,121492527803044541056704751360974487724009957507650761043424679483464778334890045929773805597614290949,216244483337223224019000724904989828660716358310562600433314577442746058361727768326718965949745599136958260211917551718034992348233259083876505235987999070191048638795502931877693189179113255689722281) -- <<encrypt encrypt :: Integer -> Integer -> Stream ByteString -> Par (Stream ByteString) encrypt n e s = streamMap (B.pack . show . power e n . code) s decrypt :: Integer -> Integer -> Stream ByteString -> Par (Stream ByteString) decrypt n d s = streamMap (B.pack . decode . power d n . integer) s -- >> integer :: ByteString -> Integer integer b | Just (i,_) <- B.readInteger b = i -- <<pipeline pipeline :: Integer -> Integer -> Integer -> ByteString -> ByteString pipeline n e d b = runPar $ do s0 <- streamFromList (chunk (size n) b) s1 <- encrypt n e s0 s2 <- decrypt n d s1 xs <- streamFold (\x y -> (y : x)) [] s2 return (B.unlines (reverse xs)) -- >> integers :: [ByteString] -> [Integer] integers bs = [ i | Just (i,_) <- map B.readInteger bs ] -------- Converting between Strings and Integers ----------- code :: ByteString -> Integer code = B.foldl' accum 0 where accum x y = (128 * x) + fromIntegral (fromEnum y) decode :: Integer -> String decode n = reverse (expand n) where expand 0 = [] expand x = toEnum (fromIntegral (x `mod` 128)) : expand (x `div` 128) chunk :: Int -> ByteString -> [ByteString] chunk n xs | B.null xs = [] chunk n xs = as : chunk n bs where (as,bs) = B.splitAt (fromIntegral n) xs size :: Integer -> Int size n = (length (show n) * 47) `div` 100 -- log_128 10 = 0.4745 ------- Constructing keys ------------------------- makeKeys :: Integer -> Integer -> (Integer, Integer, Integer) makeKeys r s = (p*q, d, invert ((p-1)*(q-1)) d) where p = nextPrime r q = nextPrime s d = nextPrime (p+q+1) nextPrime :: Integer -> Integer nextPrime a = head (filter prime [odd,odd+2..]) where odd | even a = a+1 | True = a prime p = and [power (p-1) p x == 1 | x <- [3,5,7]] invert :: Integer -> Integer -> Integer invert n a = if e<0 then e+n else e where e=iter n 0 a 1 iter :: Integer -> Integer -> Integer -> Integer -> Integer iter g v 0 w = v iter g v h w = iter h w (g `mod` h) (v - (g `div` h)*w) ------- Fast exponentiation, mod m ----------------- power :: Integer -> Integer -> Integer -> Integer power 0 m x = 1 power n m x | even n = sqr (power (n `div` 2) m x) `mod` m | True = (x * power (n-1) m x) `mod` m sqr :: Integer -> Integer sqr x = x * x
y-kamiya/parallel-concurrent-haskell
src/RsaPipeSample/rsa-pipeline.hs
gpl-2.0
3,403
1
13
684
1,289
676
613
65
2
module Blank where {-@ LIQUID "--no-termination" @-} data Vec a = V (Int -> a) {-@ data Vec a < dom :: Int -> Prop, rng :: Int -> a -> Prop > = V {a :: i:Int<dom> -> a <rng i>} @-} {-@ empty :: forall <p :: Int -> a -> Prop>. Vec <{v:Int|0=1}, p> a @-} empty = V $ \_ -> error "empty vector!" {-@ set :: forall a <d :: Int -> Prop, r :: Int -> a -> Prop>. key: Int<d> -> val: a<r key> -> vec: Vec<{v:Int<d>| v /= key},r> a -> Vec <d, r> a @-} set key val (V f) = V $ \k -> if k == key then val else f k {- loop :: forall a <p :: Int -> a -> Prop>. lo:Int -> hi:{Int | lo <= hi} -> base:a<p lo> -> f:(i:Int -> a<p i> -> a<p (i+1)>) -> a<p hi> @-} -- loop :: Int -> Int -> a -> (Int -> a -> a) -> a -- loop lo hi base f = go lo base -- where -- go i acc -- | i < hi = go (i+1) (f i acc) -- | otherwise = acc {-@ loop :: forall a <p :: Int -> a -> Prop>. lo:Nat -> hi:{Nat | lo <= hi} -> base:Vec <{v:Nat | (v < lo)}, p> a -> f:(i:Nat -> Vec <{v:Nat | v < i}, p> a -> Vec <{v:Nat | v < i+1}, p> a) -> Vec <{v:Nat | v < hi}, p> a @-} loop :: Int -> Int -> Vec a -> (Int -> Vec a -> Vec a) -> Vec a loop lo hi base f = go lo base where go i acc | i < hi = go (i+1) (f i acc) | otherwise = acc {-@ predicate Seg V I J = (I <= V && V < J) @-} {-@ type IdVec N = Vec <{\v -> (Seg v 0 N)}, {\k v -> v=k}> Int @-} {-@ initUpto :: n:Nat -> (IdVec n) @-} initUpto n = loop 0 n empty (\i acc -> set i i acc) {-@ qualif Foo(v:Int): v < 0 @-}
mightymoose/liquidhaskell
tests/pos/vecloop.hs
bsd-3-clause
1,844
0
12
787
244
131
113
12
2
-- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- {-# OPTIONS_GHC -fno-warn-orphans #-} module Thrift.Types where import Data.ByteString.Lazy (ByteString) import Data.Foldable (foldl') import Data.Hashable ( Hashable, hashWithSalt ) import Data.Int import Test.QuickCheck.Arbitrary import Test.QuickCheck.Gen (elements) import Data.Text.Lazy (Text) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector instance (Hashable k, Hashable v) => Hashable (Map.HashMap k v) where hashWithSalt salt = foldl' hashWithSalt salt . Map.toList instance (Hashable a) => Hashable (Set.HashSet a) where hashWithSalt = foldl' hashWithSalt instance (Hashable a) => Hashable (Vector.Vector a) where hashWithSalt = Vector.foldl' hashWithSalt -- | Map from field key to field id and type in a Thrift Struct type TypeMap = Map.HashMap Text (Int16, ThriftType) -- | Definition of a generic Thrift value. This is the internal represention -- inside the Thrift library. The client sees the autogenerated record type and -- the Thrift Compiler generates code to convert between the record type and the -- more generic 'ThriftVal' data ThriftVal = TStruct (Map.HashMap Int16 (Text, ThriftVal)) | TMap ThriftType ThriftType [(ThriftVal, ThriftVal)] | TList ThriftType [ThriftVal] | TSet ThriftType [ThriftVal] | TBool Bool | TByte Int8 -- ^ 'TByte' is a signed integer for compatibility with other -- languages | TI16 Int16 | TI32 Int32 | TI64 Int64 | TString ByteString -- ^ 8-bit characters are sufficient since that is what other -- languages use | TFloat Float | TDouble Double deriving (Eq, Show) -- | Type information is needed for collection types (ie 'T_STRUCT', 'T_MAP', -- 'T_LIST', and 'T_SET') so that we know what types those collections are -- parameterized by. In most protocols, this cannot be discerned directly -- from the data being read. data ThriftType = T_STOP | T_VOID | T_BOOL | T_BYTE | T_DOUBLE | T_I16 | T_I32 | T_I64 | T_STRING | T_STRUCT TypeMap | T_MAP ThriftType ThriftType | T_SET ThriftType | T_LIST ThriftType | T_FLOAT deriving ( Eq, Show ) -- | NOTE: when using toEnum information about parametized types is NOT -- preserved. This design choice is consistent with the Thrift implementation -- in other languages instance Enum ThriftType where fromEnum T_STOP = 0 fromEnum T_VOID = 1 fromEnum T_BOOL = 2 fromEnum T_BYTE = 3 fromEnum T_DOUBLE = 4 fromEnum T_I16 = 6 fromEnum T_I32 = 8 fromEnum T_I64 = 10 fromEnum T_STRING = 11 fromEnum (T_STRUCT _) = 12 fromEnum (T_MAP _ _) = 13 fromEnum (T_SET _) = 14 fromEnum (T_LIST _) = 15 fromEnum T_FLOAT = 19 toEnum 0 = T_STOP toEnum 1 = T_VOID toEnum 2 = T_BOOL toEnum 3 = T_BYTE toEnum 4 = T_DOUBLE toEnum 6 = T_I16 toEnum 8 = T_I32 toEnum 10 = T_I64 toEnum 11 = T_STRING toEnum 12 = T_STRUCT Map.empty toEnum 13 = T_MAP T_VOID T_VOID toEnum 14 = T_SET T_VOID toEnum 15 = T_LIST T_VOID toEnum 19 = T_FLOAT toEnum t = error $ "Invalid ThriftType " ++ show t data MessageType = M_CALL | M_REPLY | M_EXCEPTION deriving ( Eq, Show ) instance Enum MessageType where fromEnum M_CALL = 1 fromEnum M_REPLY = 2 fromEnum M_EXCEPTION = 3 toEnum 1 = M_CALL toEnum 2 = M_REPLY toEnum 3 = M_EXCEPTION toEnum t = error $ "Invalid MessageType " ++ show t instance Arbitrary MessageType where arbitrary = elements [M_CALL, M_REPLY, M_EXCEPTION]
guker/fbthrift
thrift/lib/hs/Thrift/Types.hs
apache-2.0
4,679
0
9
1,252
869
488
381
93
0
module Cmm.X86.InstrCore where import Cmm.LabelGenerator import Data.Int import Text.Printf -- | bypassing non exisiting module system of haskell data X86CodeGen = X86CodeGen data SizeDirective = BYTE | WORD | DWORD | QWORD -- 64 bit won't be supported for the time being deriving (Eq, Ord) instance Show SizeDirective where show BYTE = "BYTE" show WORD = "WORD" show DWORD = "DWORD PTR" show QWORD = "QWORD PTR" data UnaryInstr = PUSH | POP | NEG | NOT | INC | DEC | IDIV deriving (Eq, Ord) instance Show UnaryInstr where show PUSH = "push" show POP = "pop" show NEG = "neg" show NOT = "not" show INC = "inc" show DEC = "dec" show IDIV = "idiv" data BinayInstr = MOV | ADD | SUB | SHL | SHR | SAL | SAR | AND | OR | XOR | TEST | CMP | LEA | IMUL deriving (Eq, Ord) instance Show BinayInstr where show MOV = "mov" show ADD = "add" show SUB = "sub" show SHL = "shl" show SAL = "sal" show SAR = "sar" show AND = "and" show OR = "or" show XOR = "xor" show TEST = "test" show CMP = "cmp" show LEA = "lea" show IMUL = "imul" data Cond = E | NE | L | LE | G | GE | Z deriving (Eq, Ord) -- used with 'j' prefix instance Show Cond where show E = "e" show NE = "ne" show L = "l" show LE = "le" show G = "g" show GE = "ge" show Z = "z" data Scale = S2 | S4 | S8 -- possible scaling values for effective addressing deriving (Eq, Ord, Show) scaleToInt :: Scale -> Int32 scaleToInt S2 = 2 scaleToInt S4 = 4 scaleToInt S8 = 8 data EffectiveAddress = EffectiveAddress { base :: Maybe Temp , indexScale :: Maybe (Temp, Scale) , displacement :: Int32 } deriving (Eq, Ord) data Operand = Imm Int32 | Reg Temp | Mem EffectiveAddress deriving (Eq, Ord) data X86Instr = Unary UnaryInstr (Maybe SizeDirective, Operand) | Binary BinayInstr (Maybe SizeDirective, Operand) (Maybe SizeDirective, Operand) | LABEL Label | CDQ | JMP Label | J Cond Label | CALL Label | RET | NOP deriving (Eq, Ord) data X86Comment = X86Comment String deriving (Eq, Ord) comment :: String -> X86Comment comment = X86Comment emptyComment :: X86Comment emptyComment = comment "" instance Show X86Comment where show (X86Comment c) = "# " ++ c data X86Func = X86Func { x86functionName :: String , x86body :: [X86Instr] , x86comments :: [X86Comment] , x86spilledCount :: Int32 } deriving (Eq, Ord) data X86Prog = X86Prog { x86functions :: [X86Func] } deriving (Eq, Ord) instance Show X86Prog where show p = concat ["\t.intel_syntax noprefix\n\t", ".global Lmain\n"] ++ concatMap (\x -> show x ++ "\n") (x86functions p) instance Show X86Func where show f = x86functionName f ++ ":\n\t" ++ concatMap (\x -> x ++ "\n\t") body where body :: [String] body = zipWith (\x c -> printf "%-35s %s" (show x) (show c)) (x86body f) (x86comments f) instance Show X86Instr where show (Unary u (s,o)) = show u ++ maybe "" (\x -> ' ' : show x) s ++ ' ' : show o show (Binary b (s1, o1) (s2, o2)) = show b ++ maybe "" (\x -> ' ' : show x) s1 ++ ' ' : show o1 ++ ", "++ maybe "" (\x -> ' ' : show x) s2 ++ ' ' : show o2 show (LABEL l) = l ++ ":" show RET = "ret" show CDQ = "cdq" show (JMP l) = "jmp " ++ l show (J cond l) = "j" ++ show cond ++ " " ++ l show (CALL l) = "call " ++ l show NOP = "" instance Show Operand where show (Reg t) = show t show (Imm i32) = show i32 show (Mem ea) = show ea instance Show EffectiveAddress where show ea = let c = show (displacement ea) in case (base ea, indexScale ea) of (Just bt, Just (t, s)) -> "[" ++ show bt ++ " + " ++ show t ++ "*" ++ show s ++ " + " ++ c ++ "]" (_, Just (t, s)) -> "[" ++ show t ++ "*" ++ show s ++ " + " ++ c ++ "]" (Just bt, _) -> case displacement ea of 0 -> "[" ++ show bt ++ "]" _ -> "[" ++ show bt ++ " + " ++ c ++ "]" (_, _) -> "[" ++ c ++ "]" -- | Registers -- -- base pointer (register) ebp :: Operand ebp = Reg ebpT ebpT :: Temp ebpT = mkNamedTemp "%ebp" -- stack pointer (register) esp :: Operand esp = Reg espT espT :: Temp espT = mkNamedTemp "%esp" -- return register eax :: Operand eax = Reg eaxT eaxT :: Temp eaxT = mkNamedTemp "%eax" ebx :: Operand ebx = Reg ebxT ebxT :: Temp ebxT = mkNamedTemp "%ebx" -- math register (used for mathematic expressions) ecx :: Operand ecx = Reg ecxT ecxT :: Temp ecxT = mkNamedTemp "%ecx" -- used to move the first argument to edx if not already a register edx :: Operand edx = Reg edxT edxT :: Temp edxT = mkNamedTemp "%edx" edi :: Operand edi = Reg ediT ediT :: Temp ediT = mkNamedTemp "%edi" esi :: Operand esi = Reg esiT esiT :: Temp esiT = mkNamedTemp "%esi"
cirquit/hjc
src/Cmm/X86/InstrCore.hs
mit
5,446
0
19
1,949
1,829
975
854
182
1
-- Part 1 module Session4.Recursion (test) where import Prelude ((+), (*), Bool(..), Double, IO, Int, return) -- | empty a.k.a. null -- Examples: -- >>> empty [] -- True -- >>> empty [1, 2, 3, 4] -- False empty :: [a] -> Bool empty [] = True empty _ = False -- | map -- Examples: -- >>> map (+100) [] -- [] -- >>> map (+100) [1, 2, 3, 4] -- [101,102,103,104] map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x : xs) = f x : map f xs -- | len a.k.a. length -- Examples: -- >>> len [] -- 0 -- >>> len [1, 2, 3, 4] -- 4 len :: [a] -> Int len [] = 0 len (_ : xs) = 1 + len xs -- | sum -- Examples: -- >>> sum [] -- 0 -- >>> sum [1, 2, 3, 4] -- 10 sum :: [Int] -> Int sum [] = 0 sum (x : xs) = (+) x (sum xs) -- | product -- Examples: -- >>> product [] -- 1.0 -- >>> product [1, 2, 3, 4] -- 24.0 product :: [Double] -> Double product [] = 1 product (x : xs) = (*) x (product xs) -- | foldr -- Examples: -- >>> foldr (+) 0 [1, 2, 3, 4] -- 10 -- >>> foldr (*) 1 [1, 2, 3, 4] -- 24 foldr :: (a -> b -> b) -> b -> [a] -> b foldr _ z [] = z foldr f z (x : xs) = f x (foldr f z xs) test :: IO () test = do let _ = foldr (+) (0 :: Int) [1, 2, 3, 4] _ = empty ([1, 2, 3, 4] :: [Int]) _ = len ([1, 2, 3, 4] :: [Int]) _ = map (+100) [] :: [Int] _ = sum [1, 2, 3, 4] _ = product [1, 2, 3, 4] return ()
seahug/pcph-scratch
src/Session4/Recursion.hs
mit
1,346
2
12
392
589
343
246
29
1
module Latte.FrontEnd.Spec (main, spec) where import Test.Hspec import qualified Latte.FrontEnd.MainFunctionPresenceSpec import qualified Latte.FrontEnd.FunctionNameDuplicationSpec import qualified Latte.FrontEnd.TypeCheckSpec import qualified Latte.FrontEnd.VariableDeclaredSpec main :: IO () main = hspec spec spec :: Spec spec = do describe "Main function presence" Latte.FrontEnd.MainFunctionPresenceSpec.spec describe "Function name duplication" Latte.FrontEnd.FunctionNameDuplicationSpec.spec describe "Type check" Latte.FrontEnd.TypeCheckSpec.spec describe "Are variables/names declared" Latte.FrontEnd.VariableDeclaredSpec.spec
mpsk2/LatteCompiler
testsuite/tests/Latte/FrontEnd/Spec.hs
mit
657
0
8
73
124
72
52
14
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} module Database.Persist.Sql.Types ( module Database.Persist.Sql.Types , SqlBackend (..), SqlReadBackend (..), SqlWriteBackend (..) , Statement (..), LogFunc, InsertSqlResult (..) , readToUnknown, readToWrite, writeToUnknown , SqlBackendCanRead, SqlBackendCanWrite, SqlReadT, SqlWriteT, IsSqlBackend ) where import Control.Exception (Exception) import Control.Monad.Trans.Resource (ResourceT) import Data.Acquire (Acquire) import Control.Monad.Logger (NoLoggingT) import Control.Monad.IO.Class (MonadIO (..)) import Control.Monad.Trans.Reader (ReaderT (..)) import Control.Monad.Trans.Writer (WriterT) import Data.Typeable (Typeable) import Database.Persist.Types import Database.Persist.Sql.Types.Internal import Data.IORef (IORef) import Data.Map (Map) import Data.Int (Int64) import Data.Conduit (Source) import Data.Pool (Pool) import Language.Haskell.TH.Syntax (Loc) import Control.Monad.Logger (LogSource, LogLevel) import System.Log.FastLogger (LogStr) import Data.Text (Text) -- | Deprecated synonym for @SqlBackend@. type Connection = SqlBackend {-# DEPRECATED Connection "Please use SqlBackend instead" #-} data Column = Column { cName :: !DBName , cNull :: !Bool , cSqlType :: !SqlType , cDefault :: !(Maybe Text) , cDefaultConstraintName :: !(Maybe DBName) , cMaxLen :: !(Maybe Integer) , cReference :: !(Maybe (DBName, DBName)) -- table name, constraint name } deriving (Eq, Ord, Show) data PersistentSqlException = StatementAlreadyFinalized Text | Couldn'tGetSQLConnection deriving (Typeable, Show) instance Exception PersistentSqlException type SqlPersistT = ReaderT SqlBackend type SqlPersist = SqlPersistT {-# DEPRECATED SqlPersist "Please use SqlPersistT instead" #-} type SqlPersistM = SqlPersistT (NoLoggingT (ResourceT IO)) type Sql = Text -- Bool indicates if the Sql is safe type CautiousMigration = [(Bool, Sql)] type Migration = WriterT [Text] (WriterT CautiousMigration (ReaderT SqlBackend IO)) () type ConnectionPool = Pool SqlBackend -- $rawSql -- -- Although it covers most of the useful cases, @persistent@'s -- API may not be enough for some of your tasks. May be you need -- some complex @JOIN@ query, or a database-specific command -- needs to be issued. -- -- To issue raw SQL queries, use 'rawSql'. It does all the hard work of -- automatically parsing the rows of the result. It may return: -- -- * An 'Entity', that which 'selectList' returns. -- All of your entity's fields are -- automatically parsed. -- -- * A @'Single' a@, which is a single, raw column of type @a@. -- You may use a Haskell type (such as in your entity -- definitions), for example @Single Text@ or @Single Int@, -- or you may get the raw column value with @Single -- 'PersistValue'@. -- -- * A tuple combining any of these (including other tuples). -- Using tuples allows you to return many entities in one -- query. -- -- The only difference between issuing SQL queries with 'rawSql' -- and using other means is that we have an /entity selection/ -- /placeholder/, the double question mark @??@. It /must/ be -- used whenever you want to @SELECT@ an 'Entity' from your -- query. Here's a sample SQL query @sampleStmt@ that may be -- issued: -- -- @ -- SELECT ??, ?? -- FROM \"Person\", \"Likes\", \"Object\" -- WHERE \"Person\".id = \"Likes\".\"personId\" -- AND \"Object\".id = \"Likes\".\"objectId\" -- AND \"Person\".name LIKE ? -- @ -- -- To use that query, you could say -- -- @ -- do results <- 'rawSql' sampleStmt [\"%Luke%\"] -- forM_ results $ -- \\( Entity personKey person -- , Entity objectKey object -- ) -> do ... -- @ -- -- Note that 'rawSql' knows how to replace the double question -- marks @??@ because of the type of the @results@. -- | A single column (see 'rawSql'). Any 'PersistField' may be -- used here, including 'PersistValue' (which does not do any -- processing). newtype Single a = Single {unSingle :: a} deriving (Eq, Ord, Show, Read)
pseudonom/persistent
persistent/Database/Persist/Sql/Types.hs
mit
4,437
0
12
805
630
413
217
75
0
module Glucose.Codegen.JavaScript (codegen) where import Control.Comonad import Control.Lens import Control.Monad.RWS import Data.Foldable (toList) import Data.Set as Set (Set, fromList, empty, insert, delete, member) import Data.Text (Text, pack, unpack) import Glucose.Identifier import Glucose.IR data JSRaw = JSRaw Text instance Show JSRaw where show (JSRaw s) = unpack s type Codegen = RWS () Text (Set Identifier, Set Identifier) execCodegen :: Set Identifier -> Codegen a -> JSRaw execCodegen vars m = JSRaw . snd $ evalRWS m () (empty, vars) codegen :: Module Checked -> JSRaw codegen (Module defs) = execCodegen vars $ mapAttemptM_ attemptToDefine (map extract defs) where vars = Set.fromList $ map identifier (toList defs) attemptToDefine def = maybe (pure False) ((True <$) . tell) =<< definition def mapAttemptM_ :: Monad m => (a -> m Bool) -> [a] -> m () mapAttemptM_ _ [] = pure () mapAttemptM_ f as = deleteWhen f as >>= mapAttemptM_ f deleteWhen :: Monad m => (a -> m Bool) -> [a] -> m [a] deleteWhen _ [] = pure [] deleteWhen f as = go as where go [] = error "Recursive aliases in codegen?" go (a:as) = do shouldDelete <- f a if shouldDelete then pure as else (a:) <$> go as definition :: Definition Checked -> Codegen (Maybe Text) definition (Definition (extract -> Identifier name) (extract -> Reference Global (Identifier target) _)) = do targetUndefined <- uses _2 (Set.member $ Identifier target) if targetUndefined then pure Nothing else do _2 %= delete (Identifier name) pure . Just $ name <> " = " <> target <> "\n" definition (Definition (extract -> Identifier name) def) = do _2 %= delete (Identifier name) expr <- expression (extract def) pure . Just $ name <> " = " <> expr <> "\n" expression :: Expression Checked -> Codegen Text expression (Literal a) = pure . pack $ show a expression (Reference _ (Identifier a) _) = pure a expression (Constructor (extract -> typeName) _) = do typeDefined <- uses _1 (Set.member typeName) unless typeDefined $ do _1 %= Set.insert typeName tell $ typeDefinition typeName pure $ "new " <> identify typeName <> "()" typeDefinition :: Identifier -> Text typeDefinition (Identifier typeName) = typeName <> " = function() {}\n"
sardonicpresence/glucose
src/Glucose/Codegen/Javascript.hs
mit
2,323
0
14
500
934
466
468
-1
-1
-- (Ready for) Prime Time -- http://www.codewars.com/kata/521ef596c106a935c0000519/ module PrimeTime where prime :: Int -> [Int] prime n = takeWhile (<= n) . sieve $ [2..] where sieve (n:ns) = n : sieve [n' | n' <- ns, n' `mod` n /= 0]
gafiatulin/codewars
src/5 kyu/PrimeTime.hs
mit
242
0
12
48
93
52
41
4
1
import Data.Aeson import Test.Tasty import Test.Tasty.QuickCheck as QC import Pulmurice.Common.Message main :: IO () main = defaultMain qcProps requestMessageProp :: ReqMsg -> Property requestMessageProp msg = Just msg === decode (encode msg) responseMessageProp :: ResMsg -> Property responseMessageProp msg = Just msg === decode (encode msg) qcProps :: TestTree qcProps = testGroup "QuickCheck properties" [ QC.testProperty "ReqMsg: decode . encode = id" requestMessageProp , QC.testProperty "ResMsg: decode . encode = id" responseMessageProp ]
futurice/pulmurice-common
tests/Tests.hs
mit
558
0
8
84
144
75
69
14
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.EventSource (js_newEventSource, newEventSource, js_close, close, pattern CONNECTING, pattern OPEN, pattern CLOSED, js_getUrl, getUrl, js_getWithCredentials, getWithCredentials, js_getReadyState, getReadyState, open, message, error, EventSource, castToEventSource, gTypeEventSource) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "new window[\"EventSource\"]($1,\n$2)" js_newEventSource :: JSString -> JSRef Dictionary -> IO (JSRef EventSource) -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource Mozilla EventSource documentation> newEventSource :: (MonadIO m, ToJSString url, IsDictionary eventSourceInit) => url -> Maybe eventSourceInit -> m EventSource newEventSource url eventSourceInit = liftIO (js_newEventSource (toJSString url) (maybe jsNull (unDictionary . toDictionary) eventSourceInit) >>= fromJSRefUnchecked) foreign import javascript unsafe "$1[\"close\"]()" js_close :: JSRef EventSource -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.close Mozilla EventSource.close documentation> close :: (MonadIO m) => EventSource -> m () close self = liftIO (js_close (unEventSource self)) pattern CONNECTING = 0 pattern OPEN = 1 pattern CLOSED = 2 foreign import javascript unsafe "$1[\"url\"]" js_getUrl :: JSRef EventSource -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.url Mozilla EventSource.url documentation> getUrl :: (MonadIO m, FromJSString result) => EventSource -> m result getUrl self = liftIO (fromJSString <$> (js_getUrl (unEventSource self))) foreign import javascript unsafe "($1[\"withCredentials\"] ? 1 : 0)" js_getWithCredentials :: JSRef EventSource -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.withCredentials Mozilla EventSource.withCredentials documentation> getWithCredentials :: (MonadIO m) => EventSource -> m Bool getWithCredentials self = liftIO (js_getWithCredentials (unEventSource self)) foreign import javascript unsafe "$1[\"readyState\"]" js_getReadyState :: JSRef EventSource -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.readyState Mozilla EventSource.readyState documentation> getReadyState :: (MonadIO m) => EventSource -> m Word getReadyState self = liftIO (js_getReadyState (unEventSource self)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onopen Mozilla EventSource.onopen documentation> open :: EventName EventSource Event open = unsafeEventName (toJSString "open") -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onmessage Mozilla EventSource.onmessage documentation> message :: EventName EventSource MessageEvent message = unsafeEventName (toJSString "message") -- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onerror Mozilla EventSource.onerror documentation> error :: EventName EventSource UIEvent error = unsafeEventName (toJSString "error")
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/EventSource.hs
mit
3,934
32
12
554
851
486
365
61
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} import qualified Data.ByteString.Lazy as L import Data.ByteString.Builder import Database.Redis import Control.Monad.IO.Class (liftIO) import System.IO import Data.Monoid((<>)) import Data.Foldable import Data.List import qualified Text.ProtocolBuffers.Basic as P import qualified Text.ProtocolBuffers.TextMessage as P import qualified Text.ProtocolBuffers.WireMessage as P import Text.ProtocolBuffers (defaultValue) import Data.Test.Foo as Foo import Data.Test.Bar as Bar import Control.Concurrent import Control.Concurrent.Async connInfo :: ConnectInfo connInfo = defaultConnectInfo { connectPort = UnixSocket "/tmp/redis.sock" } renderString :: String -> Builder renderString cs = charUtf8 '"' <> foldMap escape cs <> charUtf8 '"' where escape '\\' = charUtf8 '\\' <> charUtf8 '\\' escape '\"' = charUtf8 '\\' <> charUtf8 '\"' escape c = charUtf8 c -- getData :: IO L.ByteString -- getData = do -- h <- openFile "data.txt" ReadMode -- r <- L.hGetContents h -- return r pub :: Connection -> IO () pub conn = runRedis conn $ do let b = defaultValue { Bar.wine = P.uFromString "Bubble", Bar.good = Just True } let bs = P.messagePut b r <- publish "testchan" (L.toStrict bs) liftIO $ putStrLn ("Sent: " ++ show r) liftIO $ threadDelay 1500000 publish "testchan" "quit" liftIO $ threadDelay 100000 main = do conn <- connect connInfo a1 <- async $ pub conn wait a1 -- return ()
hnfmr/test-hedis
src/Pub.hs
mit
1,503
0
14
263
419
226
193
38
3
-- Copyright (c) 2016-present, SoundCloud Ltd. -- All rights reserved. -- -- This source code is distributed under the terms of a MIT license, -- found in the LICENSE file. {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} module Kubernetes.Model.V1.GCEPersistentDiskVolumeSource ( GCEPersistentDiskVolumeSource (..) , pdName , fsType , partition , readOnly , mkGCEPersistentDiskVolumeSource ) where import Control.Lens.TH (makeLenses) import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier) import Data.Text (Text) import GHC.Generics (Generic) import Prelude hiding (drop, error, max, min) import qualified Prelude as P import Test.QuickCheck (Arbitrary, arbitrary) import Test.QuickCheck.Instances () -- | Represents a Persistent Disk resource in Google Compute Engine.\n\nA GCE PD must exist and be formatted before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once. GCE PDs support ownership management and SELinux relabeling. data GCEPersistentDiskVolumeSource = GCEPersistentDiskVolumeSource { _pdName :: !(Text) , _fsType :: !(Text) , _partition :: !(Maybe Integer) , _readOnly :: !(Maybe Bool) } deriving (Show, Eq, Generic) makeLenses ''GCEPersistentDiskVolumeSource $(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''GCEPersistentDiskVolumeSource) instance Arbitrary GCEPersistentDiskVolumeSource where arbitrary = GCEPersistentDiskVolumeSource <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- | Use this method to build a GCEPersistentDiskVolumeSource mkGCEPersistentDiskVolumeSource :: Text -> Text -> GCEPersistentDiskVolumeSource mkGCEPersistentDiskVolumeSource xpdNamex xfsTypex = GCEPersistentDiskVolumeSource xpdNamex xfsTypex Nothing Nothing
soundcloud/haskell-kubernetes
lib/Kubernetes/Model/V1/GCEPersistentDiskVolumeSource.hs
mit
2,193
0
14
535
324
192
132
39
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Tests.Sodium.Stream.Common where import Tests.Sodium.Common () import Crypto.Sodium.SecureMem import Crypto.Sodium.Stream.Internal import Data.Bits import qualified Data.ByteString as B import Data.Maybe import Test.QuickCheck.Monadic as QM import Test.Tasty import Test.Tasty.QuickCheck mkTests :: forall t. StreamCipher t -> [TestTree] mkTests StreamCipher {..} = [ testProperty "encrypt decrypt" prop_EncryptDecrypt , testProperty "stream xor" prop_StreamXor , testProperty "mkKey" prop_mkKey , testProperty "mkNonce" prop_mkNonce , testProperty "randomKey" prop_randomKey ] where arbitraryKey :: Gen (Key t) arbitraryKey = fromJust . mkKey . fromByteString . B.pack <$> vector keyBytes arbitraryNonce :: Gen (Nonce t) arbitraryNonce = fromJust . mkNonce . B.pack <$> vector nonceBytes prop_EncryptDecrypt m = forAll arbitraryKey $ \k -> forAll arbitraryNonce $ \n -> m == streamXor k n (streamXor k n m) prop_StreamXor m = forAll arbitraryKey $ \k -> forAll arbitraryNonce $ \n -> streamXor k n m == B.pack (B.zipWith xor m $ stream k n $ B.length m) prop_mkKey = forAll arbitraryKey $ \k -> k == fromJust (mkKey $ unKey k) prop_mkNonce = forAll arbitraryNonce $ \n -> n == fromJust (mkNonce $ unNonce n) prop_randomKey = monadicIO $ do k <- run randomKey n <- pick arbitraryNonce m <- pick arbitrary QM.assert $ m == streamXor k n (streamXor k n m)
dnaq/crypto-sodium
test/Tests/Sodium/Stream/Common.hs
mit
1,783
0
17
562
487
252
235
43
1
-- | -- Module : Data.Edison.Seq.BankersQueue -- Copyright : Copyright (c) 1998-1999, 2008 Chris Okasaki -- License : MIT; see COPYRIGHT file for terms and conditions -- -- Maintainer : robdockins AT fastmail DOT fm -- Stability : stable -- Portability : GHC, Hugs (MPTC and FD) -- -- This module implements Banker's Queues. It has the standard running -- times from "Data.Edison.Seq" except for the following: -- -- * rcons, size, inBounds @O( 1 )@ -- -- /References:/ -- -- * Chris Okasaki, /Purely Functional Data Structures/, -- 1998, sections 6.3.2 and 8.4.1. -- -- * Chris Okasaki, \"Simple and efficient purely functional -- queues and deques\", /Journal of Function Programming/ -- 5(4):583-592, October 1995. module Data.Edison.Seq.BankersQueue ( -- * Sequence Type Seq, -- instance of Sequence, Functor, Monad, MonadPlus -- * Sequence operations empty,singleton,lcons,rcons,append,lview,lhead,ltail,rview,rhead,rtail, lheadM,ltailM,rheadM,rtailM, null,size,concat,reverse,reverseOnto,fromList,toList,map,concatMap, fold,fold',fold1,fold1',foldr,foldr',foldl,foldl',foldr1,foldr1',foldl1,foldl1', reducer,reducer',reducel,reducel',reduce1,reduce1', copy,inBounds,lookup,lookupM,lookupWithDefault,update,adjust, mapWithIndex,foldrWithIndex,foldrWithIndex',foldlWithIndex,foldlWithIndex', take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile, zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3, strict, strictWith, -- * Unit testing structuralInvariant, -- * Documentation moduleName ) where import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1, filter,takeWhile,dropWhile,lookup,take,drop,splitAt, zip,zip3,zipWith,zipWith3,unzip,unzip3,null) import qualified Control.Applicative as App import qualified Data.Edison.Seq as S ( Sequence(..) ) import Data.Edison.Seq.Defaults import qualified Data.Edison.Seq.ListSeq as L import Data.Monoid import Data.Semigroup as SG import Control.Monad.Identity import Test.QuickCheck -- signatures for exported functions moduleName :: String empty :: Seq a singleton :: a -> Seq a lcons :: a -> Seq a -> Seq a rcons :: a -> Seq a -> Seq a append :: Seq a -> Seq a -> Seq a lview :: (Monad m) => Seq a -> m (a, Seq a) lhead :: Seq a -> a lheadM :: (Monad m) => Seq a -> m a ltail :: Seq a -> Seq a ltailM :: (Monad m) => Seq a -> m (Seq a) rview :: (Monad m) => Seq a -> m (a, Seq a) rhead :: Seq a -> a rheadM :: (Monad m) => Seq a -> m a rtail :: Seq a -> Seq a rtailM :: (Monad m) => Seq a -> m (Seq a) null :: Seq a -> Bool size :: Seq a -> Int concat :: Seq (Seq a) -> Seq a reverse :: Seq a -> Seq a reverseOnto :: Seq a -> Seq a -> Seq a fromList :: [a] -> Seq a toList :: Seq a -> [a] map :: (a -> b) -> Seq a -> Seq b concatMap :: (a -> Seq b) -> Seq a -> Seq b fold :: (a -> b -> b) -> b -> Seq a -> b fold' :: (a -> b -> b) -> b -> Seq a -> b fold1 :: (a -> a -> a) -> Seq a -> a fold1' :: (a -> a -> a) -> Seq a -> a foldr :: (a -> b -> b) -> b -> Seq a -> b foldl :: (b -> a -> b) -> b -> Seq a -> b foldr1 :: (a -> a -> a) -> Seq a -> a foldl1 :: (a -> a -> a) -> Seq a -> a reducer :: (a -> a -> a) -> a -> Seq a -> a reducel :: (a -> a -> a) -> a -> Seq a -> a reduce1 :: (a -> a -> a) -> Seq a -> a foldr' :: (a -> b -> b) -> b -> Seq a -> b foldl' :: (b -> a -> b) -> b -> Seq a -> b foldr1' :: (a -> a -> a) -> Seq a -> a foldl1' :: (a -> a -> a) -> Seq a -> a reducer' :: (a -> a -> a) -> a -> Seq a -> a reducel' :: (a -> a -> a) -> a -> Seq a -> a reduce1' :: (a -> a -> a) -> Seq a -> a copy :: Int -> a -> Seq a inBounds :: Int -> Seq a -> Bool lookup :: Int -> Seq a -> a lookupM :: (Monad m) => Int -> Seq a -> m a lookupWithDefault :: a -> Int -> Seq a -> a update :: Int -> a -> Seq a -> Seq a adjust :: (a -> a) -> Int -> Seq a -> Seq a mapWithIndex :: (Int -> a -> b) -> Seq a -> Seq b foldrWithIndex :: (Int -> a -> b -> b) -> b -> Seq a -> b foldlWithIndex :: (b -> Int -> a -> b) -> b -> Seq a -> b foldrWithIndex' :: (Int -> a -> b -> b) -> b -> Seq a -> b foldlWithIndex' :: (b -> Int -> a -> b) -> b -> Seq a -> b take :: Int -> Seq a -> Seq a drop :: Int -> Seq a -> Seq a splitAt :: Int -> Seq a -> (Seq a, Seq a) subseq :: Int -> Int -> Seq a -> Seq a filter :: (a -> Bool) -> Seq a -> Seq a partition :: (a -> Bool) -> Seq a -> (Seq a, Seq a) takeWhile :: (a -> Bool) -> Seq a -> Seq a dropWhile :: (a -> Bool) -> Seq a -> Seq a splitWhile :: (a -> Bool) -> Seq a -> (Seq a, Seq a) zip :: Seq a -> Seq b -> Seq (a,b) zip3 :: Seq a -> Seq b -> Seq c -> Seq (a,b,c) zipWith :: (a -> b -> c) -> Seq a -> Seq b -> Seq c zipWith3 :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d unzip :: Seq (a,b) -> (Seq a, Seq b) unzip3 :: Seq (a,b,c) -> (Seq a, Seq b, Seq c) unzipWith :: (a -> b) -> (a -> c) -> Seq a -> (Seq b, Seq c) unzipWith3 :: (a -> b) -> (a -> c) -> (a -> d) -> Seq a -> (Seq b, Seq c, Seq d) strict :: Seq a -> Seq a strictWith :: (a -> b) -> Seq a -> Seq a structuralInvariant :: Seq a -> Bool moduleName = "Data.Edison.Seq.BankersQueue" data Seq a = Q !Int [a] [a] !Int -- invariant: front at least as long as rear structuralInvariant (Q x f r y) = length f == x && length r == y && x >= y -- not exported makeQ :: Int -> [a] -> [a] -> Int -> Seq a makeQ i xs ys j | j > i = Q (i + j) (xs ++ L.reverse ys) [] 0 | otherwise = Q i xs ys j empty = Q 0 [] [] 0 singleton x = Q 1 [x] [] 0 lcons x (Q i xs ys j) = Q (i+1) (x:xs) ys j rcons y (Q i xs ys j) = makeQ i xs (y:ys) (j+1) append (Q i1 xs1 ys1 j1) (Q i2 xs2 ys2 j2) = Q (i1 + j1 + i2) (xs1 ++ L.reverseOnto ys1 xs2) ys2 j2 lview (Q _ [] _ _) = fail "BankersQueue.lview: empty sequence" lview (Q i (x:xs) ys j) = return (x, makeQ (i-1) xs ys j) lhead (Q _ [] _ _) = error "BankersQueue.lhead: empty sequence" lhead (Q _ (x:_) _ _) = x lheadM (Q _ [] _ _) = fail "BankersQueue.lheadM: empty sequence" lheadM (Q _ (x:_) _ _) = return x ltail (Q i (_:xs) ys j) = makeQ (i-1) xs ys j ltail _ = error "BankersQueue.ltail: empty sequence" ltailM (Q i (_:xs) ys j) = return (makeQ (i-1) xs ys j) ltailM _ = fail "BankersQueue.ltail: empty sequence" rview (Q i xs (y:ys) j) = return (y, Q i xs ys (j-1)) rview (Q i xs [] _) = case L.rview xs of Nothing -> fail "BankersQueue.rview: empty sequence" Just (x,xs') -> return (x, Q (i-1) xs' [] 0) rhead (Q _ _ (y:_) _) = y rhead (Q _ [] [] _) = error "BankersQueue.rhead: empty sequence" rhead (Q _ xs [] _) = L.rhead xs rheadM (Q _ _ (y:_) _) = return y rheadM (Q _ [] [] _) = fail "BankersQueue.rheadM: empty sequence" rheadM (Q _ xs [] _) = return (L.rhead xs) rtail (Q i xs (_:ys) j) = Q i xs ys (j-1) rtail (Q _ [] [] _) = error "BankersQueue.rtail: empty sequence" rtail (Q i xs [] _) = Q (i-1) (L.rtail xs) [] 0 rtailM (Q i xs (_:ys) j) = return (Q i xs ys (j-1)) rtailM (Q _ [] [] _) = fail "BankersQueue.rtailM: empty sequence" rtailM (Q i xs [] _) = return (Q (i-1) (L.rtail xs) [] 0) null (Q i _ _ _) = (i == 0) size (Q i _ _ j) = i + j reverse (Q i xs ys j) = makeQ j ys xs i reverseOnto (Q i1 xs1 ys1 j1) (Q i2 xs2 ys2 j2) = Q (i1 + j1 + i2) (ys1 ++ L.reverseOnto xs1 xs2) ys2 j2 fromList xs = Q (length xs) xs [] 0 toList (Q _ xs ys j) | j == 0 = xs | otherwise = xs ++ L.reverse ys map f (Q i xs ys j) = Q i (L.map f xs) (L.map f ys) j -- local fn on lists revfoldr :: (t -> t1 -> t1) -> t1 -> [t] -> t1 revfoldr _ e [] = e revfoldr f e (x:xs) = revfoldr f (f x e) xs revfoldr' :: (t -> a -> a) -> a -> [t] -> a revfoldr' _ e [] = e revfoldr' f e (x:xs) = e `seq` revfoldr' f (f x e) xs -- local fn on lists revfoldl :: (t -> t1 -> t) -> t -> [t1] -> t revfoldl _ e [] = e revfoldl f e (x:xs) = f (revfoldl f e xs) x revfoldl' :: (b -> t -> b) -> b -> [t] -> b revfoldl' _ e [] = e revfoldl' f e (x:xs) = (\z -> f z x) $! (revfoldl f e xs) fold f e (Q _ xs ys _) = L.foldr f (L.foldr f e ys) xs fold' f e (Q _ xs ys _) = (L.foldl' (flip f) $! (L.foldl' (flip f) e ys)) xs fold1 = fold1UsingFold fold1' = fold1'UsingFold' foldr f e (Q _ xs ys _) = L.foldr f (revfoldr f e ys) xs foldr' f e (Q _ xs ys _) = L.foldr' f (revfoldr' f e ys) xs foldl f e (Q _ xs ys _) = revfoldl f (L.foldl f e xs) ys foldl' f e (Q _ xs ys _) = revfoldl' f (L.foldl' f e xs) ys foldr1 f (Q _ xs (y:ys) _) = L.foldr f (revfoldr f y ys) xs foldr1 f (Q i xs [] _) | i == 0 = error "BankersQueue.foldr1: empty sequence" | otherwise = L.foldr1 f xs foldr1' f (Q _ xs (y:ys) _) = L.foldr' f (revfoldr' f y ys) xs foldr1' f (Q i xs [] _) | i == 0 = error "BankersQueue.foldr1': empty sequence" | otherwise = L.foldr1' f xs foldl1 f (Q _ (x:xs) ys _) = revfoldl f (L.foldl f x xs) ys foldl1 _ _ = error "BankersQueue.foldl1: empty sequence" foldl1' f (Q _ (x:xs) ys _) = revfoldl' f (L.foldl' f x xs) ys foldl1' _ _ = error "BankersQueue.foldl1': empty sequence" copy n x | n < 0 = empty | otherwise = Q n (L.copy n x) [] 0 -- reduce1: given sizes could do more effective job of dividing evenly! lookup idx q = runIdentity (lookupM idx q) lookupM idx (Q i xs ys j) | idx < i = L.lookupM idx xs | otherwise = L.lookupM (j - (idx - i) - 1) ys lookupWithDefault d idx (Q i xs ys j) | idx < i = L.lookupWithDefault d idx xs | otherwise = L.lookupWithDefault d (j - (idx - i) - 1) ys update idx e q@(Q i xs ys j) | idx < i = if idx < 0 then q else Q i (L.update idx e xs) ys j | otherwise = let k' = j - (idx - i) - 1 in if k' < 0 then q else Q i xs (L.update k' e ys) j adjust f idx q@(Q i xs ys j) | idx < i = if idx < 0 then q else Q i (L.adjust f idx xs) ys j | otherwise = let k' = j - (idx - i) - 1 in if k' < 0 then q else Q i xs (L.adjust f k' ys) j {- could do mapWithIndex :: (Int -> a -> b) -> s a -> s b foldrWithIndex :: (Int -> a -> b -> b) -> b -> s a -> b foldlWithIndex :: (b -> Int -> a -> b) -> b -> s a -> b but don't bother for now -} take len q@(Q i xs ys j) = if len <= i then if len <= 0 then empty else Q len (L.take len xs) [] 0 else let len' = len - i in if len' >= j then q else Q i xs (L.drop (j - len') ys) len' drop len q@(Q i xs ys j) = if len <= i then if len <= 0 then q else makeQ (i - len) (L.drop len xs) ys j else let len' = len - i in if len' >= j then empty else Q (j - len') (L.reverse (L.take (j - len') ys)) [] 0 -- could write more efficient version of reverse (take ...) splitAt idx q@(Q i xs ys j) = if idx <= i then if idx <= 0 then (empty, q) else let (xs',xs'') = L.splitAt idx xs in (Q idx xs' [] 0, makeQ (i - idx) xs'' ys j) else let idx' = idx - i in if idx' >= j then (q, empty) else let (ys', ys'') = L.splitAt (j - idx') ys in (Q i xs ys'' idx', Q (j - idx') (L.reverse ys') [] 0) -- could do splitAt followed by reverse more efficiently... strict l@(Q _ xs ys _) = L.strict xs `seq` L.strict ys `seq` l strictWith f l@(Q _ xs ys _) = L.strictWith f xs `seq` L.strictWith f ys `seq` l -- the remaining functions all use defaults concat = concatUsingFoldr concatMap = concatMapUsingFoldr reducer = reducerUsingReduce1 reducel = reducelUsingReduce1 reduce1 = reduce1UsingLists reducer' = reducer'UsingReduce1' reducel' = reducel'UsingReduce1' reduce1' = reduce1'UsingLists inBounds = inBoundsUsingSize mapWithIndex = mapWithIndexUsingLists foldrWithIndex = foldrWithIndexUsingLists foldrWithIndex' = foldrWithIndex'UsingLists foldlWithIndex = foldlWithIndexUsingLists foldlWithIndex' = foldlWithIndex'UsingLists subseq = subseqDefault filter = filterUsingLists partition = partitionUsingLists takeWhile = takeWhileUsingLview dropWhile = dropWhileUsingLview splitWhile = splitWhileUsingLview zip = zipUsingLists zip3 = zip3UsingLists zipWith = zipWithUsingLists zipWith3 = zipWith3UsingLists unzip = unzipUsingLists unzip3 = unzip3UsingLists unzipWith = unzipWithUsingLists unzipWith3 = unzipWith3UsingLists -- instances instance S.Sequence Seq where {lcons = lcons; rcons = rcons; lview = lview; lhead = lhead; ltail = ltail; lheadM = lheadM; ltailM = ltailM; rheadM = rheadM; rtailM = rtailM; rview = rview; rhead = rhead; rtail = rtail; null = null; size = size; concat = concat; reverse = reverse; reverseOnto = reverseOnto; fromList = fromList; toList = toList; fold = fold; fold' = fold'; fold1 = fold1; fold1' = fold1'; foldr = foldr; foldr' = foldr'; foldl = foldl; foldl' = foldl'; foldr1 = foldr1; foldr1' = foldr1'; foldl1 = foldl1; foldl1' = foldl1'; reducer = reducer; reducer' = reducer'; reducel = reducel; reducel' = reducel'; reduce1 = reduce1; reduce1' = reduce1'; copy = copy; inBounds = inBounds; lookup = lookup; lookupM = lookupM; lookupWithDefault = lookupWithDefault; update = update; adjust = adjust; mapWithIndex = mapWithIndex; foldrWithIndex = foldrWithIndex; foldlWithIndex = foldlWithIndex; foldrWithIndex' = foldrWithIndex'; foldlWithIndex' = foldlWithIndex'; take = take; drop = drop; splitAt = splitAt; subseq = subseq; filter = filter; partition = partition; takeWhile = takeWhile; dropWhile = dropWhile; splitWhile = splitWhile; zip = zip; zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip; unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3; strict = strict; strictWith = strictWith; structuralInvariant = structuralInvariant; instanceName _ = moduleName} instance Functor Seq where fmap = map instance App.Alternative Seq where empty = empty (<|>) = append instance App.Applicative Seq where pure = return x <*> y = do x' <- x y' <- y return (x' y') instance Monad Seq where return = singleton xs >>= k = concatMap k xs instance MonadPlus Seq where mplus = append mzero = empty instance Eq a => Eq (Seq a) where q1 == q2 = (size q1 == size q2) && (toList q1 == toList q2) instance Ord a => Ord (Seq a) where compare = defaultCompare instance Show a => Show (Seq a) where showsPrec = showsPrecUsingToList instance Read a => Read (Seq a) where readsPrec = readsPrecUsingFromList instance Arbitrary a => Arbitrary (Seq a) where arbitrary = do xs <- arbitrary ys <- arbitrary return (let i = L.size xs j = L.size ys in if i >= j then Q i xs ys j else Q j ys xs i) instance CoArbitrary a => CoArbitrary (Seq a) where coarbitrary (Q _ xs ys _) = coarbitrary xs . coarbitrary ys instance Semigroup (Seq a) where (<>) = append instance Monoid (Seq a) where mempty = empty mappend = (SG.<>)
robdockins/edison
edison-core/src/Data/Edison/Seq/BankersQueue.hs
mit
15,242
0
15
4,142
6,939
3,653
3,286
326
4
module HJS.Parser.ParserMonad where import Control.Monad.Identity import Control.Monad.Error import Control.Monad.State import HJS.Parser.Lexer data ParseResult a = Ok a | Failed String deriving Show data LexerMode = Normal | InComment | InRegex deriving Show data LexerState = LS { rest::String,lineno::Int,mode::LexerMode,tr:: [String], nl:: Bool, rest2 :: String, expectRegex :: Bool, lastToken::(Maybe Token)} deriving Show startState str = LS { rest=str, lineno=1, mode =Normal, tr=[], nl = False, rest2 = "", expectRegex = False,lastToken=Nothing} type P = StateT LexerState (ErrorT String Identity) getLineNo :: P Int getLineNo = do s <- get return $ lineno s putLineNo :: Int -> P () putLineNo l = do s <- get put s { lineno = l } trace :: String -> P () trace ts = do s <- get put s { tr = ts : (tr s) } ifM a b c = do case a of True -> b False -> c
nbrunt/JSHOP
res/hjs-0.1/src/HJS/Parser/ParserMonad.hs
mit
1,053
3
12
344
374
211
163
27
2
import Data.List import Data.Ord data Graph a = Graph [a] [(a, a)] deriving (Show, Eq) data Adjacency a = Adj [(a, [a])] deriving (Show, Eq) data Friendly a = Edge [(a, a)] deriving (Show, Eq) -- Problem 80 -- Conversions -- graphToAdj, adjToGraph, graphToFri, friToGraph, adjToFri, friToAdj graphToAdj :: Eq a => Graph a -> Adjacency a graphToAdj (Graph [] _) = Adj [] graphToAdj (Graph (x:xs) edges) = Adj ((x, connectedWithX):remainingAdjacencies) where f (a, b) = if a == x then [b] else if b == x then [a] else [] connectedWithX = concatMap f edges Adj remainingAdjacencies = graphToAdj (Graph xs edges) adjToGraph :: Eq a => Adjacency a -> Graph a adjToGraph (Adj []) = Graph [] [] adjToGraph (Adj ((x, ys):rest)) = Graph (x:xs) (edgesWithX ++ remainingEdges) where Graph xs remainingEdges = adjToGraph (Adj rest) f y = if elem (x, y) remainingEdges || elem (y, x) remainingEdges then [] else [(x, y)] edgesWithX = concatMap f ys graphToFri :: Eq a => Graph a -> Friendly a graphToFri (Graph xs edges) = Edge (edges ++ lonelies) where lonelies = [(x, x)| x <- xs, not (x `elem` (map fst edges) || x `elem` (map snd edges))] friToGraph :: Eq a => Friendly a -> Graph a friToGraph (Edge []) = Graph [] [] friToGraph (Edge ((x, y):rest)) = Graph nodes edges where Graph remainingNodes remainingEdges = friToGraph (Edge rest) nodesWithX = if x `elem` remainingNodes then remainingNodes else (x:remainingNodes) nodes = if y `elem` nodesWithX then nodesWithX else (y:nodesWithX) edges = if x == y then remainingEdges else (x,y):remainingEdges adjToFri :: Eq a => Adjacency a -> Friendly a adjToFri = graphToFri . adjToGraph friToAdj :: Eq a => Friendly a -> Adjacency a friToAdj = graphToAdj . friToGraph -- Problem 81 -- paths -- Paths from one node to another one paths :: Eq a => a -> a -> [(a, a)] -> [[a]] paths x y zs = _paths [y] x zs where _paths ys@(y:_) x zs = if x == y then [ys] else concatMap f zs where f (x1, y1) = if y1 == y && not (x1 `elem` ys) then _paths (x1:ys) x zs else [] -- Problem 82 -- cycle -- Cycle from a given node cycle :: Eq a => a -> [(a, a)] -> [[a]] cycle x es = _cycle [x] es where _cycle xs es = concatMap f es where last = xs !! (length xs - 1) first = xs !! 0 f (x, y) = if x == last && y == first then [xs ++ [y]] else if x == last && not (y `elem` xs) then _cycle (xs ++ [y]) es else [] -- Problem 83 -- spantrees -- Construct all spanning trees spantrees :: (Eq a, Ord a) => Graph a -> [Graph a] spantrees (Graph [] _) = [] spantrees (Graph [x] _) = [Graph [x] []] spantrees (Graph xs es) = nubBy (\(Graph _ es1) (Graph _ es2) -> sort es1 == sort es2) $ concat [concatMap (f x) (gs x) | x <- xs] where without x (a, b) = a /= x && b /= x gs x = spantrees (Graph (filter (/= x) xs) (filter (without x) es)) f v (Graph vs es2) = [Graph (v:vs) (e2:es2) | e2<-es, not (without v e2)] k4 = Graph ['a', 'b', 'c', 'd'] [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('a', 'c'), ('b', 'd')] -- Problem 84 -- prim -- Construct the minimum spanning tree prim :: (Eq a, Ord b) => [a] -> [(a, a, b)] -> [(a, a, b)] prim [] _ = [] prim xs@(x:_) es = prim' xs es [x] where contains x (a, b, _) = x == a || x == b prim' xs es seen = if length seen == length xs then [] else (nextEdge: prim' xs es (seen ++ [next])) where trd (_,_,w) = w xor a b = (a || b) && (not (a && b)) f (a, b, _) = (a `elem` seen) `xor` (b `elem` seen) possibs = filter f es nextEdge = minimumBy (comparing trd) possibs g (a, b, _) = if a `elem` seen then b else a next = g nextEdge -- Problem 85 -- iso -- Graph isomorphism iso :: (Eq a, Ord a, Eq b, Ord b) => Graph a -> Graph b -> Bool iso g1 g2 = any (\f -> graphEqual (f g1) g2) (makeMappings g1 g2) where matching [] x = error "No matching element found" matching ((a,b):ys) x = if a == x then b else matching ys x g mapping (Graph xs es) = Graph (map (matching mapping) xs) [(matching mapping a, matching mapping b) | (a,b)<-es] makeMappings (Graph xs1 _) (Graph xs2 _) = if length xs1 /= length xs2 then [] else [g (zip perm xs2) | perm <- permutations xs1] graphEqual (Graph xs1 es1) (Graph xs2 es2) = sort xs1 == sort xs2 && sort es1 == sort es2 -- Problem 86 -- degree, sortedDegrees, kcolor -- Write a function that determines the degree of a given node. -- Write a function that generates a list of all nodes of a graph -- sorted according to decreasing degree. -- Use Welch-Powell's algorithm to paint the nodes of a graph in such -- a way that adjacent nodes have different colors. degree :: Eq a => Graph a -> a -> Int degree (Graph _ es) x = length $ filter (\(a, b) -> x == a || x == b) es sortedDegrees :: Eq a => Graph a -> [a] sortedDegrees g@(Graph xs es) = reverse $ sortBy (comparing (degree g)) xs kcolor :: (Eq a, Ord a) => Graph a -> [(a, Int)] kcolor g = kcolor' adj 1 [] where adj = sortByDegrees g sortByDegrees g = sortBy (comparing (length . snd)) adj' where Adj adj' = graphToAdj g kcolor' [] _ acc = acc kcolor' xs n acc = kcolor' newxs (n+1) acc' where newxs = [x | x <- xs, notElem (fst x, n) acc'] acc' = color xs n acc color [] _ acc = acc color ((v,e):xs) n acc = if any (\x -> (x, n) `elem` acc) e then color xs n acc else color xs n ((v, n):acc) -- Problem 87 -- depthfirst -- Depth first order graph traversal (alternative solution) depthfirst :: Eq a => Graph a -> a -> [a] depthfirst g x = reverse $ search g x [] where search (Graph xs _) _ seen | length seen == length xs = seen search (Graph xs es) x seen = foldl' combine (x:seen) next where combine sofar node = if notElem node sofar then search g node sofar else sofar next = [y | y <- xs, y `notElem` seen && ((x, y) `elem` es || (y, x) `elem` es)] -- Problem 88 -- connectedComponents -- Write a function that splits a graph into its connected components connectedComponents :: Eq a => Graph a -> [[a]] connectedComponents (Graph [] _) = [] connectedComponents g@(Graph xs@(x:_) es) = connectedToX : rest where connectedToX = depthfirst g x rest = connectedComponents (Graph (xs \\ connectedToX) es) -- Problem 89 -- bipartite -- Write a function that finds out if the given graph is bipartite bipartite :: (Eq a, Ord a) => Graph a -> Bool bipartite g = length (nub (map snd (kcolor g))) == 2
CrazyMerlyn/99problems-haskell
80-89.hs
mit
7,593
0
16
2,688
3,082
1,648
1,434
102
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Netpoll.Database where import qualified Data.Foldable as Foldable import qualified Data.List as List import qualified Data.Maybe as Maybe import qualified Data.Monoid as Monoid import qualified Data.Word as Word import qualified Database.PostgreSQL.Simple as Postgres import qualified Database.PostgreSQL.Simple.FromRow as FromRow import qualified Database.PostgreSQL.Simple.FromField as FromField import qualified Netpoll.Poller as Poller infixr 4 <> (<>) :: Monoid.Monoid m => m -> m -> m (<>) = Monoid.mappend {- -- Object names below 32 chars just in case we ever want to port to oracle. -- In practice this means table names are 28 chars or less. -- schema: create role netpoll login password 'netpoll' creatdb; create database netpoll with owner = netpoll encoding = 'UTF8'; ------------- -- Scheduler ------------- create table schedule ( interval int not null , constraint schedule_pk primary key (interval) ); create table sched_slot ( interval int not null , slot int not null , constraint sched_slot_pk primary key (interval, slot) , constraint sched_slot_ck1 check (slot >= 0 and slot < interval) , constraint sched_slot_fk1 foreign key (interval) references schedule (interval) ); create table sched_request ( request_id text not null , address text not null , auth_token text not null , routing_token text not null , poller_type text not null , interval int not null , timeout int not null , retries int not null , constraint sched_request_pk primary key (request_id) ); -- ensures that a request can only go in one slot create table sched_request_slot ( request_id text not null , interval int not null , slot int not null , constraint sched_request_slot_pk primary key (request_id, interval, slot) , constraint sched_request_slot_fk1 foreign key (request_id) references sched_request (request_id) , constraint sched_request_slot_fk2 foreign key (interval, slot) references sched_slot (interval, slot) ); -- list of dataseries (measurements) for a given request create table sched_request_measure ( request_id text not null , dataseries_id int not null , calculator text not null , constraint sched_request_measure_pk primary key (request_id, dataseries_id) , constraint sched_request_measure_fk1 foreign key (request_id) references sched_request (request_id) ); -- list of oids for a given measurement create table sched_request_measure_val ( request_id text not null , dataseries_id int not null , position int not null , value text not null , constraint sched_request_measure_val_pk primary key (request_id, dataseries_id) , constraint sched_request_measure_val_fk1 foreign key (request_id, dataseries_id) references sched_request_measure (request_id, dataseries_id) ); ------------- -- Datastore ------------- Partitions: - highres: by day - 15min/hourly: by month - daily: not at all The table structures: - highres: dataseries_id :: int ts :: timestamp value :: double valid_ind :: int - lowres: dataseries_id :: int start_ts :: timestamp end_ts :: timestamp cnt :: int avg :: double sum :: double max :: double min :: double stddev :: double Tables could be called: - measure_highres - measure_15min - measure_hourly - measure_daily create table measure_highres ( dataseries_id int not null , ts timestamp with time zone not null , value double not null , valid_ind int not null , constraint measure_highres_pk primary key (dataseries_id, ts) ); create index measure_highres_ts_ix1 on measure_highres(ts); create table measure_15min ( dataseries_id int not null , start_ts timestamp with time zone not null , end_ts timestamp with time zone not null , cnt int not null , avg double not null , sum double not null , min double not null , max double not null , stddev double not null , constraint measure_15min_pk primary key (dataseries_id, ts) ); create index measure_15min_start_ts on measure_15min(start_ts); create table measure_highres_20150101 inherits measure_highres check (ts >= to_timestamp('2015-01-01', 'yyyy-mm-dd') and ts < to_timestamp('2015-01-02', 'yyyy-mm-dd') ) ; create table measure_15min_201501 inherits measure_15min check (start_ts >= to_timestamp('2015-01-01', 'yyyy-mm-dd') and start_ts < to_timestamp('2015-01-02', 'yyyy-mm-dd') ) ; -} getSchedules :: Postgres.Connection -> IO [Word.Word16] getSchedules conn = do let stmt = "select interval from schedule order by interval" is <- Postgres.query_ conn stmt return (map fromIntegral (List.concat is::[Int])) type SlotRequests = (Word.Word16, [Poller.PollRequest]) -- For a given interval, return the slots and all of the requests -- in each slot. getRequestsForInterval :: Postgres.Connection -> Word.Word16 -> IO [SlotRequests] getRequestsForInterval conn interval = do let stmt = "select " <> " ss.slot " <> ", sr.request_id " <> ", srm.dataseries_id " <> ", srm.calculator " <> ", srmv.position " <> ", srmv.value " <> ", sr.address " <> ", sr.auth_token " <> ", sr.routing_token " <> ", sr.poller_type " <> ", sr.interval " <> ", sr.timeout " <> ", sr.retries " <> "from sched_slot ss " <> "join sched_request_slot srs on 1=1 " <> " and srs.interval = ss.interval " <> " and srs.slot = ss.slot " <> "join sched_request sr on 1=1 " <> " and sr.request_id = srs.request_id " <> "join sched_request_measure srm on 1=1 " <> " and srm.request_id = sr.request_id " <> "join sched_request_measure_val srmv on 1=1 " <> " and srmv.request_id = srm.request_id " <> " and srmv.dataseries_id = srm.dataseries_id " <> "where ss.interval = ? " <> "order by 1 desc, 2 desc, 3 desc, 5 desc " let initial = ([], (-1, [])) :: ([SlotRequests], SlotRequests) (results, last) <- Postgres.fold conn stmt [interval] initial processRequests return (last:results) type ReqQueryTuple = ( Int -- slot , String -- req-id , Int -- ds-id , String -- calculator , Int -- position , String -- value , String -- address , String -- auth-token , String -- routing-token , String -- poller-type , Int -- interval , Int -- timeout , Int -- retries ) -- add FromRow instances for 11-13 columns instance ( FromField.FromField a, FromField.FromField b, FromField.FromField c , FromField.FromField d, FromField.FromField e, FromField.FromField f , FromField.FromField g, FromField.FromField h, FromField.FromField i , FromField.FromField j, FromField.FromField k ) => FromRow.FromRow (a,b,c,d,e,f,g,h,i,j,k) where fromRow = (,,,,,,,,,,) <$> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field instance ( FromField.FromField a, FromField.FromField b, FromField.FromField c , FromField.FromField d, FromField.FromField e, FromField.FromField f , FromField.FromField g, FromField.FromField h, FromField.FromField i , FromField.FromField j, FromField.FromField k, FromField.FromField l ) => FromRow.FromRow (a,b,c,d,e,f,g,h,i,j,k,l) where fromRow = (,,,,,,,,,,,) <$> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field instance ( FromField.FromField a, FromField.FromField b, FromField.FromField c , FromField.FromField d, FromField.FromField e, FromField.FromField f , FromField.FromField g, FromField.FromField h, FromField.FromField i , FromField.FromField j, FromField.FromField k, FromField.FromField l , FromField.FromField m ) => FromRow.FromRow (a,b,c,d,e,f,g,h,i,j,k,l,m) where fromRow = (,,,,,,,,,,,,) <$> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field <*> FromRow.field -- prev holds what's been built of the current SlotRequests so far. -- 1. If the current slot differs from the previous then push the -- previous SlotRequests onto the list and make a new one. -- -- 2. If the current request-id differs from the previous then make -- a new PollRequest and prefix it to the list in prev. -- -- 3. If the current dataseries-id differs from previous then make -- a new tuple and prefix it to the measurements list. -- -- 4. Finally, it's just another value, so prefix it to the value list. processRequests :: ([SlotRequests], SlotRequests) -> ReqQueryTuple -> IO ([SlotRequests], SlotRequests) processRequests (results, prevSr@(prevSlot, prevReqs)) row = do let slot = getSlot row let prevRequestId = if List.null prevReqs then Nothing else (Just (Poller.requestId (head prevReqs))) let prevDataseriesId :: Maybe Int prevDataseriesId = if List.null prevReqs then Nothing else let rms = Poller.requestMeasurements (head prevReqs) in if List.null rms then Nothing else (Just ((\(d,_,_) -> d) (head rms))) case () of -- first row _ | prevSlot == -1 -> return ([], makeSlotRequest row) -- 1. change of slot - the only time we accumulate to the results list | slot /= prevSlot -> return (prevSr:results, makeSlotRequest row) -- 2. change of request-id | getRequestId row /= Maybe.fromJust prevRequestId -> do let (_, [pr]) = makeSlotRequest row return (results, (prevSlot, pr:prevReqs)) -- 3. change of dataseries-id | getDataseriesId row /= Maybe.fromJust prevDataseriesId -> do let m = makeMeasurement row -- prefix new measure to list in first request. -- This means building a new request to replace it. let (r1:rs) = prevReqs let ms = Poller.requestMeasurements r1 let r2 = r1 { Poller.requestMeasurements = m:ms } return (results, (prevSlot, r2:rs)) -- 4. another value | otherwise -> do -- prefix new value to list in first measurement. -- This means recreating the first measurement and -- the first request. let (_,_,[v]) = makeMeasurement row let (r1:rs) = prevReqs let (m1:ms) = Poller.requestMeasurements r1 let (dsId, calc, vals) = m1 let m2 = (dsId, calc, v:vals) let r2 = r1 { Poller.requestMeasurements = m2:ms } return (results, (prevSlot, r2:rs)) getSlot :: ReqQueryTuple -> Word.Word16 getSlot (a,b,c,d,e,f,g,h,i,j,k,l,m) = fromIntegral a getRequestId :: ReqQueryTuple -> String getRequestId (a,b,c,d,e,f,g,h,i,j,k,l,m) = b getDataseriesId :: ReqQueryTuple -> Int getDataseriesId (a,b,c,d,e,f,g,h,i,j,k,l,m) = c makeSlotRequest :: ReqQueryTuple -> SlotRequests makeSlotRequest row@ ( rowSlot , rowReqId , rowDsId , rowCalc , rowPos , rowVal , rowAddr , rowAuth , rowRoute , rowPoller , rowInterval , rowTimeout , rowRetries ) = let pr = Poller.PollRequest { Poller.requestId = rowReqId , Poller.requestAddress = rowAddr , Poller.requestAuthToken = rowAuth , Poller.requestRoutingToken = rowRoute , Poller.requestPollerType = rowPoller , Poller.requestInterval = fromIntegral rowInterval , Poller.requestIntervalRange = (0, fromIntegral rowInterval - 1) , Poller.requestTimeout = fromIntegral rowTimeout , Poller.requestRetries = fromIntegral rowRetries , Poller.requestNextTimeout = 0 , Poller.requestMeasurements = [makeMeasurement row] } in (fromIntegral rowSlot, [pr]) makeMeasurement :: ReqQueryTuple -> (Int, String, [String]) makeMeasurement ( rowSlot , rowReqId , rowDsId , rowCalc , rowPos , rowVal , rowAddr , rowAuth , rowRoute , rowPoller , rowInterval , rowTimeout , rowRetries ) = (rowDsId, rowCalc, [rowVal]) createSchedule :: Postgres.Connection -> Word.Word16 -> IO () createSchedule conn interval = do Postgres.begin conn let stmt = "insert into schedule (interval) values (?)" _ <- Postgres.execute conn stmt [interval] let stmt = "insert into sched_slot (interval, slot) values (?, ?)" let bindvals = [(interval, s) | s <- [0..(interval - 1)]] _ <- Postgres.executeMany conn stmt bindvals Postgres.commit conn addRequestToSchedule :: Postgres.Connection -> Word.Word16 -> Word.Word16 -> Poller.PollRequest -> IO () addRequestToSchedule conn interval slot req = do let reqId = Poller.requestId req Postgres.begin conn let stmt = "insert into sched_request " <> "(request_id, address, auth_token, routing_token," <> " poller_type, interval, timeout, retries)" <> " values (?, ?, ?, ?, ?, ?, ?, ?)" let bindvals = ( Poller.requestId req , Poller.requestAddress req , Poller.requestAuthToken req , Poller.requestRoutingToken req , Poller.requestPollerType req , Poller.requestInterval req , Poller.requestTimeout req , Poller.requestRetries req ) _ <- Postgres.execute conn stmt bindvals let stmt = "insert into sched_request_measure " <> "(request_id, dataseries_id, calculator) " <> "values (?, ?, ?)" let stmt2 = "insert into sched_request_measure_val " <> "(request_id, dataseries_id, position, value) " <> "values (?, ?, ?, ?)" Foldable.forM_ (Poller.requestMeasurements req) $ \(dsId, calc, oids) -> do _ <- Postgres.execute conn stmt (reqId, dsId, calc) Foldable.forM_ (zip oids [1..]) $ \(oid, pos::Int) -> do _ <- Postgres.execute conn stmt2 (reqId, dsId, pos, oid) return () let stmt = "insert into sched_request_slot (request_id, interval, slot) values (?, ?, ?)" _ <- Postgres.execute conn stmt (reqId, interval, slot) Postgres.commit conn deleteRequestFromSchedules conn req = do let reqId = Poller.requestId req Postgres.begin conn let stmt = "delete from sched_request_measure_val where request_id = ?" _ <- Postgres.execute conn stmt [reqId] let stmt = "delete from sched_request_measure where request_id = ?" _ <- Postgres.execute conn stmt [reqId] let stmt = "delete from sched_request_slot where request_id = ?" _ <- Postgres.execute conn stmt [reqId] let stmt = "delete from sched_request where request_id = ?" _ <- Postgres.execute conn stmt [reqId] Postgres.commit conn insertHighResValue conn res = do let stmt = "insert into measure_highres " <> "(dataseries_id, ts, value, valid_ind)" <> " values (?, to_timestamp(?), ?, ?)" let valid_ind = Poller.resultErrorCode res let bindvals = ( Poller.resultDataseriesId res , Poller.resultTimestamp res , Poller.resultValue res , valid_ind ) Postgres.begin conn _ <- Postgres.execute conn stmt bindvals Postgres.commit conn
abayley/netpoll
src/Netpoll/Database.hs
gpl-3.0
16,044
0
35
4,087
3,095
1,677
1,418
248
4
{-# LANGUAGE FlexibleContexts #-} module Language.Objection.Parser.Token ( tokenize, Token(..), ) where import Control.Applicative ((<$>), (*>), (<*)) import Control.Monad.Identity (Identity) import Data.Int import Text.Parsec data Token = TAdd | TChar | TClass | TComma | TDivide | TDot | TDoubleEquals | TEquals | TG | TGE | TIdentifier String | TInt | TIntLiteral Int32 | TL | TLE | TLeftBrace | TLeftBracket | TLeftParen | TLong | TMultiply | TPrivate | TProtected | TPublic | TRightBrace | TRightBracket | TRightParen | TSemicolon | TSubtract | TVoid deriving (Show, Read) tokenize :: Stream s Identity Char => SourceName -> s -> Either ParseError [(SourcePos, Token)] tokenize = parse tokensP stringToken :: (Stream s m Char, Monad m) => String -> Token -> ParsecT s u m Token stringToken s t = try (string s) *> return t charToken :: (Stream s m Char, Monad m) => Char -> Token -> ParsecT s u m Token charToken c t = char c *> return t integerLiteralP :: (Stream s m Char, Monad m) => ParsecT s u m Int32 integerLiteralP = read <$> try (many1 digit) identifierP :: (Stream s m Char, Monad m) => ParsecT s u m String identifierP = try (many1 letter) tokensP :: (Stream s m Char, Monad m) => ParsecT s u m [(SourcePos, Token)] tokensP = many $ spaces *> tokenP <* spaces tokenP :: (Stream s m Char, Monad m) => ParsecT s u m (SourcePos, Token) tokenP = do pos <- getPosition tok <- charToken '+' TAdd <|> stringToken "char" TChar <|> stringToken "class" TClass <|> charToken ',' TComma <|> charToken '/' TDivide <|> charToken '.' TDot <|> stringToken "==" TDoubleEquals <|> charToken '=' TEquals <|> stringToken ">=" TGE <|> charToken '>' TG <|> stringToken "int" TInt <|> stringToken "<=" TLE <|> charToken '<' TL <|> charToken '{' TLeftBrace <|> charToken '[' TLeftBracket <|> charToken '(' TLeftParen <|> stringToken "long" TLong <|> charToken '*' TMultiply <|> stringToken "private" TPrivate <|> stringToken "protected" TProtected <|> stringToken "public" TPublic <|> charToken '}' TRightBrace <|> charToken ']' TRightBracket <|> charToken ')' TRightParen <|> charToken ';' TSemicolon <|> charToken '-' TSubtract <|> stringToken "void" TVoid <|> (TIntLiteral <$> integerLiteralP) <|> (TIdentifier <$> identifierP) <?> "Token" return (pos, tok)
jhance/objection
Language/Objection/Parser/Token.hs
gpl-3.0
3,351
0
37
1,467
837
438
399
93
1
{-# LANGUAGE GADTs, Rank2Types, CPP #-} -- Module : FRP.Yampa.Basic -- Copyright : (c) Antony Courtney and Henrik Nilsson, Yale University, 2003 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (GHC extensions) -- | Defines basic signal functions, and elementary ways of altering them. -- -- This module defines very basic ways of creating and modifying signal -- functions. In particular, it defines ways of creating constant output -- producing SFs, and SFs that just pass the signal through unmodified. -- -- It also defines ways of altering the input and the output signal only -- by inserting one value in the signal, or by transforming it. module FRP.Yampa.Basic ( -- * Basic signal functions identity, -- :: SF a a constant, -- :: b -> SF a b -- ** Initialization (-->), -- :: b -> SF a b -> SF a b, infixr 0 (>--), -- :: a -> SF a b -> SF a b, infixr 0 (-=>), -- :: (b -> b) -> SF a b -> SF a b infixr 0 (>=-), -- :: (a -> a) -> SF a b -> SF a b infixr 0 initially -- :: a -> SF a a ) where import FRP.Yampa.InternalCore (SF(..), sfConst, sfId) infixr 0 -->, >--, -=>, >=- ------------------------------------------------------------------------------ -- Basic signal functions ------------------------------------------------------------------------------ -- | Identity: identity = arr id -- -- Using 'identity' is preferred over lifting id, since the arrow combinators -- know how to optimise certain networks based on the transformations being -- applied. identity :: SF a a identity = SF {sfTF = \a -> (sfId, a)} {-# ANN constant "HLint: ignore Use const" #-} -- | Identity: constant b = arr (const b) -- -- Using 'constant' is preferred over lifting const, since the arrow combinators -- know how to optimise certain networks based on the transformations being -- applied. constant :: b -> SF a b constant b = SF {sfTF = \_ -> (sfConst b, b)} ------------------------------------------------------------------------------ -- Initialization ------------------------------------------------------------------------------ -- | Initialization operator (cf. Lustre/Lucid Synchrone). -- -- The output at time zero is the first argument, and from -- that point on it behaves like the signal function passed as -- second argument. (-->) :: b -> SF a b -> SF a b b0 --> (SF {sfTF = tf10}) = SF {sfTF = \a0 -> (fst (tf10 a0), b0)} -- | Input initialization operator. -- -- The input at time zero is the first argument, and from -- that point on it behaves like the signal function passed as -- second argument. (>--) :: a -> SF a b -> SF a b a0 >-- (SF {sfTF = tf10}) = SF {sfTF = \_ -> tf10 a0} -- | Transform initial output value. -- -- Applies a transformation 'f' only to the first output value at -- time zero. (-=>) :: (b -> b) -> SF a b -> SF a b f -=> (SF {sfTF = tf10}) = SF {sfTF = \a0 -> let (sf1, b0) = tf10 a0 in (sf1, f b0)} -- | Transform initial input value. -- -- Applies a transformation 'f' only to the first input value at -- time zero. {-# ANN (>=-) "HLint: ignore Avoid lambda" #-} (>=-) :: (a -> a) -> SF a b -> SF a b f >=- (SF {sfTF = tf10}) = SF {sfTF = \a0 -> tf10 (f a0)} -- | Override initial value of input signal. initially :: a -> SF a a initially = (--> identity)
keera-studios/pang-a-lambda
Yampa-0.10.4/src/FRP/Yampa/Basic.hs
gpl-3.0
3,519
0
12
806
551
338
213
28
1
module Hamming (distance) where distance :: String -> String -> Maybe Int distance [] [] = Just 0 distance [] _ = Nothing distance _ [] = Nothing distance (x:xs) (y:ys) = if eq then rest else rest >>= return . (+1) where eq = x == y rest = distance xs ys
daewon/til
exercism/haskell/hamming/src/Hamming.hs
mpl-2.0
266
0
7
64
131
70
61
8
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DLP.Organizations.Locations.StoredInfoTypes.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a stored infoType. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-stored-infotypes to -- learn more. -- -- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.organizations.locations.storedInfoTypes.get@. module Network.Google.Resource.DLP.Organizations.Locations.StoredInfoTypes.Get ( -- * REST Resource OrganizationsLocationsStoredInfoTypesGetResource -- * Creating a Request , organizationsLocationsStoredInfoTypesGet , OrganizationsLocationsStoredInfoTypesGet -- * Request Lenses , olsitgXgafv , olsitgUploadProtocol , olsitgAccessToken , olsitgUploadType , olsitgName , olsitgCallback ) where import Network.Google.DLP.Types import Network.Google.Prelude -- | A resource alias for @dlp.organizations.locations.storedInfoTypes.get@ method which the -- 'OrganizationsLocationsStoredInfoTypesGet' request conforms to. type OrganizationsLocationsStoredInfoTypesGetResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GooglePrivacyDlpV2StoredInfoType -- | Gets a stored infoType. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-stored-infotypes to -- learn more. -- -- /See:/ 'organizationsLocationsStoredInfoTypesGet' smart constructor. data OrganizationsLocationsStoredInfoTypesGet = OrganizationsLocationsStoredInfoTypesGet' { _olsitgXgafv :: !(Maybe Xgafv) , _olsitgUploadProtocol :: !(Maybe Text) , _olsitgAccessToken :: !(Maybe Text) , _olsitgUploadType :: !(Maybe Text) , _olsitgName :: !Text , _olsitgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrganizationsLocationsStoredInfoTypesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olsitgXgafv' -- -- * 'olsitgUploadProtocol' -- -- * 'olsitgAccessToken' -- -- * 'olsitgUploadType' -- -- * 'olsitgName' -- -- * 'olsitgCallback' organizationsLocationsStoredInfoTypesGet :: Text -- ^ 'olsitgName' -> OrganizationsLocationsStoredInfoTypesGet organizationsLocationsStoredInfoTypesGet pOlsitgName_ = OrganizationsLocationsStoredInfoTypesGet' { _olsitgXgafv = Nothing , _olsitgUploadProtocol = Nothing , _olsitgAccessToken = Nothing , _olsitgUploadType = Nothing , _olsitgName = pOlsitgName_ , _olsitgCallback = Nothing } -- | V1 error format. olsitgXgafv :: Lens' OrganizationsLocationsStoredInfoTypesGet (Maybe Xgafv) olsitgXgafv = lens _olsitgXgafv (\ s a -> s{_olsitgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). olsitgUploadProtocol :: Lens' OrganizationsLocationsStoredInfoTypesGet (Maybe Text) olsitgUploadProtocol = lens _olsitgUploadProtocol (\ s a -> s{_olsitgUploadProtocol = a}) -- | OAuth access token. olsitgAccessToken :: Lens' OrganizationsLocationsStoredInfoTypesGet (Maybe Text) olsitgAccessToken = lens _olsitgAccessToken (\ s a -> s{_olsitgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). olsitgUploadType :: Lens' OrganizationsLocationsStoredInfoTypesGet (Maybe Text) olsitgUploadType = lens _olsitgUploadType (\ s a -> s{_olsitgUploadType = a}) -- | Required. Resource name of the organization and storedInfoType to be -- read, for example -- \`organizations\/433245324\/storedInfoTypes\/432452342\` or -- projects\/project-id\/storedInfoTypes\/432452342. olsitgName :: Lens' OrganizationsLocationsStoredInfoTypesGet Text olsitgName = lens _olsitgName (\ s a -> s{_olsitgName = a}) -- | JSONP olsitgCallback :: Lens' OrganizationsLocationsStoredInfoTypesGet (Maybe Text) olsitgCallback = lens _olsitgCallback (\ s a -> s{_olsitgCallback = a}) instance GoogleRequest OrganizationsLocationsStoredInfoTypesGet where type Rs OrganizationsLocationsStoredInfoTypesGet = GooglePrivacyDlpV2StoredInfoType type Scopes OrganizationsLocationsStoredInfoTypesGet = '["https://www.googleapis.com/auth/cloud-platform"] requestClient OrganizationsLocationsStoredInfoTypesGet'{..} = go _olsitgName _olsitgXgafv _olsitgUploadProtocol _olsitgAccessToken _olsitgUploadType _olsitgCallback (Just AltJSON) dLPService where go = buildClient (Proxy :: Proxy OrganizationsLocationsStoredInfoTypesGetResource) mempty
brendanhay/gogol
gogol-dlp/gen/Network/Google/Resource/DLP/Organizations/Locations/StoredInfoTypes/Get.hs
mpl-2.0
5,716
0
15
1,181
703
414
289
109
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Webmasters.Sites.Add -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Adds a site to the set of the user\'s sites in Search Console. -- -- /See:/ <https://developers.google.com/webmaster-tools/ Search Console API Reference> for @webmasters.sites.add@. module Network.Google.Resource.Webmasters.Sites.Add ( -- * REST Resource SitesAddResource -- * Creating a Request , sitesAdd , SitesAdd -- * Request Lenses , saSiteURL ) where import Network.Google.Prelude import Network.Google.WebmasterTools.Types -- | A resource alias for @webmasters.sites.add@ method which the -- 'SitesAdd' request conforms to. type SitesAddResource = "webmasters" :> "v3" :> "sites" :> Capture "siteUrl" Text :> QueryParam "alt" AltJSON :> Put '[JSON] () -- | Adds a site to the set of the user\'s sites in Search Console. -- -- /See:/ 'sitesAdd' smart constructor. newtype SitesAdd = SitesAdd' { _saSiteURL :: Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SitesAdd' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'saSiteURL' sitesAdd :: Text -- ^ 'saSiteURL' -> SitesAdd sitesAdd pSaSiteURL_ = SitesAdd' {_saSiteURL = pSaSiteURL_} -- | The URL of the site to add. saSiteURL :: Lens' SitesAdd Text saSiteURL = lens _saSiteURL (\ s a -> s{_saSiteURL = a}) instance GoogleRequest SitesAdd where type Rs SitesAdd = () type Scopes SitesAdd = '["https://www.googleapis.com/auth/webmasters"] requestClient SitesAdd'{..} = go _saSiteURL (Just AltJSON) webmasterToolsService where go = buildClient (Proxy :: Proxy SitesAddResource) mempty
brendanhay/gogol
gogol-webmaster-tools/gen/Network/Google/Resource/Webmasters/Sites/Add.hs
mpl-2.0
2,534
0
12
582
303
186
117
46
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeOperators #-} import Control.Applicative import Control.Exception (throwIO) import Control.Lens import Control.Monad (void, forM) import Data.Char (toLower) import Data.Configifier import Data.Function (on) import Data.Functor.Infix ((<$$>)) import Data.List (intercalate, sortBy, isPrefixOf) import Data.Maybe (catMaybes) import Data.String.Conversions import Data.Typeable import Data.Version import Distribution.PackageDescription import Distribution.PackageDescription.Parse import Distribution.PackageDescription.PrettyPrint import Distribution.Verbosity import Distribution.Version import Network.Wreq hiding (Proxy) import System.Directory import System.Environment import Text.Show.Pretty import qualified Data.Attoparsec.ByteString.Char8 as AP import qualified Data.Attoparsec.Combinator as AP import qualified Data.ByteString as SBS import qualified Data.Map.Strict as Map type Config = Tagged ConfigDesc type ConfigDesc = ToConfigCode Config' type Config' = Maybe ("cabalFile" :> ST) :*> ("freezeFiles" :> [ST]) getConfig :: IO Config getConfig = do let configFile :: FilePath = "./conf.yml" configFileSource :: [Source] <- do yes <- doesFileExist configFile return $ if yes then [YamlFile configFile] else [] sources <- (configFileSource ++) <$> (sequence [ ShellEnv <$> getEnvironment , CommandLine <$> getArgs ]) configify sources main' :: IO () main' = do config :: Config <- getConfig let Just cabalFile :: Maybe FilePath = cs <$> config >>. (Proxy :: Proxy '["cabalFile"]) freezeFiles :: [FilePath] = cs <$> config >>. (Proxy :: Proxy '["freezeFiles"]) cabalFileContents <- readPackageDescription deafening cabalFile print cabalFileContents -- the cabal config file parser lives in cabal-install in -- Distribution.Client.Config, which is not exposed in a library. -- so what this was all about won't work as simply as i hoped... -- freezeFileContents :: Int <- _ deafening freezeFile -- print freezeFileContents -- lowerBoundsFromFreezeFile :: FilePath -> FilePath -> IO () -- lowerBoundsFromFreezeFile = _ ---------------------------------------------------------------------- -- pull stackage config, relax version constraints, and impose on package file's `build-depends` -- section. main :: IO () main = do config :: Config <- getConfig let freezeFiles :: [FilePath] = cs <$> config >>. (Proxy :: Proxy '["freezeFiles"]) versionFreeze <- mconcat . reverse <$> forM freezeFiles (\ freezeFile -> do putStrLn $ " -- source: " ++ freezeFile versionFreezeStr :: SBS <- if "http://" `isPrefixOf` freezeFile || "https://" `isPrefixOf` freezeFile then cs . (^. responseBody) <$> get freezeFile else SBS.readFile freezeFile let Right versionFreezePart = parseFreezeFile versionFreezeStr -- print versionFreezePart -- print $ Map.size versionFreezePart return versionFreezePart) Right (deps :: [ST]) <- parseBuildDependsBlob . cs <$> getContents putStrLn . showConstraints $ injectConstraints deps versionFreeze type VersionFreeze = Map.Map ST Version -- | Since cabal-install doesn't export cabal config file parsing as a library, we re-implement the -- parts we need for stackage here. parseFreezeFile :: SBS -> Either String VersionFreeze parseFreezeFile = AP.eitherResult . AP.parse p where p :: AP.Parser VersionFreeze p = do AP.many' comment AP.string "constraints:" Map.fromList . catMaybes <$> AP.many' constraint comment :: AP.Parser () comment = AP.string "--" >> AP.manyTill' AP.anyChar end >> return () end :: AP.Parser () end = AP.endOfLine <|> AP.endOfInput constraint :: AP.Parser (Maybe (ST, Version)) constraint = do AP.many' AP.space n :: String <- AP.manyTill' AP.anyChar AP.space AP.many' AP.space ((do AP.string "==" v :: Version <- version [] end return $ Just (cs n, v)) <|> (do AP.string "installed," return Nothing)) version :: [Int] -> AP.Parser Version version acc = do i :: Int <- AP.decimal let acc' = acc ++ [i] ((AP.char ',' >> return (Version acc' [])) <|> (AP.char '.' >> version acc')) -- | Read a `build-depends` cut&pasted from a package description file (discard version -- constraints). parseBuildDependsBlob :: SBS -> Either String [ST] parseBuildDependsBlob s = AP.eitherResult $ AP.feed (AP.parse p s) "" where p :: AP.Parser [ST] p = AP.many' space' >> AP.sepBy' (cs <$> it) sep sep :: AP.Parser () sep = AP.manyTill' AP.anyChar (AP.char ',') >> void (AP.many' space') space' :: AP.Parser () space' = void AP.space <|> AP.endOfLine it :: AP.Parser String it = (:) <$> AP.satisfy (AP.inClass "a-zA-Z") <*> AP.many' (AP.satisfy (AP.inClass "-0-9a-zA-Z")) type VersionConstraint = Either Version VersionInterval type VersionConstraints = Map.Map ST VersionConstraint injectConstraints :: [ST] -> VersionFreeze -> VersionConstraints injectConstraints packages freeze = Map.fromList $ f <$> packages where f :: ST -> (ST, VersionConstraint) f package = (package,) $ case Map.lookup package freeze of Just v -> mkConstraint v Nothing -> error $ "injectConstraints: package " <> show package <> " not found in freeze files." mkConstraint :: Version -> VersionConstraint mkConstraint (Version v@(a:b:_) _) = Right ( LowerBound (Version v []) InclusiveBound , UpperBound (Version [a, b+1] []) ExclusiveBound ) mkConstraint v = Left v showConstraints :: VersionConstraints -> String showConstraints constraints = " " <> intercalate "\n , " (f <$> sort' (Map.toList constraints)) where f :: (ST, VersionConstraint) -> String -- f (p, (Left (Version [] _))) = cs p f (p, (Left v)) = cs p <> " ==" <> showVersion v f (p, (Right (LowerBound l InclusiveBound, UpperBound u ExclusiveBound))) = cs p <> " >=" <> showVersion l <> " && <" <> showVersion u sort' :: [(ST, a)] -> [(ST, a)] sort' = sortBy (compare `on` (map toLower . cs . fst))
fisx/cabal-extras
src/Main.hs
agpl-3.0
6,433
0
18
1,343
1,827
957
870
132
2
ans [a,b] = a + b main = do l <- getLine let i = map read $ words l :: [Integer] o = ans i print o
a143753/AOJ
NTL_2_A.hs
apache-2.0
119
0
11
48
70
34
36
6
1
module Arrays where import Data.Array.IArray type ArrayLength = Int createNewEmptyArray :: ArrayLength -> Array Int a createNewEmptyArray = undefined fromList :: [a] -> Array Int a fromList xs = listArray (0, l - 1) xs where l = length xs buildPair :: (Int, Int) buildPair = let arr = listArray (1,10) (repeat 37) :: Array Int Int arr' = arr // [(1, 64)] in (arr ! 1, arr' ! 1)
songpp/my-haskell-playground
src/Arrays.hs
apache-2.0
417
0
11
109
169
94
75
12
1
module External.A137735 (a137735) where a137735 :: Int -> Integer a137735 n = a137735_list !! n a137735_list :: [Integer] a137735_list = 1 : remaining 1 1 where remaining n maxTerm = nextTerm : remaining (n + 1) (max nextTerm maxTerm) where nextTerm = floor $ toRational n / toRational maxTerm
peterokagey/haskellOEIS
src/External/A137735.hs
apache-2.0
302
0
11
57
111
58
53
7
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE RecordWildCards #-} -- | The module provides functionality for manipulating PoliMorf, the -- morphological dictionary for Polish. module Data.PoliMorf ( -- * Types Form , Base , POS , MSD , Tag , Cat , Entry (..) , split , pos , msd , atomic -- * Parsing , readPoliMorf , parsePoliMorf ) where import Control.Applicative ((<$>)) import Control.Arrow (second) import qualified Data.Text as T import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.IO as L -- | A word form. type Form = T.Text -- | A base form. type Base = T.Text -- | A part of speech. type POS = T.Text -- | A morphosyntactic description type MSD = T.Text -- | A morphosyntactic tag. (Tag = POS + MSD) type Tag = T.Text -- | A semantic category. It will be set to "" when there is -- no category assigned to a particular PoliMorf entry. type Cat = T.Text -- | An entry from the PoliMorf dictionary. data Entry = Entry { form :: !Form , base :: !Base , tag :: !Tag , cat :: !Cat } deriving (Eq, Ord, Show, Read) -- | Split tag. split :: Tag -> (POS, MSD) split = second (T.drop 1) . T.break (==':') -- | Entry POS. pos :: Entry -> POS pos = fst . split . tag -- | Entry MSD. msd :: Entry -> MSD msd = snd . split . tag -- | Is the entry an atomic one? More precisely, we treat all negative -- forms starting with ''nie'' and all superlatives starting with ''naj'' -- as non-atomic entries. atomic :: Entry -> Bool atomic x | "sup" `T.isInfixOf` tag x && "naj" `T.isPrefixOf` form x = False | "neg" `T.isInfixOf` tag x && "nie" `T.isPrefixOf` form x = False | otherwise = True -- | Read the PoliMorf from the file. readPoliMorf :: FilePath -> IO [Entry] readPoliMorf path = parsePoliMorf <$> L.readFile path -- | Parse the PoliMorf into a list of entries. parsePoliMorf :: L.Text -> [Entry] parsePoliMorf = map parsePoliRow . L.lines -- | Get an entry pair from a PoliMorf row. parsePoliRow :: L.Text -> Entry parsePoliRow row = case map L.toStrict (L.split (=='\t') row) of _form : _base : _tag : rest -> Entry _form _base _tag $ case rest of [] -> "" (_cat:_) -> _cat _ -> error $ "parsePoliRow: invalid row \"" ++ L.unpack row ++ "\""
kawu/polimorf
src/Data/PoliMorf.hs
bsd-2-clause
2,320
0
13
512
591
342
249
65
3
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} -- | -- -- Generic OAuth2 plugin for Yesod -- -- * See Yesod.Auth.OAuth2.GitHub for example usage. -- module Yesod.Auth.OAuth2 ( authOAuth2 , authOAuth2Widget , oauth2Url , fromProfileURL , YesodOAuth2Exception(..) , module Network.OAuth.OAuth2 ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif import Control.Exception.Lifted import Control.Monad.IO.Class import Data.ByteString (ByteString) import Data.Monoid ((<>)) import Data.Text (Text, pack) import Data.Text.Encoding (decodeUtf8With, encodeUtf8) import Data.Text.Encoding.Error (lenientDecode) import Data.Typeable import Network.HTTP.Conduit (Manager) import Network.OAuth.OAuth2 import System.Random import Yesod.Auth import Yesod.Core import Yesod.Form import qualified Data.ByteString.Lazy as BL -- | Provider name and Aeson parse error data YesodOAuth2Exception = InvalidProfileResponse Text BL.ByteString deriving (Show, Typeable) instance Exception YesodOAuth2Exception oauth2Url :: Text -> AuthRoute oauth2Url name = PluginR name ["forward"] -- | Create an @'AuthPlugin'@ for the given OAuth2 provider -- -- Presents a generic @"Login via name"@ link -- authOAuth2 :: YesodAuth m => Text -- ^ Service name -> OAuth2 -- ^ Service details -> (Manager -> AccessToken -> IO (Creds m)) -- ^ This function defines how to take an @'AccessToken'@ and -- retrieve additional information about the user, to be -- set in the session as @'Creds'@. Usually this means a -- second authorized request to @api/me.json@. -- -- See @'fromProfileURL'@ for an example. -> AuthPlugin m authOAuth2 name = authOAuth2Widget [whamlet|Login via #{name}|] name -- | Create an @'AuthPlugin'@ for the given OAuth2 provider -- -- Allows passing a custom widget for the login link. See @'oauth2Eve'@ for an -- example. -- authOAuth2Widget :: YesodAuth m => WidgetT m IO () -> Text -> OAuth2 -> (Manager -> AccessToken -> IO (Creds m)) -> AuthPlugin m authOAuth2Widget widget name oauth getCreds = AuthPlugin name dispatch login where url = PluginR name ["callback"] withCallback csrfToken = do tm <- getRouteToParent render <- lift getUrlRender return oauth { oauthCallback = Just $ encodeUtf8 $ render $ tm url , oauthOAuthorizeEndpoint = oauthOAuthorizeEndpoint oauth <> "&state=" <> encodeUtf8 csrfToken } dispatch "GET" ["forward"] = do csrfToken <- liftIO generateToken setSession tokenSessionKey csrfToken authUrl <- bsToText . authorizationUrl <$> withCallback csrfToken lift $ redirect authUrl dispatch "GET" ["callback"] = do newToken <- lookupGetParam "state" oldToken <- lookupSession tokenSessionKey deleteSession tokenSessionKey case newToken of Just csrfToken | newToken == oldToken -> do code <- lift $ runInputGet $ ireq textField "code" oauth' <- withCallback csrfToken master <- lift getYesod result <- liftIO $ fetchAccessToken (authHttpManager master) oauth' (encodeUtf8 code) case result of Left _ -> permissionDenied "Unable to retreive OAuth2 token" Right token -> do creds <- liftIO $ getCreds (authHttpManager master) token lift $ setCredsRedirect creds _ -> permissionDenied "Invalid OAuth2 state token" dispatch _ _ = notFound generateToken = pack . take 30 . randomRs ('a', 'z') <$> newStdGen tokenSessionKey :: Text tokenSessionKey = "_yesod_oauth2_" <> name login tm = [whamlet|<a href=@{tm $ oauth2Url name}>^{widget}|] -- | Handle the common case of fetching Profile information from a JSON endpoint -- -- Throws @'InvalidProfileResponse'@ if JSON parsing fails -- fromProfileURL :: FromJSON a => Text -- ^ Plugin name -> URI -- ^ Profile URI -> (a -> Creds m) -- ^ Conversion to Creds -> Manager -> AccessToken -> IO (Creds m) fromProfileURL name url toCreds manager token = do result <- authGetJSON manager token url case result of Right profile -> return $ toCreds profile Left err -> throwIO $ InvalidProfileResponse name err bsToText :: ByteString -> Text bsToText = decodeUtf8With lenientDecode
jasonzoladz/yesod-auth-oauth2
Yesod/Auth/OAuth2.hs
bsd-2-clause
4,800
0
24
1,327
967
512
455
93
5
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} ------------------------------------------------------------------------------ -- | Pre-packaged Handlers that deal with form submissions and standard -- use-cases involving authentication. module Snap.Snaplet.Auth.Handlers where ------------------------------------------------------------------------------ import Control.Applicative import Control.Monad.State import Control.Monad.Trans.Either import Control.Monad.Trans.Maybe import Data.ByteString (ByteString) import Data.Maybe import Data.Serialize hiding (get) import Data.Time import Data.Text.Encoding (decodeUtf8) import Data.Text (Text, null, strip) import Prelude hiding (null) import Web.ClientSession ------------------------------------------------------------------------------ import Snap.Core import Snap.Snaplet import Snap.Snaplet.Auth.AuthManager import Snap.Snaplet.Auth.Handlers.Errors import Snap.Snaplet.Auth.Types import Snap.Snaplet.Session ------------------------------------------------------------------------------ ---------------------------- -- Higher level functions -- ---------------------------- ------------------------------------------------------------------------------ -- | Create a new user from just a username and password -- createUser :: Text -- ^ Username -> ByteString -- ^ Password -> Handler b (AuthManager b) (Either AuthFailure AuthUser) createUser unm pwd | null $ strip unm = return $ Left UsernameMissing | otherwise = do uExists <- usernameExists unm if uExists then return $ Left DuplicateLogin else withBackend $ \r -> liftIO $ buildAuthUser r unm pwd ------------------------------------------------------------------------------ -- | Check whether a user with the given username exists. -- usernameExists :: Text -- ^ The username to be checked -> Handler b (AuthManager b) Bool usernameExists username = withBackend $ \r -> liftIO $ isJust <$> lookupByLogin r username ------------------------------------------------------------------------------ -- | Lookup a user by her username, check given password and perform login -- loginByUsername :: Text -- ^ Username/login for user -> Password -- ^ Should be ClearText -> Bool -- ^ Set remember token? -> Handler b (AuthManager b) (Either AuthFailure AuthUser) loginByUsername _ (Encrypted _) _ = return $ Left EncryptedPassword loginByUsername unm pwd shouldRemember = do sk <- gets siteKey cn <- gets rememberCookieName cd <- gets rememberCookieDomain rp <- gets rememberPeriod withBackend $ loginByUsername' sk cn cd rp where -------------------------------------------------------------------------- loginByUsername' :: (IAuthBackend t) => Key -> ByteString -> Maybe ByteString -> Maybe Int -> t -> Handler b (AuthManager b) (Either AuthFailure AuthUser) loginByUsername' sk cn cd rp r = liftIO (lookupByLogin r unm) >>= maybe (return $! Left UserNotFound) found where ---------------------------------------------------------------------- found user = checkPasswordAndLogin user pwd >>= either (return . Left) matched ---------------------------------------------------------------------- matched user | shouldRemember = do token <- gets randomNumberGenerator >>= liftIO . randomToken 64 setRememberToken sk cn cd rp token let user' = user { userRememberToken = Just (decodeUtf8 token) } saveUser user' return $! Right user' | otherwise = return $ Right user ------------------------------------------------------------------------------ -- | Remember user from the remember token if possible and perform login -- loginByRememberToken :: Handler b (AuthManager b) (Either AuthFailure AuthUser) loginByRememberToken = withBackend $ \impl -> do key <- gets siteKey cookieName_ <- gets rememberCookieName period <- gets rememberPeriod runEitherT $ do token <- noteT (AuthError "loginByRememberToken: no remember token") $ MaybeT $ getRememberToken key cookieName_ period user <- noteT (AuthError "loginByRememberToken: no remember token") $ MaybeT $ liftIO $ lookupByRememberToken impl $ decodeUtf8 token lift $ forceLogin user return user ------------------------------------------------------------------------------ -- | Logout the active user -- logout :: Handler b (AuthManager b) () logout = do s <- gets session withTop s $ withSession s removeSessionUserId rc <- gets rememberCookieName rd <- gets rememberCookieDomain expireSecureCookie rc rd modify $ \mgr -> mgr { activeUser = Nothing } ------------------------------------------------------------------------------ -- | Return the current user; trying to remember from cookie if possible. -- currentUser :: Handler b (AuthManager b) (Maybe AuthUser) currentUser = cacheOrLookup $ withBackend $ \r -> do s <- gets session uid <- withTop s getSessionUserId case uid of Nothing -> hush <$> loginByRememberToken Just uid' -> liftIO $ lookupByUserId r uid' ------------------------------------------------------------------------------ -- | Convenience wrapper around 'rememberUser' that returns a bool result -- isLoggedIn :: Handler b (AuthManager b) Bool isLoggedIn = isJust <$> currentUser ------------------------------------------------------------------------------ -- | Create or update a given user -- saveUser :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) saveUser u | null $ userLogin u = return $ Left UsernameMissing | otherwise = withBackend $ \r -> liftIO $ save r u ------------------------------------------------------------------------------ -- | Destroy the given user -- destroyUser :: AuthUser -> Handler b (AuthManager b) () destroyUser u = withBackend $ liftIO . flip destroy u ----------------------------------- -- Lower level helper functions -- ----------------------------------- ------------------------------------------------------------------------------ -- | Mutate an 'AuthUser', marking failed authentication -- -- This will save the user to the backend. -- markAuthFail :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) markAuthFail u = withBackend $ \r -> do lo <- gets lockout incFailCtr u >>= checkLockout lo >>= liftIO . save r where -------------------------------------------------------------------------- incFailCtr u' = return $ u' { userFailedLoginCount = userFailedLoginCount u' + 1 } -------------------------------------------------------------------------- checkLockout lo u' = case lo of Nothing -> return u' Just (mx, wait) -> if userFailedLoginCount u' >= mx then do now <- liftIO getCurrentTime let reopen = addUTCTime wait now return $! u' { userLockedOutUntil = Just reopen } else return u' ------------------------------------------------------------------------------ -- | Mutate an 'AuthUser', marking successful authentication -- -- This will save the user to the backend. -- markAuthSuccess :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) markAuthSuccess u = withBackend $ \r -> incLoginCtr u >>= updateIp >>= updateLoginTS >>= resetFailCtr >>= liftIO . save r where -------------------------------------------------------------------------- incLoginCtr u' = return $ u' { userLoginCount = userLoginCount u' + 1 } -------------------------------------------------------------------------- updateIp u' = do ip <- rqClientAddr <$> getRequest return $ u' { userLastLoginIp = userCurrentLoginIp u' , userCurrentLoginIp = Just ip } -------------------------------------------------------------------------- updateLoginTS u' = do now <- liftIO getCurrentTime return $ u' { userCurrentLoginAt = Just now , userLastLoginAt = userCurrentLoginAt u' } -------------------------------------------------------------------------- resetFailCtr u' = return $ u' { userFailedLoginCount = 0 , userLockedOutUntil = Nothing } ------------------------------------------------------------------------------ -- | Authenticate and log the user into the current session if successful. -- -- This is a mid-level function exposed to allow roll-your-own ways of looking -- up a user from the database. -- -- This function will: -- -- 1. Check the password -- -- 2. Login the user into the current session -- -- 3. Mark success/failure of the authentication trial on the user record -- checkPasswordAndLogin :: AuthUser -- ^ An existing user, somehow looked up from db -> Password -- ^ A ClearText password -> Handler b (AuthManager b) (Either AuthFailure AuthUser) checkPasswordAndLogin u pw = case userLockedOutUntil u of Just x -> do now <- liftIO getCurrentTime if now > x then auth u else return . Left $ LockedOut x Nothing -> auth u where auth :: AuthUser -> Handler b (AuthManager b) (Either AuthFailure AuthUser) auth user = case authenticatePassword user pw of Just e -> do markAuthFail user return $ Left e Nothing -> do forceLogin user modify (\mgr -> mgr { activeUser = Just user }) markAuthSuccess user ------------------------------------------------------------------------------ -- | Login and persist the given 'AuthUser' in the active session -- -- Meant to be used if you have other means of being sure that the person is -- who she says she is. -- forceLogin :: AuthUser -- ^ An existing user, somehow looked up from db -> Handler b (AuthManager b) (Either AuthFailure ()) forceLogin u = do s <- gets session withSession s $ case userId u of Just x -> do withTop s (setSessionUserId x) return $ Right () Nothing -> return . Left $ AuthError $ "forceLogin: Can't force the login of a user " ++ "without userId" ------------------------------------ -- Internal, non-exported helpers -- ------------------------------------ ------------------------------------------------------------------------------ getRememberToken :: (Serialize t, MonadSnap m) => Key -> ByteString -> Maybe Int -> m (Maybe t) getRememberToken sk rc rp = getSecureCookie rc sk rp ------------------------------------------------------------------------------ setRememberToken :: (Serialize t, MonadSnap m) => Key -> ByteString -> Maybe ByteString -> Maybe Int -> t -> m () setRememberToken sk rc rd rp token = setSecureCookie rc rd sk rp token ------------------------------------------------------------------------------ -- | Set the current user's 'UserId' in the active session -- setSessionUserId :: UserId -> Handler b SessionManager () setSessionUserId (UserId t) = setInSession "__user_id" t ------------------------------------------------------------------------------ -- | Remove 'UserId' from active session, effectively logging the user out. removeSessionUserId :: Handler b SessionManager () removeSessionUserId = deleteFromSession "__user_id" ------------------------------------------------------------------------------ -- | Get the current user's 'UserId' from the active session -- getSessionUserId :: Handler b SessionManager (Maybe UserId) getSessionUserId = do uid <- getFromSession "__user_id" return $ liftM UserId uid ------------------------------------------------------------------------------ -- | Check password for a given user. -- -- Returns "Nothing" if check is successful and an "IncorrectPassword" error -- otherwise -- authenticatePassword :: AuthUser -- ^ Looked up from the back-end -> Password -- ^ Check against this password -> Maybe AuthFailure authenticatePassword u pw = auth where auth = case userPassword u of Nothing -> Just PasswordMissing Just upw -> check $ checkPassword pw upw check b = if b then Nothing else Just IncorrectPassword ------------------------------------------------------------------------------ -- | Wrap lookups around request-local cache -- cacheOrLookup :: Handler b (AuthManager b) (Maybe AuthUser) -- ^ Lookup action to perform if request local cache is empty -> Handler b (AuthManager b) (Maybe AuthUser) cacheOrLookup f = do au <- gets activeUser if isJust au then return au else do au' <- f modify (\mgr -> mgr { activeUser = au' }) return au' ------------------------------------------------------------------------------ -- | Register a new user by specifying login and password 'Param' fields -- registerUser :: ByteString -- ^ Login field -> ByteString -- ^ Password field -> Handler b (AuthManager b) (Either AuthFailure AuthUser) registerUser lf pf = do l <- fmap decodeUtf8 <$> getParam lf p <- getParam pf let l' = note UsernameMissing l let p' = note PasswordMissing p -- In case of multiple AuthFailure, the first available one -- will be propagated. case liftM2 (,) l' p' of Left e -> return $ Left e Right (lgn, pwd) -> createUser lgn pwd ------------------------------------------------------------------------------ -- | A 'MonadSnap' handler that processes a login form. -- -- The request paremeters are passed to 'performLogin' -- -- To make your users stay logged in for longer than the session replay -- prevention timeout, you must pass a field name as the third parameter and -- that field must be set to a value of \"1\" by the submitting form. This -- lets you use a user selectable check box. Or if you want user remembering -- always turned on, you can use a hidden form field. loginUser :: ByteString -- ^ Username field -> ByteString -- ^ Password field -> Maybe ByteString -- ^ Remember field; Nothing if you want no remember function. -> (AuthFailure -> Handler b (AuthManager b) ()) -- ^ Upon failure -> Handler b (AuthManager b) () -- ^ Upon success -> Handler b (AuthManager b) () loginUser unf pwdf remf loginFail loginSucc = runEitherT (loginUser' unf pwdf remf) >>= either loginFail (const loginSucc) ------------------------------------------------------------------------------ loginUser' :: ByteString -> ByteString -> Maybe ByteString -> EitherT AuthFailure (Handler b (AuthManager b)) AuthUser loginUser' unf pwdf remf = do mbUsername <- lift $ getParam unf mbPassword <- lift $ getParam pwdf remember <- lift $ liftM (fromMaybe False) (runMaybeT $ do field <- MaybeT $ return remf value <- MaybeT $ getParam field return $ value == "1" || value == "on") password <- noteT PasswordMissing $ hoistMaybe mbPassword username <- noteT UsernameMissing $ hoistMaybe mbUsername EitherT $ loginByUsername (decodeUtf8 username) (ClearText password) remember ------------------------------------------------------------------------------ -- | Simple handler to log the user out. Deletes user from session. -- logoutUser :: Handler b (AuthManager b) () -- ^ What to do after logging out -> Handler b (AuthManager b) () logoutUser target = logout >> target ------------------------------------------------------------------------------ -- | Require that an authenticated 'AuthUser' is present in the current -- session. -- -- This function has no DB cost - only checks to see if a user_id is present -- in the current session. -- requireUser :: SnapletLens b (AuthManager b) -- ^ Lens reference to an "AuthManager" -> Handler b v a -- ^ Do this if no authenticated user is present. -> Handler b v a -- ^ Do this if an authenticated user is present. -> Handler b v a requireUser auth bad good = do loggedIn <- withTop auth isLoggedIn if loggedIn then good else bad ------------------------------------------------------------------------------ -- | Run a function on the backend, and return the result. -- -- This uses an existential type so that the backend type doesn't -- 'escape' AuthManager. The reason that the type is Handler b -- (AuthManager v) a and not a is because anything that uses the -- backend will return an IO something, which you can liftIO, or a -- Handler b (AuthManager v) a if it uses other handler things. -- withBackend :: (forall r. (IAuthBackend r) => r -> Handler b (AuthManager v) a) -- ^ The function to run with the handler. -> Handler b (AuthManager v) a withBackend f = join $ do (AuthManager backend_ _ _ _ _ _ _ _ _ _) <- get return $ f backend_ ------------------------------------------------------------------------------ -- | This function generates a random password reset token and stores it in -- the database for the user. Call this function when a user forgets their -- password. Then use the token to autogenerate a link that the user can -- visit to reset their password. This function also sets a timestamp so the -- reset token can be expired. setPasswordResetToken :: Text -> Handler b (AuthManager b) (Maybe Text) setPasswordResetToken login = do tokBS <- liftIO . randomToken 40 =<< gets randomNumberGenerator let token = decodeUtf8 tokBS now <- liftIO getCurrentTime success <- modPasswordResetToken login (Just token) (Just now) return $ if success then Just token else Nothing ------------------------------------------------------------------------------ -- | Clears a user's password reset token. Call this when the user -- successfully changes their password to ensure that the password reset link -- cannot be used again. clearPasswordResetToken :: Text -> Handler b (AuthManager b) Bool clearPasswordResetToken login = modPasswordResetToken login Nothing Nothing ------------------------------------------------------------------------------ -- | Helper function used for setting and clearing the password reset token -- and associated timestamp. modPasswordResetToken :: Text -> Maybe Text -> Maybe UTCTime -> Handler v (AuthManager v) Bool modPasswordResetToken login token timestamp = do res <- runMaybeT $ do u <- MaybeT $ withBackend $ \b -> liftIO $ lookupByLogin b login lift $ saveUser $ u { userResetToken = token , userResetRequestedAt = timestamp } return () return $ maybe False (\_ -> True) res
23Skidoo/snap
src/Snap/Snaplet/Auth/Handlers.hs
bsd-3-clause
20,449
0
19
5,403
3,650
1,852
1,798
292
4
import Data.Accessor import Graphics.Rendering.Chart.Plot.Image import Graphics.Rendering.Chart import Graphics.Rendering.Chart.Gtk import Data.Array.Repa ((:.)(..)) import qualified Data.Array.Repa as A size = 100 image :: A.Array A.U A.DIM2 (Double,Double,Double) image = A.computeS $ A.fromFunction (A.ix2 size size) $ \(A.Z :. x :. y)->( realToFrac y / realToFrac size , realToFrac x / realToFrac size , realToFrac (x+y) / realToFrac (2*size) ) chart :: Layout1 Double Double chart = layout where layout = layout1_title ^= "Hello World" $ layout1_plots ^= [Left (toPlot hi)] $ defaultLayout1 hi = image_data ^= image $ image_extent ^= ((0,0), (2,2)) $ defaultImage main = renderableToWindow (toRenderable chart) 640 480
bgamari/chart-image
Test.hs
bsd-3-clause
898
0
12
273
293
164
129
21
1
import System.Hardware.Sump as Sump import I2c import Data.Machine parseLevel '0' = Low parseLevel '1' = High signals = let sda = map parseLevel "1110001110001111" scl = map parseLevel "1111100100111111" in zipWith I2cSignals scl sda main = mapM_ print $ Data.Machine.run $ supply signals (auto decode)
bgamari/sump
TestI2c.hs
bsd-3-clause
323
0
9
65
101
52
49
10
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ViewPatterns #-} -- | -- Module : Data.Array.Accelerate.Trafo.Algebra -- Copyright : [2012] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Algebraic simplifications of scalar expressions, including constant folding -- and using algebraic properties of particular operator-operand combinations. -- module Data.Array.Accelerate.Trafo.Algebra ( evalPrimApp ) where import Prelude hiding ( exp ) import Data.Maybe ( fromMaybe ) import Data.Bits import Data.Char import qualified Prelude as P -- friends import Data.Array.Accelerate.AST import Data.Array.Accelerate.Type import Data.Array.Accelerate.Tuple import Data.Array.Accelerate.Array.Sugar ( Elt, toElt, fromElt ) import Data.Array.Accelerate.Analysis.Match import Data.Array.Accelerate.Trafo.Common -- Propagate constant expressions, which are either constant valued expressions -- or constant let bindings. Be careful not to follow self-cycles. -- propagate :: forall env aenv exp. Gamma env env aenv -> OpenExp env aenv exp -> Maybe exp propagate env = cvtE where cvtE :: OpenExp env aenv e -> Maybe e cvtE exp = case exp of Const c -> Just (toElt c) PrimConst c -> Just (evalPrimConst c) Prj ix (Var v) | Tuple t <- prjExp v env -> cvtT ix t Prj ix e | Just c <- cvtE e -> cvtP ix (fromTuple c) Var ix | e <- prjExp ix env , Nothing <- matchOpenExp exp e -> cvtE e -- _ -> Nothing cvtP :: TupleIdx t e -> t -> Maybe e cvtP ZeroTupIdx (_, v) = Just v cvtP (SuccTupIdx idx) (tup, _) = cvtP idx tup cvtT :: TupleIdx t e -> Tuple (OpenExp env aenv) t -> Maybe e cvtT ZeroTupIdx (SnocTup _ e) = cvtE e cvtT (SuccTupIdx idx) (SnocTup tup _) = cvtT idx tup cvtT _ _ = error "hey what's the head angle on that thing?" -- Attempt to evaluate primitive function applications -- evalPrimApp :: forall env aenv a r. (Elt a, Elt r) => Gamma env env aenv -> PrimFun (a -> r) -> OpenExp env aenv a -> OpenExp env aenv r evalPrimApp env f x -- First attempt to move constant values towards the left | Just r <- commutes f x env = evalPrimApp env f r | Just r <- associates f x = r -- Now attempt to evaluate any expressions | otherwise = fromMaybe (PrimApp f x) $ case f of PrimAdd ty -> evalAdd ty x env PrimSub ty -> evalSub ty x env PrimMul ty -> evalMul ty x env PrimNeg ty -> evalNeg ty x env PrimAbs ty -> evalAbs ty x env PrimSig ty -> evalSig ty x env PrimQuot ty -> evalQuot ty x env PrimRem ty -> evalRem ty x env PrimIDiv ty -> evalIDiv ty x env PrimMod ty -> evalMod ty x env PrimBAnd ty -> evalBAnd ty x env PrimBOr ty -> evalBOr ty x env PrimBXor ty -> evalBXor ty x env PrimBNot ty -> evalBNot ty x env PrimBShiftL ty -> evalBShiftL ty x env PrimBShiftR ty -> evalBShiftR ty x env PrimBRotateL ty -> evalBRotateL ty x env PrimBRotateR ty -> evalBRotateR ty x env PrimFDiv ty -> evalFDiv ty x env PrimRecip ty -> evalRecip ty x env PrimSin ty -> evalSin ty x env PrimCos ty -> evalCos ty x env PrimTan ty -> evalTan ty x env PrimAsin ty -> evalAsin ty x env PrimAcos ty -> evalAcos ty x env PrimAtan ty -> evalAtan ty x env PrimAsinh ty -> evalAsinh ty x env PrimAcosh ty -> evalAcosh ty x env PrimAtanh ty -> evalAtanh ty x env PrimExpFloating ty -> evalExpFloating ty x env PrimSqrt ty -> evalSqrt ty x env PrimLog ty -> evalLog ty x env PrimFPow ty -> evalFPow ty x env PrimLogBase ty -> evalLogBase ty x env PrimAtan2 ty -> evalAtan2 ty x env PrimTruncate ta tb -> evalTruncate ta tb x env PrimRound ta tb -> evalRound ta tb x env PrimFloor ta tb -> evalFloor ta tb x env PrimCeiling ta tb -> evalCeiling ta tb x env PrimLt ty -> evalLt ty x env PrimGt ty -> evalGt ty x env PrimLtEq ty -> evalLtEq ty x env PrimGtEq ty -> evalGtEq ty x env PrimEq ty -> evalEq ty x env PrimNEq ty -> evalNEq ty x env PrimMax ty -> evalMax ty x env PrimMin ty -> evalMin ty x env PrimLAnd -> evalLAnd x env PrimLOr -> evalLOr x env PrimLNot -> evalLNot x env PrimOrd -> evalOrd x env PrimChr -> evalChr x env PrimBoolToInt -> evalBoolToInt x env PrimFromIntegral ta tb -> evalFromIntegral ta tb x env -- Discriminate binary functions that commute, and if so return the operands in -- a stable ordering. If only one of the arguments is a constant, this is placed -- to the left of the operator. Returning Nothing indicates no change is made. -- commutes :: forall env aenv a r. (Elt a, Elt r) => PrimFun (a -> r) -> OpenExp env aenv a -> Gamma env env aenv -> Maybe (OpenExp env aenv a) commutes f x env = case f of PrimAdd _ -> swizzle x PrimMul _ -> swizzle x PrimBAnd _ -> swizzle x PrimBOr _ -> swizzle x PrimBXor _ -> swizzle x PrimEq _ -> swizzle x PrimNEq _ -> swizzle x PrimMax _ -> swizzle x PrimMin _ -> swizzle x PrimLAnd -> swizzle x PrimLOr -> swizzle x _ -> Nothing where swizzle :: OpenExp env aenv (b,b) -> Maybe (OpenExp env aenv (b,b)) swizzle (Tuple (NilTup `SnocTup` a `SnocTup` b)) | Nothing <- propagate env a , Just _ <- propagate env b = Just $ Tuple (NilTup `SnocTup` b `SnocTup` a) -- TLM: changing the ordering here when neither term can be reduced can be -- disadvantageous: for example in (x &&* y), the user might have put a -- simpler condition first that is designed to fail fast. -- -- | Nothing <- propagate env a -- , Nothing <- propagate env b -- , hashOpenExp a > hashOpenExp b -- = Just $ Tuple (NilTup `SnocTup` b `SnocTup` a) swizzle _ = Nothing -- Determine if successive applications of a binary operator will associate, and -- if so move them to the left. That is: -- -- a + (b + c) --> (a + b) + c -- -- Returning Nothing indicates no change is made. -- -- TLM: we might get into trouble here, as we've lost track of where the user -- has explicitly put parenthesis. -- associates :: (Elt a, Elt r) => PrimFun (a -> r) -> OpenExp env aenv a -> Maybe (OpenExp env aenv r) associates fun exp = case fun of PrimAdd _ -> swizzle fun exp [PrimAdd ty, PrimSub ty] PrimSub _ -> swizzle fun exp [PrimAdd ty, PrimSub ty] PrimLAnd -> swizzle fun exp [fun] PrimLOr -> swizzle fun exp [fun] _ -> swizzle fun exp [fun] where -- TODO: check the list of ops is complete (and correct) ty = undefined ops = [ PrimMul ty, PrimFDiv ty, PrimAdd ty, PrimSub ty, PrimBAnd ty, PrimBOr ty, PrimBXor ty ] swizzle :: (Elt a, Elt r) => PrimFun (a -> r) -> OpenExp env aenv a -> [PrimFun (a -> r)] -> Maybe (OpenExp env aenv r) swizzle f x lvl | Just REFL <- matches f ops , Just (a,bc) <- untup2 x , PrimApp g y <- bc , Just REFL <- matches g lvl , Just (b,c) <- untup2 y = Just $ PrimApp g (tup2 (PrimApp f (tup2 (a,b)), c)) swizzle _ _ _ = Nothing matches :: (Elt s, Elt t) => PrimFun (s -> a) -> [PrimFun (t -> a)] -> Maybe (s :=: t) matches _ [] = Nothing matches f (x:xs) | Just REFL <- matchPrimFun' f x = Just REFL | otherwise = matches f xs -- Helper functions -- ---------------- type a :-> b = forall env aenv. OpenExp env aenv a -> Gamma env env aenv -> Maybe (OpenExp env aenv b) eval1 :: Elt b => (a -> b) -> a :-> b eval1 f x env | Just a <- propagate env x = Just $ Const (fromElt (f a)) | otherwise = Nothing eval2 :: Elt c => (a -> b -> c) -> (a,b) :-> c eval2 f (untup2 -> Just (x,y)) env | Just a <- propagate env x , Just b <- propagate env y = Just $ Const (fromElt (f a b)) eval2 _ _ _ = Nothing tup2 :: (Elt a, Elt b) => (OpenExp env aenv a, OpenExp env aenv b) -> OpenExp env aenv (a, b) tup2 (a,b) = Tuple (NilTup `SnocTup` a `SnocTup` b) untup2 :: OpenExp env aenv (a, b) -> Maybe (OpenExp env aenv a, OpenExp env aenv b) untup2 exp | Tuple (NilTup `SnocTup` a `SnocTup` b) <- exp = Just (a, b) | otherwise = Nothing -- Methods of Num -- -------------- evalAdd :: Elt a => NumType a -> (a,a) :-> a evalAdd (IntegralNumType ty) | IntegralDict <- integralDict ty = evalAdd' evalAdd (FloatingNumType ty) | FloatingDict <- floatingDict ty = evalAdd' evalAdd' :: (Elt a, Eq a, Num a) => (a,a) :-> a evalAdd' (untup2 -> Just (x,y)) env | Just a <- propagate env x , a == 0 = Just y evalAdd' arg env = eval2 (+) arg env evalSub :: Elt a => NumType a -> (a,a) :-> a evalSub ty@(IntegralNumType ty') | IntegralDict <- integralDict ty' = evalSub' ty evalSub ty@(FloatingNumType ty') | FloatingDict <- floatingDict ty' = evalSub' ty evalSub' :: forall a. (Elt a, Eq a, Num a) => NumType a -> (a,a) :-> a evalSub' ty (untup2 -> Just (x,y)) env | Just b <- propagate env y , b == 0 = Just x | Nothing <- propagate env x , Just b <- propagate env y = Just $ evalPrimApp env (PrimAdd ty) (Tuple $ NilTup `SnocTup` Const (fromElt (-b)) `SnocTup` x) | Just REFL <- matchOpenExp x y = Just $ Const (fromElt (0::a)) -- TLM: definitely the purview of rewrite rules evalSub' _ arg env = eval2 (-) arg env evalMul :: Elt a => NumType a -> (a,a) :-> a evalMul (IntegralNumType ty) | IntegralDict <- integralDict ty = evalMul' evalMul (FloatingNumType ty) | FloatingDict <- floatingDict ty = evalMul' evalMul' :: (Elt a, Eq a, Num a) => (a,a) :-> a evalMul' (untup2 -> Just (x,y)) env | Just a <- propagate env x , Nothing <- propagate env y = case a of 0 -> Just x 1 -> Just y _ -> Nothing evalMul' arg env = eval2 (*) arg env evalNeg :: Elt a => NumType a -> a :-> a evalNeg (IntegralNumType ty) | IntegralDict <- integralDict ty = eval1 negate evalNeg (FloatingNumType ty) | FloatingDict <- floatingDict ty = eval1 negate evalAbs :: Elt a => NumType a -> a :-> a evalAbs (IntegralNumType ty) | IntegralDict <- integralDict ty = eval1 abs evalAbs (FloatingNumType ty) | FloatingDict <- floatingDict ty = eval1 abs evalSig :: Elt a => NumType a -> a :-> a evalSig (IntegralNumType ty) | IntegralDict <- integralDict ty = eval1 signum evalSig (FloatingNumType ty) | FloatingDict <- floatingDict ty = eval1 signum -- Methods of Integral & Bits -- -------------------------- evalQuot :: Elt a => IntegralType a -> (a,a) :-> a evalQuot ty | IntegralDict <- integralDict ty = eval2 quot evalRem :: Elt a => IntegralType a -> (a,a) :-> a evalRem ty | IntegralDict <- integralDict ty = eval2 rem evalIDiv :: Elt a => IntegralType a -> (a,a) :-> a evalIDiv ty | IntegralDict <- integralDict ty = evalIDiv' evalIDiv' :: (Elt a, Integral a, Eq a) => (a,a) :-> a evalIDiv' (untup2 -> Just (x,y)) env | Just 1 <- propagate env y = Just x evalIDiv' arg env = eval2 div arg env evalMod :: Elt a => IntegralType a -> (a,a) :-> a evalMod ty | IntegralDict <- integralDict ty = eval2 mod evalBAnd :: Elt a => IntegralType a -> (a,a) :-> a evalBAnd ty | IntegralDict <- integralDict ty = eval2 (.&.) evalBOr :: Elt a => IntegralType a -> (a,a) :-> a evalBOr ty | IntegralDict <- integralDict ty = eval2 (.|.) evalBXor :: Elt a => IntegralType a -> (a,a) :-> a evalBXor ty | IntegralDict <- integralDict ty = eval2 xor evalBNot :: Elt a => IntegralType a -> a :-> a evalBNot ty | IntegralDict <- integralDict ty = eval1 complement evalBShiftL :: Elt a => IntegralType a -> (a,Int) :-> a evalBShiftL ty | IntegralDict <- integralDict ty = eval2 shiftL evalBShiftR :: Elt a => IntegralType a -> (a,Int) :-> a evalBShiftR ty | IntegralDict <- integralDict ty = eval2 shiftR evalBRotateL :: Elt a => IntegralType a -> (a,Int) :-> a evalBRotateL ty | IntegralDict <- integralDict ty = eval2 rotateL evalBRotateR :: Elt a => IntegralType a -> (a,Int) :-> a evalBRotateR ty | IntegralDict <- integralDict ty = eval2 rotateR -- Methods of Fractional & Floating -- -------------------------------- evalFDiv :: Elt a => FloatingType a -> (a,a) :-> a evalFDiv ty | FloatingDict <- floatingDict ty = evalFDiv' evalFDiv' :: (Elt a, Fractional a, Eq a) => (a,a) :-> a evalFDiv' (untup2 -> Just (x,y)) env | Just 1 <- propagate env y = Just x evalFDiv' arg env = eval2 (/) arg env evalRecip :: Elt a => FloatingType a -> a :-> a evalRecip ty | FloatingDict <- floatingDict ty = eval1 recip evalSin :: Elt a => FloatingType a -> a :-> a evalSin ty | FloatingDict <- floatingDict ty = eval1 sin evalCos :: Elt a => FloatingType a -> a :-> a evalCos ty | FloatingDict <- floatingDict ty = eval1 cos evalTan :: Elt a => FloatingType a -> a :-> a evalTan ty | FloatingDict <- floatingDict ty = eval1 tan evalAsin :: Elt a => FloatingType a -> a :-> a evalAsin ty | FloatingDict <- floatingDict ty = eval1 asin evalAcos :: Elt a => FloatingType a -> a :-> a evalAcos ty | FloatingDict <- floatingDict ty = eval1 acos evalAtan :: Elt a => FloatingType a -> a :-> a evalAtan ty | FloatingDict <- floatingDict ty = eval1 atan evalAsinh :: Elt a => FloatingType a -> a :-> a evalAsinh ty | FloatingDict <- floatingDict ty = eval1 asinh evalAcosh :: Elt a => FloatingType a -> a :-> a evalAcosh ty | FloatingDict <- floatingDict ty = eval1 acosh evalAtanh :: Elt a => FloatingType a -> a :-> a evalAtanh ty | FloatingDict <- floatingDict ty = eval1 atanh evalExpFloating :: Elt a => FloatingType a -> a :-> a evalExpFloating ty | FloatingDict <- floatingDict ty = eval1 P.exp evalSqrt :: Elt a => FloatingType a -> a :-> a evalSqrt ty | FloatingDict <- floatingDict ty = eval1 sqrt evalLog :: Elt a => FloatingType a -> a :-> a evalLog ty | FloatingDict <- floatingDict ty = eval1 log evalFPow :: Elt a => FloatingType a -> (a,a) :-> a evalFPow ty | FloatingDict <- floatingDict ty = eval2 (**) evalLogBase :: Elt a => FloatingType a -> (a,a) :-> a evalLogBase ty | FloatingDict <- floatingDict ty = eval2 logBase evalAtan2 :: Elt a => FloatingType a -> (a,a) :-> a evalAtan2 ty | FloatingDict <- floatingDict ty = eval2 atan2 evalTruncate :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalTruncate ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 truncate evalRound :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalRound ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 round evalFloor :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalFloor ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 floor evalCeiling :: (Elt a, Elt b) => FloatingType a -> IntegralType b -> a :-> b evalCeiling ta tb | FloatingDict <- floatingDict ta , IntegralDict <- integralDict tb = eval1 ceiling -- Relational & Equality -- --------------------- evalLt :: ScalarType a -> (a,a) :-> Bool evalLt (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (<) evalLt (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (<) evalLt (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (<) evalGt :: ScalarType a -> (a,a) :-> Bool evalGt (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (>) evalGt (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (>) evalGt (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (>) evalLtEq :: ScalarType a -> (a,a) :-> Bool evalLtEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (<=) evalLtEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (<=) evalLtEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (<=) evalGtEq :: ScalarType a -> (a,a) :-> Bool evalGtEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (>=) evalGtEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (>=) evalGtEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (>=) evalEq :: ScalarType a -> (a,a) :-> Bool evalEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (==) evalEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (==) evalEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (==) evalNEq :: ScalarType a -> (a,a) :-> Bool evalNEq (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 (/=) evalNEq (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 (/=) evalNEq (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 (/=) evalMax :: Elt a => ScalarType a -> (a,a) :-> a evalMax (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 max evalMax (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 max evalMax (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 max evalMin :: Elt a => ScalarType a -> (a,a) :-> a evalMin (NumScalarType (IntegralNumType ty)) | IntegralDict <- integralDict ty = eval2 min evalMin (NumScalarType (FloatingNumType ty)) | FloatingDict <- floatingDict ty = eval2 min evalMin (NonNumScalarType ty) | NonNumDict <- nonNumDict ty = eval2 min -- Logical operators -- ----------------- evalLAnd :: (Bool,Bool) :-> Bool evalLAnd (untup2 -> Just (x,y)) env | Just a <- propagate env x = Just $ if a then y else Const (fromElt False) evalLAnd _ _ = Nothing evalLOr :: (Bool,Bool) :-> Bool evalLOr (untup2 -> Just (x,y)) env | Just a <- propagate env x = Just $ if a then Const (fromElt True) else y evalLOr _ _ = Nothing evalLNot :: Bool :-> Bool evalLNot = eval1 not evalOrd :: Char :-> Int evalOrd = eval1 ord evalChr :: Int :-> Char evalChr = eval1 chr evalBoolToInt :: Bool :-> Int evalBoolToInt = eval1 fromEnum evalFromIntegral :: Elt b => IntegralType a -> NumType b -> a :-> b evalFromIntegral ta (IntegralNumType tb) | IntegralDict <- integralDict ta , IntegralDict <- integralDict tb = eval1 fromIntegral evalFromIntegral ta (FloatingNumType tb) | IntegralDict <- integralDict ta , FloatingDict <- floatingDict tb = eval1 fromIntegral -- Scalar primitives -- ----------------- evalPrimConst :: PrimConst a -> a evalPrimConst (PrimMinBound ty) = evalMinBound ty evalPrimConst (PrimMaxBound ty) = evalMaxBound ty evalPrimConst (PrimPi ty) = evalPi ty evalMinBound :: BoundedType a -> a evalMinBound (IntegralBoundedType ty) | IntegralDict <- integralDict ty = minBound evalMinBound (NonNumBoundedType ty) | NonNumDict <- nonNumDict ty = minBound evalMaxBound :: BoundedType a -> a evalMaxBound (IntegralBoundedType ty) | IntegralDict <- integralDict ty = maxBound evalMaxBound (NonNumBoundedType ty) | NonNumDict <- nonNumDict ty = maxBound evalPi :: FloatingType a -> a evalPi ty | FloatingDict <- floatingDict ty = pi
robeverest/accelerate
Data/Array/Accelerate/Trafo/Algebra.hs
bsd-3-clause
20,751
0
16
5,884
7,578
3,652
3,926
384
54
module Lib.Task2 where import qualified Data.List as List task2 = sum $ filter isEven $ takeWhile (<4000000) fibs where fibs = List.unfoldr (\(a,b) -> Just (a,(b,a+b))) (0,1) isEven x = x `mod` 2 ==0
Austrotaxus/EulerProj
src/Lib/Task2.hs
bsd-3-clause
221
0
13
55
110
64
46
5
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Y.String ( YiString , Position , Size(..) , fromString, toString , toReverseString , fromLazyText, toLazyText , empty , singleton, null, length , append, concat , reverse , take, drop , takeScreenful , coordsOfPosition , coordsOfPositionWrappingToWidth , positionForCoords , cons, snoc , splitAt , splitAtLine , splitOnNewLines , wrappedLinesForWidth , countNewLines , insertAt , deleteAt , readFile, writeFile ) where import Prelude hiding (null, length, concat, splitAt, reverse, take, drop, lines , foldr, foldl , readFile, writeFile) import Control.Applicative hiding (empty) import Control.DeepSeq import Control.Lens hiding (cons, snoc, index) import Data.Binary import Data.Default import Data.Foldable (foldr, foldMap, toList) import Data.Int import Data.Monoid import qualified Data.Sequence as S import Data.String hiding (lines) import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.IO as TIO import qualified Data.Text.Lazy.Encoding as TE maxShortLineLength :: Int64 maxShortLineLength = 128 data Line = ShortLine TL.Text !Size | LongLine (S.Seq TL.Text) !Size deriving Show data YiString = YiString { fromYiString :: S.Seq Line , stringSize :: !Size } deriving Show mkLine :: TL.Text -> Line mkLine t = mkLine' t (Size (TL.length t)) mkLine' :: TL.Text -> Size -> Line mkLine' t (Size n) | n < maxShortLineLength = ShortLine t (Size n) mkLine' t size = LongLine (S.fromList $ map TL.fromStrict $ TL.toChunks t) size instance Monoid Line where mempty = ShortLine "" (Size 0) mappend (ShortLine l (Size lsize)) (ShortLine r (Size rsize)) | lsize + rsize <= maxShortLineLength = ShortLine (l <> r) (Size (lsize + rsize)) mappend (ShortLine l lsize) (ShortLine r rsize) = LongLine (S.fromList [l, r]) (lsize <> rsize) mappend (ShortLine l lsize) (LongLine rs rsize) = LongLine (l <| rs) (lsize <> rsize) mappend (LongLine ls lsize) (ShortLine r rsize) = LongLine (ls |> r) (lsize <> rsize) mappend (LongLine ls lsize) (LongLine rs rsize) = LongLine (ls <> rs) (lsize <> rsize) instance NFData Line where rnf (ShortLine t _) = rnf t rnf (LongLine chunks _) = rnf chunks instance NFData Size where rnf (Size i) = rnf i lineToLazyText :: Line -> TL.Text lineToLazyText (ShortLine t _) = t lineToLazyText (LongLine chunks _) = foldr mappend "" chunks instance Monoid YiString where mempty = "" mappend s (YiString _ (Size 0)) = s mappend (YiString _ (Size 0)) s = s mappend (YiString l sl) (YiString r sr) = YiString ((l' S.|> (lend <> rbegin)) <> r') (sl <> sr) where l' S.:> lend = S.viewr l rbegin S.:< r' = S.viewl r fromLazyText :: TL.Text -> YiString fromLazyText t = YiString (S.fromList $ map mkLine $ TL.splitOn "\n" t) (Size $ TL.length t) instance IsString YiString where fromString = fromLazyText . TL.pack instance Default YiString where def = mempty instance Eq YiString where lhs == rhs = stringSize lhs == stringSize rhs && toLazyText lhs == toLazyText rhs instance NFData YiString where rnf (YiString lines _) = rnf lines toLazyText :: YiString -> TL.Text toLazyText = TL.intercalate "\n" . foldr (mappend . return . lineToLazyText) [] . fromYiString toString :: YiString -> String toString = TL.unpack . toLazyText toReverseString :: YiString -> String toReverseString = toString . reverse type Position = Int64 -- | Size measured in characters, not bytes. newtype Size = Size { fromSize :: Int64 } deriving (Eq, Show, Ord) instance Monoid Size where mempty = Size 0 mappend (Size a) (Size b) = Size (a + b) singleton :: Char -> YiString singleton '\n' = YiString (S.fromList [mempty, mempty]) (Size 1) singleton c = YiString (S.singleton (ShortLine (TL.singleton c) (Size 1))) (Size 1) null :: YiString -> Bool null = TL.null . toLazyText empty :: YiString empty = mempty append :: YiString -> YiString -> YiString append = mappend concat :: [YiString] -> YiString concat = mconcat length :: YiString -> Size length (YiString _lines size) = size oneliner :: Line -> YiString oneliner l = YiString (S.singleton l) (lineSize l) findSplitBoundary :: Int64 -> S.Seq Line -> (Int64, Int) findSplitBoundary n64 = go 0 0 . toList where go !lengthAcc !index [] = (lengthAcc, index) go !lengthAcc !index (l:_) | lengthAcc + 1 + fromSize (lineSize l) > n64 = (lengthAcc, index) go !lengthAcc !index (l:ls) = go (lengthAcc + 1 + fromSize (lineSize l)) (succ index) ls splitAt :: Position -> YiString -> (YiString, YiString) splitAt n s | n <= 0 = (mempty, s) splitAt n s@(YiString _lines (Size size)) | fromIntegral n >= size = (s, mempty) splitAt n (YiString lines (Size size)) = (YiString leftLines (Size n64), YiString rightLines (Size (size - n64))) where n64 = fromIntegral n :: Int64 (positionAtStartOfBoundaryLine, boundaryLineIndex) = findSplitBoundary n64 lines mostlyLeftPart = S.take (succ boundaryLineIndex) lines strictlyRightPart = S.drop (succ boundaryLineIndex) lines strictlyLeftPart S.:> lastLeftLine = S.viewr mostlyLeftPart (leftLines, rightLines) = (strictlyLeftPart |> lineTake (n64 - positionAtStartOfBoundaryLine) lastLeftLine, lineDrop (n64 - positionAtStartOfBoundaryLine) lastLeftLine <| strictlyRightPart) splitAtLine :: Int64 -> YiString -> (YiString, YiString) splitAtLine 0 s = (mempty, s) splitAtLine i s@(YiString lines _) | fromIntegral i >= S.length lines = (s, mempty) splitAtLine i (YiString lines _) = ( YiString ls' (Size (fromIntegral i) <> foldMap lineSize ls') , YiString rs (Size (fromIntegral (S.length rs - 1)) <> foldMap lineSize rs) ) where ls = S.take (fromIntegral i) lines rs = S.drop (fromIntegral i) lines ls' = if S.length rs >= 1 || lineSize (ls ^. _last) > Size 0 then ls |> mempty else ls splitOnNewLines :: (Applicative f, Monoid (f YiString)) => YiString -> f YiString splitOnNewLines (YiString lines _) = foldMap go lines where go line = pure (YiString (S.singleton line) (lineSize line)) wrappedLinesForWidth :: (Applicative f, Monoid (f Line)) => Int64 -> YiString -> f YiString wrappedLinesForWidth w (YiString lines _) = oneliner <$> foldMap (lineSplitAtEvery w) lines countNewLines :: YiString -> Int64 countNewLines = pred . fromIntegral . S.length . fromYiString reverseLine :: Line -> Line reverseLine (ShortLine t size) = ShortLine (TL.reverse t) size reverseLine (LongLine chunks size) = LongLine (fmap TL.reverse (S.reverse chunks)) size reverse :: YiString -> YiString reverse (YiString lines size) = YiString (reverseLine <$> S.reverse lines) size take :: Int64 -> YiString -> YiString take n = fst . splitAt n takeScreenful :: Int64 -> Int64 -> YiString -> YiString takeScreenful w h (YiString _lines (Size size)) | w == 0 || h == 0 || size == 0 = mempty takeScreenful w h (YiString lines (Size size)) | headLineLength >= w * h = YiString (S.singleton (lineTake (w * h) headLine)) (Size (fromIntegral (w * h))) | h - headLineHeight > 0 = YiString (S.fromList [headLine, mempty]) (Size (fromIntegral (succ headLineLength))) <> takeScreenful w (h - headLineHeight) tailString | otherwise = YiString (S.singleton headLine) headLineSize where headLineHeight = max 1 (headLineLength `div` w + signum (headLineLength `rem` w)) headLineLength = fromIntegral $ fromSize headLineSize headLineSize = lineSize headLine (headLine, tailString) = case S.viewl lines of l S.:< tailLines -> (l, YiString tailLines (Size (size - 1 - fromIntegral headLineLength))) S.EmptyL -> error "lines can't be empty sequence." lineDrop :: Int64 -> Line -> Line lineDrop 0 l = l lineDrop n l | fromIntegral n >= fromSize (lineSize l) = mempty lineDrop n (ShortLine t (Size size)) = ShortLine (TL.drop (fromIntegral n) t) (Size (size - fromIntegral n)) lineDrop n l@(LongLine _chunks (Size size)) | size - fromIntegral n < maxShortLineLength = ShortLine (TL.drop (fromIntegral n) (lineToLazyText l)) (Size (size - fromIntegral n)) lineDrop n l@(LongLine _chunks (Size size)) = mkLine' (TL.drop (fromIntegral n) (lineToLazyText l)) (Size (size - fromIntegral n)) lineTake :: Int64 -> Line -> Line lineTake 0 _ = mempty lineTake n l | fromSize (lineSize l) < fromIntegral n = l lineTake n l = mkLine' (TL.take (fromIntegral n) (lineToLazyText l)) (Size (fromIntegral n)) lineSplitAtEvery :: (Applicative f, Monoid (f Line)) => Int64 -> Line -> f Line lineSplitAtEvery i l | fromSize (lineSize l) <= fromIntegral i = pure l lineSplitAtEvery i l = pure (lineTake i l) <> lineSplitAtEvery i (lineDrop i l) drop :: Int64 -> YiString -> YiString drop n = snd . splitAt n coordsOfPosition :: Position -> YiString -> (Int64, Int64) coordsOfPosition p s = coordsOfPositionWrappingToWidth p (fromSize (length s)) s coordsOfPositionWrappingToWidth :: Position -> Int64 -> YiString -> (Int64, Int64) coordsOfPositionWrappingToWidth pos w (YiString lines _) = go 0 (fromIntegral pos) (toList lines) where go !topOffset _p [] = (topOffset, 0) go !topOffset p (line : rest) = let lineLength = fromIntegral (fromSize (lineSize line)) in if p <= lineLength && p < w then (topOffset, p) else if p > lineLength then go (topOffset + max 1 (lineLength `div` w + signum (lineLength `rem` w))) (p - lineLength - 1) rest else (topOffset + p `div` w, p `rem` w) positionForCoords :: (Int64, Int64) -> YiString -> Position positionForCoords (y, x) s = fromIntegral x + fromSize (length (fst (splitAtLine y s))) lineSnoc :: Line -> Char -> Line lineSnoc (ShortLine t (Size size)) c | size > maxShortLineLength = LongLine (S.fromList [t, TL.singleton c]) (Size (succ size)) lineSnoc (ShortLine t (Size size)) c = ShortLine (t `TL.snoc` c) (Size (succ size)) lineSnoc (LongLine chunks (Size size)) c | TL.length (chunks ^. _last) >= maxShortLineLength = LongLine (chunks |> TL.singleton c) (Size (succ size)) lineSnoc (LongLine chunks (Size size)) c = LongLine (chunks & over _last (`TL.snoc` c)) (Size (succ size)) lineCons :: Char -> Line -> Line lineCons c (ShortLine t (Size size)) | size > maxShortLineLength = LongLine (S.fromList [TL.singleton c, t]) (Size (succ size)) lineCons c (ShortLine t (Size size)) = ShortLine (c `TL.cons` t) (Size (succ size)) lineCons c (LongLine chunks (Size size)) | TL.length (chunks ^. _head) >= maxShortLineLength = LongLine (TL.singleton c <| chunks) (Size (succ size)) lineCons c (LongLine chunks (Size size)) = LongLine (chunks & over _head (c `TL.cons`)) (Size (succ size)) lineSize :: Line -> Size lineSize (ShortLine _t size) = size lineSize (LongLine _chunks size) = size snoc :: YiString -> Char -> YiString snoc (YiString lines (Size size)) '\n' = YiString (lines |> mempty) (Size (succ size)) snoc (YiString lines (Size size)) c = YiString (lines & over _last (`lineSnoc` c)) (Size (succ size)) cons :: Char -> YiString -> YiString cons '\n' (YiString lines (Size size)) = YiString (mempty <| lines) (Size (succ size)) cons c (YiString lines (Size size)) = YiString (lines & over _head (c `lineCons`)) (Size (succ size)) insertAt :: YiString -> Position -> YiString -> YiString insertAt new pos old = oldLeft <> new <> oldRight where (oldLeft, oldRight) = splitAt pos old deleteAt :: Position -> Size -> YiString -> YiString deleteAt index (Size size) old = left <> right where (left, (_middle, right)) = splitAt size <$> splitAt index old readFile :: FilePath -> IO YiString readFile f = fromLazyText <$> TIO.readFile f writeFile :: FilePath -> YiString -> IO () writeFile f = TIO.writeFile f . toLazyText instance Binary YiString where get = fromLazyText . TE.decodeUtf8 <$> get put = put . TE.encodeUtf8 . toLazyText
ethercrow/y
src/Y/String.hs
bsd-3-clause
12,497
0
19
2,927
4,936
2,544
2,392
285
4
{-# LANGUAGE TemplateHaskell #-} module WithArity (main) where import Criterion.Main import Criterion.Types import Data.Monoid import Data.Syntactic hiding (E) import Data.Syntactic.Functional main :: IO () main = defaultMainWith (defaultConfig {csvFile = Just "bench-results/withArity.csv"}) [ bgroup "eval 5" [ bench "gadt" $ nf evl (gExpr 5) , bench "Syntactic" $ nf evalDen (sExpr 5) ] , bgroup "eval 6" [ bench "gadt" $ nf evl (gExpr 6) , bench "Syntactic" $ nf evalDen (sExpr 6) ] , bgroup "eval 7" [ bench "gadt" $ nf evl (gExpr 7) , bench "Syntactic" $ nf evalDen (sExpr 7) ] , bgroup "size 5" [ bench "gadt" $ nf gSize (gExpr 5) , bench "Syntactic" $ nf size (sExpr 5) ] , bgroup "size 6" [ bench "gadt" $ nf gSize (gExpr 6) , bench "Syntactic" $ nf size (sExpr 6) ] , bgroup "size 7" [ bench "gadt" $ nf gSize (gExpr 7) , bench "Syntactic" $ nf size (sExpr 7) ]] -- Expressions gExpr :: Int -> E Int gExpr 0 = E0 1 gExpr 1 = E2 (E2 (E0 1) (E0 1)) (E1 (E0 1)) gExpr n = E10 (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) (gExpr (n-1)) sExpr :: Int -> T' Int sExpr 0 = t0 1 sExpr 1 = t2 (t2 (t0 1) (t0 1)) (t1 (t0 1)) sExpr n = t10 (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) (sExpr (n-1)) gSize :: E a -> Int gSize (E0 _) = 1 gSize (E1 a) = gSize a gSize (E2 a b) = gSize a + gSize b gSize (E3 a b c) = gSize a + gSize b + gSize c gSize (E5 a b c d e) = gSize a + gSize b + gSize c + gSize d + gSize e gSize (E10 a b c d e f g h i j) = gSize a + gSize b + gSize c + gSize d + gSize e + gSize f + gSize g + gSize h + gSize i + gSize j -- Comparing Syntactic with GADTs -- GADTs data E a where E0 :: a -> E a E1 :: E a -> E a E2 :: E a -> E a -> E a E3 :: E a -> E a -> E a -> E a E5 :: E a -> E a -> E a -> E a -> E a -> E a E10 :: E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a -> E a evl :: E Int -> Int evl (E0 n) = n evl (E1 a) = evl a evl (E2 a b) = evl a + evl b evl (E3 a b c) = evl a + evl b + evl c evl (E5 a b c d e) = evl a + evl b + evl c + evl d + evl e evl (E10 a b c d e f g h i j) = evl a + evl b + evl c + evl d + evl e + evl f + evl g + evl h + evl i + evl j -- Syntactic data T a where T0 :: Num a => a -> T (Full a) T1 :: Num a => T (a :-> Full a) T2 :: Num a => T (a :-> a :-> Full a) T3 :: Num a => T (a :-> a :-> a :-> Full a) T5 :: Num a => T (a :-> a :-> a :-> a :-> a :-> Full a) T10 :: Num a => T (a :-> a :-> a :-> a :-> a :-> a :-> a :-> a :-> a :-> a :-> Full a) type T' a = AST T (Full a) t0 :: Num a => a -> T' a t0 = Sym . T0 t1 :: Num a => T' a -> T' a t1 a = Sym T1 :$ a t2 :: Num a => T' a -> T' a -> T' a t2 a b = Sym T2 :$ a :$ b t3 :: Num a => T' a -> T' a -> T' a -> T' a t3 a b c = Sym T3 :$ a :$ b :$ c t5 :: Num a => T' a -> T' a -> T' a -> T' a -> T' a -> T' a t5 a b c d e = Sym T5 :$ a :$ b :$ c :$ d :$ e t10 :: Num a => T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a -> T' a t10 a b c d e f g h i j = Sym T10 :$ a :$ b :$ c :$ d :$ e :$ f :$ g :$ h :$ i:$ j instance Render T where renderSym (T0 a) = "T0" renderSym T1 = "T1" renderSym T2 = "T2" renderSym T3 = "T3" renderSym T5 = "T5" renderSym T10 = "T10" interpretationInstances ''T instance Eval T where evalSym (T0 a) = a evalSym T1 = id evalSym T2 = (+) evalSym T3 = \a b c -> a + b + c evalSym T5 = \a b c d e -> a + b + c + d + e evalSym T10 = \a b c d e f g h i j -> a + b + c + d + e + f + g + h + i + j instance EvalEnv T env where compileSym p (T0 a) = compileSymDefault p (T0 a) compileSym p T1 = compileSymDefault p T1 compileSym p T2 = compileSymDefault p T2 compileSym p T3 = compileSymDefault p T3 compileSym p T5 = compileSymDefault p T5 compileSym p T10 = compileSymDefault p T10
emwap/syntactic
benchmarks/WithArity.hs
bsd-3-clause
4,415
0
18
1,623
2,557
1,241
1,316
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoStarIsType #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} module Numeric.Wavelet.Continuous ( -- * Continuous Wavelet Transform CWD(..), mapCWD , CWDLine(..), mapCWDLine , LNorm(..), CWDOpts(..), defaultCWDO , cwd , cwdReal -- * Wavelets , AWavelet(..), mapAWavelet , morlet, morletFunc , meyer, meyerFunc , fbsp, fbspFunc ) where import Data.Complex import Data.Finite import Data.Foldable import Data.Maybe import Data.Ord import Data.Proxy import Data.Type.Equality import Data.Vector.Generic.Sized (Vector) import GHC.Generics (Generic) import GHC.TypeLits.Compare import GHC.TypeNats import Math.FFT.Base import Numeric.Wavelet.Internal.FFT import qualified Data.Vector.Generic as UVG import qualified Data.Vector.Generic.Sized as VG import qualified Data.Vector.Sized as V newtype CWD v n m a b = CWD { cwdLines :: V.Vector m (CWDLine v n a b) } deriving (Show, Functor) data CWDLine v n a b = CWDLine { cwdlData :: Vector v n b , cwdlScale :: Finite (n `Div` 2 + 1) -- ^ Scale factor, in number of ticks. , cwdlFreq :: a -- ^ The frequency associated with this scale, in inverse tick , cwdlCoI :: Finite (n `Div` 2 + 1) -- ^ How many items are /outside/ of the Cone of Influence, on each side. } deriving (Show, Functor) mapCWDLine :: (UVG.Vector v b, UVG.Vector v c) => (b -> c) -> CWDLine v n a b -> CWDLine v n a c mapCWDLine f (CWDLine d s q c) = CWDLine (VG.map f d) s q c mapCWD :: (UVG.Vector v b, UVG.Vector v c) => (b -> c) -> CWD v n m a b -> CWD v n m a c mapCWD f (CWD l) = CWD (mapCWDLine f <$> l) data LNorm = L1 | L2 deriving (Show, Eq, Ord, Enum, Bounded, Generic) data CWDOpts n = CWDO { cwdoNorm :: LNorm -- ^ wavelet normalization , cwdoMinScale :: Finite (n `Div` 2 + 1) -- ^ min scale (period) , cwdoMaxScale :: Finite (n `Div` 2 + 1) -- ^ max scale (period) } deriving (Show, Eq, Ord, Generic) defaultCWDO :: KnownNat n => CWDOpts n defaultCWDO = CWDO { cwdoNorm = L2 , cwdoMinScale = minBound , cwdoMaxScale = maxBound } -- | 'cwd' for complex-valued analytic wavelets. cwd :: forall v n m a b. ( UVG.Vector v (Complex b) , KnownNat n , KnownNat m , FFTWReal b , 1 <= n , RealFloat a ) => AWavelet v a (Complex b) -> CWDOpts n -> Vector v n (Complex b) -> CWD v n m a (Complex b) cwd AW{..} CWDO{..} xs = CWD . VG.generate $ \i -> let s = scaleOf i dt = 1/s in case awVector dt of VG.SomeSized (wv :: Vector v q (Complex b)) | Just Refl <- isLE (Proxy @1) (Proxy @q) , Just Refl <- isLE (Proxy @((q-1)`Div`2)) (Proxy @(q-1)) -> let ys :: Vector v (n + q - 1) (Complex b) ys = (* (realToFrac (normie dt) :+ 0)) `VG.map` convolve xs wv coi = fromMaybe maxBound . packFinite . round @a @Integer $ sqrt 2 * s s' = fromMaybe maxBound . packFinite . round @a @Integer $ s ys' :: Vector v n (Complex b) ys' = VG.slice @_ @((q - 1)`Div`2) @n @((q-1)-((q-1)`Div`2)) Proxy ys in CWDLine ys' s' (awFreq / s) coi _ -> error "Bad scale: wavelet vector is empty?" where n = natVal (Proxy @n) m = natVal (Proxy @m) normie :: a -> a normie = case cwdoNorm of L1 -> sqrt L2 -> id minScale = fromIntegral cwdoMinScale `max` 1 maxScale = (fromIntegral cwdoMaxScale `min` (fromIntegral n / (2 * sqrt 2))) `max` (minScale + 1) scaleStep = (log maxScale - log minScale) / (fromIntegral m - 1) scaleOf :: Finite m -> a scaleOf i = exp $ log minScale + fromIntegral i * scaleStep -- | 'cwd' for real-valued analytic wavelets. cwdReal :: forall v n m a b. ( UVG.Vector v b , UVG.Vector v (Complex b) , KnownNat n , KnownNat m , FFTWReal b , 1 <= n , RealFloat a ) => AWavelet v a b -> CWDOpts n -> Vector v n b -> CWD v n m a b cwdReal aw cwdo = mapCWD realPart . cwd (mapAWavelet (:+ 0) aw) cwdo . VG.map (:+ 0) -- | Analytical Wavelet data AWavelet v a b = AW { awVector :: a -> v b -- ^ generate a vector within awRange with a given dt , awFreq :: a -- ^ Dominant frequency component , awRange :: a -- ^ range away from zero outside of which wavelet can be considered negligible } deriving Functor mapAWavelet :: (UVG.Vector v b, UVG.Vector v c) => (b -> c) -> AWavelet v a b -> AWavelet v a c mapAWavelet f (AW v q r) = AW (UVG.map f . v) q r morlet :: (UVG.Vector v (Complex a), RealFloat a) => a -> AWavelet v a (Complex a) morlet σ = AW{..} where awRange = 4 (!awFreq, mf) = morletFunc_ σ awVector = renderFunc awRange mf morletFunc :: RealFloat a => a -> a -> Complex a morletFunc = snd . morletFunc_ morletFunc_ :: RealFloat a => a -> (a, a -> Complex a) morletFunc_ σ = (q, f) where f t = (c * exp(-t*t/2) :+ 0) * (exp (0 :+ (σ * t)) - (exp (-σ2/2) :+ 0)) !c = pi ** (-1/4) * (1 + exp (-σ2) - 2 * exp (-3/4*σ2)) ** (-1/2) !σ2 = σ * σ !q = converge 20 iter σ / (2 * pi) iter w = σ / (1 - exp (-σ * w)) meyer :: (UVG.Vector v a, RealFloat a) => AWavelet v a a meyer = AW{..} where awRange = 6 awVector = renderFunc awRange meyerFunc awFreq = 4 * pi / 3 meyerFunc :: RealFloat a => a -> a meyerFunc t | isNaN ψ || isInfinite ψ = 0 | otherwise = ψ where t' = t - 0.5 t'3 = t'**3 sinTerm = sin(4*pi/3*t') / pi ψ1 = (4/3/pi*t'*cos(2*pi/3*t') - sinTerm) / (t' - 16/9 * t'3) ψ2 = (8/3/pi*t'*cos(8*pi/3*t') + sinTerm) / (t' - 64/9 * t'3) ψ = ψ1 + ψ2 fbsp :: (UVG.Vector v (Complex a), FFTWReal a) => Int -- ^ m, >= 1 -> a -- ^ f_b, bandwidth -> a -- ^ f_c, wavelet center frequency -> AWavelet v a (Complex a) fbsp m fb fc = AW{..} where awRange = 4/fb awVector = renderFunc awRange (fbspFunc m fb fc) awFreq = autoDeriveFreq awRange awVector autoDeriveFreq :: (UVG.Vector v (Complex a), FFTWReal a) => a -> (a -> v (Complex a)) -> a autoDeriveFreq r fv = case fv 0.001 of VG.SomeSized v -> let vv = zip [1..] . map magnitude . VG.toList $ fft v (i,_) = maximumBy (comparing snd) vv in fromInteger i / (r * 2) _ -> error "bad vector" fbspFunc :: RealFloat a => Int -> a -> a -> a -> Complex a fbspFunc m fb fc t = ((sqrt fb * sinc (fb * t / fromIntegral m))^m :+ 0) * exp (0 :+ (2 * pi * fc * t)) where sinc x = sin x / x -- | Render the effective range of a wavelet (based on 'awRange'), centered -- around zero. Takes a timestep. renderFunc :: (UVG.Vector v b, RealFrac a) => a -- ^ range about zero -> (a -> b) -- ^ func -> a -- ^ dt -> v b renderFunc r f dt = UVG.generate (round n) $ \i -> f (fromIntegral i * dt - r) where n = r * 2 / dt converge :: (Fractional a, Ord a) => Int -- ^ maximum iterations -> (a -> a) -- ^ function to find the fixed point convergence -> a -- ^ starting value -> a converge n f = go 0 where go !i !x | i >= n = 0 | abs (x - y) < 0.00001 = x | otherwise = go (i + 1) y where !y = f x
mstksg/wavelets
src/Numeric/Wavelet/Continuous.hs
bsd-3-clause
8,823
0
24
3,159
3,142
1,672
1,470
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module VForth.GameTextSpec ( TestableTitle(..) , TestableDescription(..) , unsafeRight , spec ) where import Test.Hspec import Test.QuickCheck.Gen import Test.QuickCheck import Data.Monoid ((<>)) import Data.Text.Arbitrary () import Data.Text (Text) import qualified Data.Text as Text import Control.Monad import VForth.GameText import Data.Text.Validation unsafeRight :: Show l => Either l r -> r unsafeRight (Right r) = r unsafeRight (Left l) = error ("Unexpectedly encountered left-value " <> show l) -- | Creates a generator for wrapped text-types that fulfills its constraints arbitraryFromConstraints :: ValidationConstraints -- ^ Provide minimum and maximum length, and regex -> Maybe String -- ^ Provides the list of valid chars. All are valid if Nothing -> (Text -> a) -- ^ A function to wrap the generated text in a newtype -> Gen a arbitraryFromConstraints ValidationConstraints{..} validChars makeFn = let validCharsGen = maybe arbitrary elements validChars validSubSeqGen = choose (vconsMinLength, vconsMaxLength) >>= \count -> replicateM count validCharsGen validTextGen = Text.pack <$> validSubSeqGen in makeFn <$> validTextGen newtype TestableTitle = TestableTitle Title deriving Show instance Arbitrary TestableTitle where arbitrary = arbitraryFromConstraints titleConstraints (Just titleChars) (TestableTitle . unsafeRight . title) newtype TestableDescription = TestableDescription Description deriving Show instance Arbitrary TestableDescription where arbitrary = arbitraryFromConstraints descriptionConstraints (Just descriptionChars) (TestableDescription . unsafeRight . description) spec :: Spec spec = return ()
budgefeeney/ventureforth
chap6/test/VForth/GameTextSpec.hs
bsd-3-clause
1,846
0
11
358
387
216
171
48
1
{-# LANGUAGE GADTs, NoImplicitPrelude, UnicodeSyntax #-} module Data.Nested.Tree ( -- * Tree type Tree (..) -- * Query , fruit, forest , null, size , lookup, member -- * Construction , empty , singleton , fromFoldable , fromList -- * List , toList -- * Utils , unionTree , unionTreeWithKey , unionTreeWithKey' , unionTreeWith , apTree , foldrTreeWithAncestors1 , foldrTreeWithAncestorsAndLeafMarker1 ) where import Data.Function (flip) import Data.Maybe (Maybe) import Data.Ord (Ord) import Data.Int (Int) import Data.Bool (Bool) import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Data.Nested.Internal ( Tree (..) , nullTree, fruit, forest , sizeTree , emptyTree , singletonTree , fromFoldableTree , fromListTree , toListTree , lookupTree , memberTree , unionTree , unionTreeWithKey , unionTreeWithKey' , unionTreeWith , apTree , foldrTreeWithAncestors1 , foldrTreeWithAncestorsAndLeafMarker1 ) empty ∷ α → Tree κ α empty = emptyTree null ∷ Tree κ α → Bool null = nullTree size ∷ Tree κ α → Int size = sizeTree lookup ∷ (Traversable φ, Ord κ) ⇒ φ κ → Tree κ α → (α, φ (Maybe α)) lookup = flip lookupTree member ∷ (Traversable φ, Ord κ) ⇒ φ κ → Tree κ α → φ Bool member = flip memberTree singleton ∷ Foldable φ ⇒ α → φ (κ,α) → Tree κ α singleton = singletonTree fromFoldable ∷ (Foldable φ, Foldable ψ, Ord κ) ⇒ α → ψ (φ (κ, α)) → Tree κ α fromFoldable = fromFoldableTree fromList ∷ (Ord κ) ⇒ α → [[(κ, α)]] → Tree κ α fromList = fromListTree toList ∷ Tree κ α → (α, [[(κ, α)]]) toList = toListTree
sheganinans/applicative-nestedmap
src/Data/Nested/Tree.hs
bsd-3-clause
2,283
0
11
914
557
322
235
61
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ConstrainedClassMethods #-} {-# LANGUAGE OverloadedStrings #-} -- We can do better syntactically! module MLModulesWithFunctors2 where import Prelude hiding (Monoid, mempty) import GHC.TypeLits class Module m where proof :: m data M (x :: Symbol) = M instance Module (M a) where proof = M class Module m => Monoid m where type T m :: * (<>) :: (?m :: m) => T m -> T m -> T m mempty :: (?m :: m) => T m instance Monoid (M "Add") where type T (M "Add") = Int (<>) = (+) mempty = 0 instance Monoid (M "Mul") where type T (M "Mul") = Int (<>) = (*) mempty = 1 class (Monoid (Additive m), Monoid (Multiplicative m)) => Semiring m where type Additive m type Multiplicative m plus :: (?m :: m) => T (Additive m) -> T (Additive m) -> T (Additive m) plus = (<>) where ?m = proof :: Additive m mul :: (?m :: m) => T (Multiplicative m) -> T (Multiplicative m) -> T (Multiplicative m) mul = (<>) where ?m = proof :: Multiplicative m zero :: (?m :: m) => T (Additive m) zero = (mempty) where ?m = proof :: Additive m one :: (?m :: m) => T (Multiplicative m) one = (mempty) where ?m = proof :: Multiplicative m instance Semiring (M "Natural")where type Additive (M "Natural") = M "Add" type Multiplicative (M "Natural") = M "Mul" foo :: Int foo = plus (mul 10 10) 100 where ?m = M @ "Natural"
sleexyz/haskell-fun
MLModulesWithFunctors2.hs
bsd-3-clause
1,635
0
12
400
592
331
261
49
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} module Foreign.HPX.Types where import Bindings.HPX import Control.Applicative (Alternative) import Control.Monad (MonadPlus) import Control.Monad.Fix (MonadFix) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Reader (ReaderT(..), ask, asks) import Data.Binary (Binary) import Data.Ix (Ix) import Data.Map (Map) import Data.Proxy (Proxy(..)) import Foreign import GHC.Show (appPrec, appPrec1) import GHC.StaticPtr (StaticKey, StaticPtr, staticKey, staticPtrInfo) import System.IO.Unsafe (unsafePerformIO) import Text.Printf (PrintfArg) class C c h where fromC :: c -> h toC :: h -> c newtype HPX a = HPX { unHPX :: ReaderT ActionEnv IO a } deriving ( Alternative , Applicative , Functor , Monad , MonadFix , MonadIO , MonadPlus ) askHPX :: HPX ActionEnv askHPX = HPX ask asksHPX :: (ActionEnv -> a) -> HPX a asksHPX = HPX . asks -- Unsafe runHPX :: ActionEnv -> HPX a -> IO a runHPX env (HPX hpx) = runReaderT hpx env newtype ActionEnv = ActionEnv { unActionEnv :: Map StaticKey (Ptr Action) } deriving ( Eq , Ord , Show ) newtype Action = Action { unAction :: C'hpx_action_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) data ActionSpec where ActionSpec :: Binary a => ActionType -> StaticPtr (a -> HPX r) -> ActionSpec instance Eq ActionSpec where ActionSpec _ sp1 == ActionSpec _ sp2 = staticKey sp1 == staticKey sp2 instance Ord ActionSpec where compare (ActionSpec _ sp1) (ActionSpec _ sp2) = compare (staticKey sp1) (staticKey sp2) instance Show ActionSpec where showsPrec p (ActionSpec _ sp) = showParen (p > appPrec) $ showString "ActionSpec " . showsPrec appPrec1 (staticPtrInfo sp) data ActionType = Default | Task | Interrupt | Function | OpenCL deriving ( Bounded , Enum , Eq , Ix , Ord , Read , Show ) instance C C'hpx_action_type_t ActionType where fromC v | v == C'HPX_DEFAULT = Default | v == C'HPX_TASK = Task | v == C'HPX_INTERRUPT = Interrupt | v == C'HPX_FUNCTION = Function | v == C'HPX_OPENCL = OpenCL | otherwise = error $ "C C'hpx_action_type_t ActionType error fromC: " ++ show v toC Default = C'HPX_DEFAULT toC Task = C'HPX_TASK toC Interrupt = C'HPX_INTERRUPT toC Function = C'HPX_FUNCTION toC OpenCL = C'HPX_OPENCL type ActionAttribute = Word32 pattern NoAttribute :: ActionAttribute pattern NoAttribute = C'HPX_ATTR_NONE pattern Marshalled :: ActionAttribute pattern Marshalled = C'HPX_MARSHALLED pattern Pinned :: ActionAttribute pattern Pinned = C'HPX_PINNED pattern Internal :: ActionAttribute pattern Internal = C'HPX_INTERNAL pattern Vectored :: ActionAttribute pattern Vectored = C'HPX_VECTORED pattern Coalesced :: ActionAttribute pattern Coalesced = C'HPX_COALESCED pattern Compressed :: ActionAttribute pattern Compressed = C'HPX_COMPRESSED pattern NullAction :: Action pattern NullAction <- ((== Action c'HPX_ACTION_NULL) -> True) where NullAction = Action c'HPX_ACTION_NULL pattern Invalid :: Action pattern Invalid <- ((== Action c'HPX_ACTION_INVALID) -> True) where Invalid = Action c'HPX_ACTION_INVALID newtype Address = Address { unAddress :: C'hpx_addr_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) here :: Address here = unsafePerformIO (Address <$> peek p'HPX_HERE) {-# NOINLINE here #-} pattern Here :: Address pattern Here <- ((== here) -> True) where Here = here newtype LCO r = LCO { unLCO :: C'hpx_addr_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) pattern NullLCO :: LCO r pattern NullLCO <- ((== LCO c'HPX_NULL) -> True) where NullLCO = LCO c'HPX_NULL newtype Status = Status { unStatus :: C'hpx_status_t } deriving ( Bits , Bounded , Enum , Eq , FiniteBits , Integral , Ix , Num , Ord , PrintfArg , Read , Real , Show , Storable ) pattern Error :: Status pattern Error <- ((== Status c'HPX_ERROR) -> True) where Error = Status c'HPX_ERROR pattern Success :: Status pattern Success <- ((== Status c'HPX_SUCCESS) -> True) where Success = Status c'HPX_SUCCESS pattern Resend :: Status pattern Resend <- ((== Status c'HPX_RESEND) -> True) where Resend = Status c'HPX_RESEND pattern LCOError :: Status pattern LCOError <- ((== Status c'HPX_LCO_ERROR) -> True) where LCOError = Status c'HPX_LCO_ERROR pattern LCOChanEmpty :: Status pattern LCOChanEmpty <- ((== Status c'HPX_LCO_CHAN_EMPTY) -> True) where LCOChanEmpty = Status c'HPX_LCO_CHAN_EMPTY pattern LCOTimeout :: Status pattern LCOTimeout <- ((== Status c'HPX_LCO_TIMEOUT) -> True) where LCOTimeout = Status c'HPX_LCO_TIMEOUT pattern LCOReset :: Status pattern LCOReset <- ((== Status c'HPX_LCO_RESET) -> True) where LCOReset = Status c'HPX_LCO_RESET pattern ENoMem :: Status pattern ENoMem <- ((== Status c'HPX_ENOMEM) -> True) where ENoMem = Status c'HPX_ENOMEM pattern User :: Status pattern User <- ((== Status c'HPX_USER) -> True) where User = Status c'HPX_USER newtype Time = Time { unTime :: C'hpx_time_t } deriving ( Eq , Num , Ord , Read , Show , Storable ) type Promise = Proxy pattern Promise :: Promise a pattern Promise = Proxy
iu-parfunc/haskell-hpx
src/Foreign/HPX/Types.hs
bsd-3-clause
6,488
0
11
2,018
1,741
947
794
208
1
-- | Let's experiment with HUnit some more -- basicaly : <https://wiki.haskell.org/HUnit_1.0_User's_Guide> module TestStuff where import Test.HUnit import Stuff
emaphis/Haskell-Practice
testing-project/test/TestStuff.hs
bsd-3-clause
166
0
4
24
14
10
4
3
0
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Main (main) where import Control.Lens import Halytics.Metric import Halytics.Monitor import Test.Tasty import Test.Tasty.HUnit (testCase, (@=?)) main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [lastFive, periodOfThree, lens1] lastFive :: TestTree lastFive = testCase "Max |^ Last 5" $ Just 5 @=? res where monitor = generate :: Monitor (Max |^ Last 5) monitor' = foldl notify monitor entries entries = [32.0, 45, 33, 1, 2, 3, 4, 5] :: [Double] res = result monitor' :: Maybe Double periodOfThree :: TestTree periodOfThree = testCase "Max |^ PeriodOf 3" $ Just <$> [45, 3, 5] @=? res where monitor = generate :: Monitor (Max |^ PeriodOf 3) monitor' = foldl notify monitor entries entries = [32.0, 45, 33, 1, 2, 3, 4, 5] :: [Double] res = result monitor' :: [Maybe Double] -- lens1 :: TestTree lens1 = testCase "_1" $ Just 100 @=? res where monitor = generate :: Monitor TestC monitor' = foldl notify monitor entries monitor'' = monitor' & _1 %~ (`notify` 100) entries = [32.0, 45, 33, 1, 2, 3, 4, 5] :: [Double] res = monitor'' ^. _1 & result :: Maybe Double -- Test Monitor generation type TestA = Max type TestC = (Max, Max) type TestE = TestC type TestF = (TestE, TestC) _testA = generate :: Monitor TestA _testE = generate :: Monitor TestE _testF = generate :: Monitor TestF
nmattia/halytics
test/Test/Spec.hs
bsd-3-clause
1,502
0
10
320
512
298
214
39
1
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Zero.KeyFetchToken.Client where import GHC.TypeLits import GHCJS.Types (JSVal) import Control.Applicative import Data.Monoid ((<>)) import Data.Proxy import qualified Data.Text as T import Data.Text (Text) import Data.Maybe (isJust, fromJust) import Data.Either.Extra (eitherToMaybe) import Reflex.Dom.Core import Servant.Reflex import Servant.API hiding (addHeader) import Zero.KeyFetchToken.Internal import Zero.Token import Zero.Hawk (rawHeaderField, rawHeader) -- For clients with KeyFetchToken routes -- KnownSymbol path, instance (HasClient t m api tag, Reflex t) => HasClient t m (KeyFetchToken :> api) tag where -- The client passes a HeaderOptions encoded as a raw JSVal in -- order to bypass MonadIO. Not the nicest type for a Dynamically -- varying stream... type Client t m (KeyFetchToken :> api) tag = Dynamic t (Either Text (Text, Text, JSVal)) -> Client t m api tag clientWithRoute Proxy q t req baseUrl hawkOpts = do let opts = fmap fromJust $ fmap eitherToMaybe hawkOpts let params = zipDynWith (\url (path, method, opts) -> (url `T.append` path, method, opts)) (showBaseUrl <$> baseUrl) opts let field = fmap Right $ fmap rawHeaderField params clientWithRoute (Proxy :: Proxy api) q t (req' field) baseUrl where req' field = addHeader "Authorization" field req
et4te/zero
src/Zero/KeyFetchToken/Client.hs
bsd-3-clause
2,139
0
15
601
416
239
177
41
0
{-# LANGUAGE UndecidableInstances, FunctionalDependencies #-} module Feldspar.Multicore.Channel.Frontend where import Control.Monad.Operational.Higher import Control.Monad.Trans import Data.Ix import Data.Proxy import Data.Typeable import Feldspar hiding ((==)) import Feldspar.Data.Storable import Feldspar.Data.Vector hiding (ofLength, VecChanSizeSpec) import Feldspar.Multicore.CoreId import qualified Feldspar.Multicore.Channel.Representation as Rep import Feldspar.Multicore.Frontend import Feldspar.Multicore.Representation hiding (CoreId) import Feldspar.Representation import qualified Language.Embedded.Concurrent.CMD as Imp import qualified Language.Embedded.Expression as Imp import qualified Language.Embedded.Imperative as Imp -------------------------------------------------------------------------------- -- Channel interface -------------------------------------------------------------------------------- data CoreChan a where CoreChan :: CoreChanType a => SizeSpec a -> Rep.CoreChan (ElemType a) -> CoreChan a class PrimType (ElemType a) => CoreChanType a where type ElemType a :: * type SizeSpec a :: * newChan :: CoreId -> CoreId -> SizeSpec a -> Multicore (CoreChan a) class CoreChanType a => CoreTransferable' m a where type Slot a :: * newSlot :: CoreChan a -> m (Slot a) getSlot :: Slot a -> m a readChan :: CoreChan a -> Slot a -> m (Data Bool) writeChan :: CoreChan a -> a -> m (Data Bool) closeChan :: CoreChan a -> m () class CoreTransferType m a t | a -> t where toTransfer :: a -> m t fromTransfer :: t -> m a class (CoreTransferable' Host a, CoreTransferable' CoreComp a) => CoreTransferable a instance (CoreTransferable' Host a, CoreTransferable' CoreComp a) => CoreTransferable a one :: SizeSpec (Data a) one = () -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance PrimType a => CoreChanType (Data a) where type ElemType (Data a) = a type SizeSpec (Data a) = () newChan f t sz = Multicore $ fmap (CoreChan sz) $ singleInj $ Rep.NewChan f t 1 instance PrimType a => CoreTransferable' Host (Data a) where type Slot (Data a) = DArr a newSlot _ = newArr 1 getSlot s = getArr s 0 readChan (CoreChan _ c) = Host . readChanBuf' c 0 1 writeChan (CoreChan _ c) = lift . force >=> Host . writeChan' c closeChan (CoreChan _ c) = Host $ closeChan' c instance PrimType a => CoreTransferable' CoreComp (Data a) where type Slot (Data a) = DArr a newSlot _ = newArr 1 getSlot s = getArr s 0 readChan (CoreChan _ c) = CoreComp . readChanBuf' c 0 1 writeChan (CoreChan _ c) = lift . force >=> CoreComp . writeChan' c closeChan (CoreChan _ c) = CoreComp $ closeChan' c instance (Monad m, PrimType a) => CoreTransferType m (Data a) (Data a) where toTransfer = return fromTransfer = return instance PrimType a => CoreChanType (Store (DPull a)) where type ElemType (Store (DPull a)) = a type SizeSpec (Store (DPull a)) = Length newChan f t sz = Multicore $ fmap (CoreChan sz) $ singleInj $ Rep.NewChan f t sz instance PrimType a => CoreTransferable' Host (Store (DPull a)) where type Slot (Store (DPull a)) = Store (DPull a) newSlot (CoreChan l _) = newStore $ value l getSlot = return readChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef Host $ readChanBuf' c 0 l arr writeChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef Host $ writeChanBuf' c 0 l arr closeChan (CoreChan _ c) = Host $ closeChan' c instance PrimType a => CoreTransferable' CoreComp (Store (DPull a)) where type Slot (Store (DPull a)) = Store (DPull a) newSlot (CoreChan l _) = newStore $ value l getSlot = return readChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef CoreComp $ readChanBuf' c 0 l arr writeChan (CoreChan _ c) s@(Store (lenRef, arr)) = do l :: Data Length <- unsafeFreezeRef lenRef CoreComp $ writeChanBuf' c 0 l arr closeChan (CoreChan _ c) = CoreComp $ closeChan' c instance (Monad m, PrimType a) => CoreTransferType m (Store (DPull a)) (Store (DPull a)) where toTransfer = return fromTransfer = return instance (MonadComp m, PrimType a) => CoreTransferType m (DPull a) (Store (DPull a)) where toTransfer = initStore fromTransfer = unsafeFreezeStore instance (MonadComp m, PrimType a) => CoreTransferType m (DPush m a) (Store (DPull a)) where toTransfer (Push len dump) = do s@(Store (_, arr)) <- newStore len let write i v = setArr arr i v dump write return s fromTransfer (Store (lenRef, arr)) = do len <- getRef lenRef return $ Push len $ \write -> for (0, 1, Excl len) $ \i -> do v <- getArr arr i write i v instance (MonadComp m, PrimType a) => CoreTransferType m (DArr a) (Store (DPull a)) where toTransfer x = do lenRef <- initRef $ Feldspar.length x return $ Store (lenRef, x) fromTransfer (Store (_, arr)) = return arr -------------------------------------------------------------------------------- -- Representation wrappers -------------------------------------------------------------------------------- readChanBuf' :: ( Typeable a, pred a , Imp.FreeExp exp, Imp.FreePred exp Bool , Rep.CoreChanCMD :<: instr, Monad m ) => Rep.CoreChan a -> exp Index -- ^ Offset in array to start writing -> exp Index -- ^ Elements to read -> DArr a -> ProgramT instr (Param2 exp pred) m (exp Bool) readChanBuf' ch off sz arr = singleInj $ Rep.ReadChan ch off sz arr writeChan' :: ( Typeable a, pred a , Imp.FreeExp exp, Imp.FreePred exp Bool , Rep.CoreChanCMD :<: instr, Monad m ) => Rep.CoreChan a -> exp a -> ProgramT instr (Param2 exp pred) m (exp Bool) writeChan' c = singleInj . Rep.WriteOne c writeChanBuf' :: ( Typeable a, pred a , Imp.FreeExp exp, Imp.FreePred exp Bool , Rep.CoreChanCMD :<: instr, Monad m ) => Rep.CoreChan a -> exp Index -- ^ Offset in array to start reading -> exp Index -- ^ Elements to write -> DArr a -> ProgramT instr (Param2 exp pred) m (exp Bool) writeChanBuf' ch off sz arr = singleInj $ Rep.WriteChan ch off sz arr closeChan' :: (Rep.CoreChanCMD :<: instr) => Rep.CoreChan a -> ProgramT instr (Param2 exp pred) m () closeChan' = singleInj . Rep.CloseChan
kmate/raw-feldspar-mcs
src/Feldspar/Multicore/Channel/Frontend.hs
bsd-3-clause
6,955
0
15
1,768
2,411
1,223
1,188
-1
-1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE ImpredicativeTypes #-} module Hack.Handler.Hyena (run, runWithConfig, ServerConf(..)) where import qualified Hack as Hack import Hyena.Server import Network.Wai as Wai import Prelude hiding ((.), (^)) import System.IO import Control.Monad import Data.Default import Data.Maybe import Data.Char import Control.Applicative ((<$>)) import qualified Data.ByteString.Char8 as C import qualified Data.ByteString as S import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.Map as M import Control.Concurrent (forkIO) import Control.Concurrent.Chan (newChan,writeChan,getChanContents) (.) :: a -> (a -> b) -> b a . f = f a infixl 9 . -- | this won't change the port or servername for hyena, use -- ./main -p 3000 to configure port -- this just make sure port and serverName are presented in Env data ServerConf = ServerConf { port :: Int, serverName :: String } instance Default ServerConf where def = ServerConf { port = 3000, serverName = "localhost" } to_s :: S.ByteString -> String to_s = C.unpack to_b :: String -> S.ByteString to_b = C.pack both_to_s :: (S.ByteString, S.ByteString) -> (String, String) both_to_s (x,y) = (to_s x, to_s y) both_to_b :: (String, String) -> (S.ByteString, S.ByteString) both_to_b (x,y) = (to_b x, to_b y) hyena_env_to_hack_env :: ServerConf -> Environment -> IO Hack.Env hyena_env_to_hack_env conf e = do -- i <- (L.fromChunks <$> e.Wai.input .enumToList) return def { Hack.requestMethod = convertRequestMethod (e.requestMethod) , Hack.scriptName = e.scriptName.to_s , Hack.pathInfo = e.pathInfo.to_s , Hack.queryString = e.queryString .fromMaybe (to_b "") .to_s , Hack.http = e.Wai.headers .map both_to_s , Hack.hackErrors = e.errors , Hack.serverPort = conf.port , Hack.serverName = conf.serverName -- , Hack.hackInput = i } where convertRequestMethod Wai.Options = Hack.OPTIONS convertRequestMethod Wai.Get = Hack.GET convertRequestMethod Wai.Head = Hack.HEAD convertRequestMethod Wai.Post = Hack.POST convertRequestMethod Wai.Put = Hack.PUT convertRequestMethod Wai.Delete = Hack.DELETE convertRequestMethod Wai.Trace = Hack.TRACE convertRequestMethod Wai.Connect = Hack.CONNECT enumToList enum = do ch <- newChan _ <- forkIO $ enum (writer ch) () getChanContents ch where writer ch () chunk = do writeChan ch chunk return (Right ()) enum_string :: L.ByteString -> IO Enumerator enum_string msg = do let s = msg.L.unpack.to_b let yieldBlock f z = do z' <- f z s case z' of Left z'' -> return z'' Right z'' -> return z'' return yieldBlock type WaiResponse = (Int, S.ByteString, Wai.Headers, Enumerator) hack_response_to_hyena_response :: Enumerator -> Hack.Response -> WaiResponse hack_response_to_hyena_response e r = ( r.Hack.status , r.Hack.status.show_status_message.fromMaybe "OK" .to_b , r.Hack.headers.map both_to_b , e ) hack_to_wai_with_config :: ServerConf -> Hack.Application -> Wai.Application hack_to_wai_with_config conf app env = do hack_env <- env.hyena_env_to_hack_env conf r <- app hack_env enum <- r.Hack.body.enum_string let hyena_response = r.hack_response_to_hyena_response enum return hyena_response run :: Hack.Application -> IO () run app = runWithConfig def app runWithConfig :: ServerConf -> Hack.Application -> IO () runWithConfig conf app = app.hack_to_wai_with_config conf .serve show_status_message :: Int -> Maybe String show_status_message x = status_code.M.lookup x status_code :: M.Map Int String status_code = [ x 100 "Continue" , x 101 "Switching Protocols" , x 200 "OK" , x 201 "Created" , x 202 "Accepted" , x 203 "Non-Authoritative Information" , x 204 "No Content" , x 205 "Reset Content" , x 206 "Partial Content" , x 300 "Multiple Choices" , x 301 "Moved Permanently" , x 302 "Found" , x 303 "See Other" , x 304 "Not Modified" , x 305 "Use Proxy" , x 307 "Temporary Redirect" , x 400 "Bad Request" , x 401 "Unauthorized" , x 402 "Payment Required" , x 403 "Forbidden" , x 404 "Not Found" , x 405 "Method Not Allowed" , x 406 "Not Acceptable" , x 407 "Proxy Authentication Required" , x 408 "Request Timeout" , x 409 "Conflict" , x 410 "Gone" , x 411 "Length Required" , x 412 "Precondition Failed" , x 413 "Request Entity Too Large" , x 414 "Request-URI Too Large" , x 415 "Unsupported Media Type" , x 416 "Requested Range Not Satisfiable" , x 417 "Expectation Failed" , x 500 "Internal Server Error" , x 501 "Not Implemented" , x 502 "Bad Gateway" , x 503 "Service Unavailable" , x 504 "Gateway Timeout" , x 505 "HTTP Version Not Supported" ] .M.fromList where x a b = (a, b)
np/hack-handler-hyena
src/Hack/Handler/Hyena.hs
bsd-3-clause
5,627
15
19
1,795
1,464
776
688
132
8
{-# LANGUAGE BangPatterns #-} module LRUCache where import Control.Applicative ((<$>)) import Data.Hashable (Hashable, hash) import qualified Data.HashPSQ as HashPSQ import Data.IORef (IORef, newIORef, atomicModifyIORef') import Data.Int (Int64) import Data.Maybe (isNothing) import qualified Data.Vector as V import Prelude hiding (lookup) type Priority = Int64 data Cache k v = Cache { cCapacity :: !Int -- ^ The maximum number of elements in the queue , cSize :: !Int -- ^ The current number of elements in the queue , cTick :: !Priority -- ^ The next logical time , cQueue :: !(HashPSQ.HashPSQ k Priority v) } deriving (Eq, Show) empty :: Int -> Cache k v empty capacity | capacity < 1 = error "Cache.empty: capacity < 1" | otherwise = Cache { cCapacity = capacity , cSize = 0 , cTick = 0 , cQueue = HashPSQ.empty } trim :: (Hashable k, Ord k) => Cache k v -> Cache k v trim c | cTick c == maxBound = empty (cCapacity c) | cSize c > cCapacity c = c { cSize = cSize c - 1 , cQueue = HashPSQ.deleteMin (cQueue c) } | otherwise = c insert :: (Hashable k, Ord k) => k -> v -> Cache k v -> Cache k v insert key val c = trim $! let (mbOldVal, queue) = HashPSQ.insertView key (cTick c) val (cQueue c) in c { cSize = if isNothing mbOldVal then cSize c + 1 else cSize c , cTick = cTick c + 1 , cQueue = queue } lookup :: (Hashable k, Ord k) => k -> Cache k v -> Maybe (v, Cache k v) lookup k c = case HashPSQ.alter lookupAndBump k (cQueue c) of (Nothing, _) -> Nothing (Just x, q) -> let !c' = trim $ c {cTick = cTick c + 1, cQueue = q} in Just (x, c') where lookupAndBump Nothing = (Nothing, Nothing) lookupAndBump (Just (_, x)) = (Just x, Just ((cTick c), x))
Garygunn94/DFS
.stack-work/intero/intero2956XM1.hs
bsd-3-clause
1,997
0
16
666
715
384
331
56
3