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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="zh-CN">
<title>Support for the Open API Specification | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/openapi/src/main/javahelp/org/zaproxy/zap/extension/openapi/resources/help_zh_CN/helpset_zh_CN.hs | apache-2.0 | 1,000 | 80 | 66 | 164 | 423 | 214 | 209 | -1 | -1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.IndexUtils
-- Copyright : (c) Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Extra utils related to the package indexes.
-----------------------------------------------------------------------------
module Distribution.Client.IndexUtils (
getIndexFileAge,
getInstalledPackages,
getSourcePackages,
getSourcePackagesStrict,
convert,
readPackageIndexFile,
parsePackageIndex,
readRepoIndex,
updateRepoIndexCache,
updatePackageIndexCacheFile,
BuildTreeRefType(..), refTypeFromTypeCode, typeCodeFromRefType
) where
import qualified Distribution.Client.Tar as Tar
import Distribution.Client.Types
import Distribution.Package
( PackageId, PackageIdentifier(..), PackageName(..)
, Package(..), packageVersion, packageName
, Dependency(Dependency), InstalledPackageId(..) )
import Distribution.Client.PackageIndex (PackageIndex)
import qualified Distribution.Client.PackageIndex as PackageIndex
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
import qualified Distribution.PackageDescription.Parse as PackageDesc.Parse
import Distribution.PackageDescription
( GenericPackageDescription )
import Distribution.PackageDescription.Parse
( parsePackageDescription )
import Distribution.Simple.Compiler
( Compiler, PackageDBStack )
import Distribution.Simple.Program
( ProgramConfiguration )
import qualified Distribution.Simple.Configure as Configure
( getInstalledPackages )
import Distribution.ParseUtils
( ParseResult(..) )
import Distribution.Version
( Version(Version), intersectVersionRanges )
import Distribution.Text
( display, simpleParse )
import Distribution.Verbosity
( Verbosity, normal, lessVerbose )
import Distribution.Simple.Utils
( die, warn, info, fromUTF8 )
import Data.Char (isAlphaNum)
import Data.Maybe (mapMaybe, fromMaybe)
import Data.List (isPrefixOf)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid(..))
#endif
import qualified Data.Map as Map
import Control.Monad (MonadPlus(mplus), when, liftM)
import Control.Exception (evaluate)
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
import qualified Data.ByteString.Char8 as BSS
import Data.ByteString.Lazy (ByteString)
import Distribution.Client.GZipUtils (maybeDecompress)
import Distribution.Client.Utils ( byteStringToFilePath
, tryFindAddSourcePackageDesc )
import Distribution.Compat.Exception (catchIO)
import Distribution.Client.Compat.Time (getFileAge, getModTime)
import System.Directory (doesFileExist)
import System.FilePath ((</>), takeExtension, splitDirectories, normalise)
import System.FilePath.Posix as FilePath.Posix
( takeFileName )
import System.IO
import System.IO.Unsafe (unsafeInterleaveIO)
import System.IO.Error (isDoesNotExistError)
import Numeric (showFFloat)
getInstalledPackages :: Verbosity -> Compiler
-> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity comp packageDbs conf =
Configure.getInstalledPackages verbosity' comp packageDbs conf
where
--FIXME: make getInstalledPackages use sensible verbosity in the first place
verbosity' = lessVerbose verbosity
convert :: InstalledPackageIndex -> PackageIndex InstalledPackage
convert index' = PackageIndex.fromList
-- There can be multiple installed instances of each package version,
-- like when the same package is installed in the global & user DBs.
-- InstalledPackageIndex.allPackagesBySourcePackageId gives us the
-- installed packages with the most preferred instances first, so by
-- picking the first we should get the user one. This is almost but not
-- quite the same as what ghc does.
[ InstalledPackage ipkg (sourceDeps index' ipkg)
| (_,ipkg:_) <- InstalledPackageIndex.allPackagesBySourcePackageId index' ]
where
-- The InstalledPackageInfo only lists dependencies by the
-- InstalledPackageId, which means we do not directly know the corresponding
-- source dependency. The only way to find out is to lookup the
-- InstalledPackageId to get the InstalledPackageInfo and look at its
-- source PackageId. But if the package is broken because it depends on
-- other packages that do not exist then we have a problem we cannot find
-- the original source package id. Instead we make up a bogus package id.
-- This should have the same effect since it should be a dependency on a
-- nonexistent package.
sourceDeps index ipkg =
[ maybe (brokenPackageId depid) packageId mdep
| let depids = InstalledPackageInfo.depends ipkg
getpkg = InstalledPackageIndex.lookupInstalledPackageId index
, (depid, mdep) <- zip depids (map getpkg depids) ]
brokenPackageId (InstalledPackageId str) =
PackageIdentifier (PackageName (str ++ "-broken")) (Version [] [])
------------------------------------------------------------------------
-- Reading the source package index
--
-- | Read a repository index from disk, from the local files specified by
-- a list of 'Repo's.
--
-- All the 'SourcePackage's are marked as having come from the appropriate
-- 'Repo'.
--
-- This is a higher level wrapper used internally in cabal-install.
--
getSourcePackages :: Verbosity -> [Repo] -> IO SourcePackageDb
getSourcePackages verbosity repos = getSourcePackages' verbosity repos
ReadPackageIndexLazyIO
-- | Like 'getSourcePackages', but reads the package index strictly. Useful if
-- you want to write to the package index after having read it.
getSourcePackagesStrict :: Verbosity -> [Repo] -> IO SourcePackageDb
getSourcePackagesStrict verbosity repos = getSourcePackages' verbosity repos
ReadPackageIndexStrict
-- | Common implementation used by getSourcePackages and
-- getSourcePackagesStrict.
getSourcePackages' :: Verbosity -> [Repo] -> ReadPackageIndexMode
-> IO SourcePackageDb
getSourcePackages' verbosity [] _mode = do
warn verbosity $ "No remote package servers have been specified. Usually "
++ "you would have one specified in the config file."
return SourcePackageDb {
packageIndex = mempty,
packagePreferences = mempty
}
getSourcePackages' verbosity repos mode = do
info verbosity "Reading available packages..."
pkgss <- mapM (\r -> readRepoIndex verbosity r mode) repos
let (pkgs, prefs) = mconcat pkgss
prefs' = Map.fromListWith intersectVersionRanges
[ (name, range) | Dependency name range <- prefs ]
_ <- evaluate pkgs
_ <- evaluate prefs'
return SourcePackageDb {
packageIndex = pkgs,
packagePreferences = prefs'
}
-- | Read a repository index from disk, from the local file specified by
-- the 'Repo'.
--
-- All the 'SourcePackage's are marked as having come from the given 'Repo'.
--
-- This is a higher level wrapper used internally in cabal-install.
--
readRepoIndex :: Verbosity -> Repo -> ReadPackageIndexMode
-> IO (PackageIndex SourcePackage, [Dependency])
readRepoIndex verbosity repo mode =
let indexFile = repoLocalDir repo </> "00-index.tar"
cacheFile = repoLocalDir repo </> "00-index.cache"
in handleNotFound $ do
warnIfIndexIsOld =<< getIndexFileAge repo
whenCacheOutOfDate indexFile cacheFile $ do
updatePackageIndexCacheFile verbosity indexFile cacheFile
readPackageIndexCacheFile mkAvailablePackage indexFile cacheFile mode
where
mkAvailablePackage pkgEntry =
SourcePackage {
packageInfoId = pkgid,
packageDescription = packageDesc pkgEntry,
packageSource = case pkgEntry of
NormalPackage _ _ _ _ -> RepoTarballPackage repo pkgid Nothing
BuildTreeRef _ _ _ path _ -> LocalUnpackedPackage path,
packageDescrOverride = case pkgEntry of
NormalPackage _ _ pkgtxt _ -> Just pkgtxt
_ -> Nothing
}
where
pkgid = packageId pkgEntry
handleNotFound action = catchIO action $ \e -> if isDoesNotExistError e
then do
case repoKind repo of
Left remoteRepo -> warn verbosity $
"The package list for '" ++ remoteRepoName remoteRepo
++ "' does not exist. Run 'cabal update' to download it."
Right _localRepo -> warn verbosity $
"The package list for the local repo '" ++ repoLocalDir repo
++ "' is missing. The repo is invalid."
return mempty
else ioError e
isOldThreshold = 15 --days
warnIfIndexIsOld dt = do
when (dt >= isOldThreshold) $ case repoKind repo of
Left remoteRepo -> warn verbosity $
"The package list for '" ++ remoteRepoName remoteRepo
++ "' is " ++ showFFloat (Just 1) dt " days old.\nRun "
++ "'cabal update' to get the latest list of available packages."
Right _localRepo -> return ()
-- | Return the age of the index file in days (as a Double).
getIndexFileAge :: Repo -> IO Double
getIndexFileAge repo = getFileAge $ repoLocalDir repo </> "00-index.tar"
-- | It is not necessary to call this, as the cache will be updated when the
-- index is read normally. However you can do the work earlier if you like.
--
updateRepoIndexCache :: Verbosity -> Repo -> IO ()
updateRepoIndexCache verbosity repo =
whenCacheOutOfDate indexFile cacheFile $ do
updatePackageIndexCacheFile verbosity indexFile cacheFile
where
indexFile = repoLocalDir repo </> "00-index.tar"
cacheFile = repoLocalDir repo </> "00-index.cache"
whenCacheOutOfDate :: FilePath -> FilePath -> IO () -> IO ()
whenCacheOutOfDate origFile cacheFile action = do
exists <- doesFileExist cacheFile
if not exists
then action
else do
origTime <- getModTime origFile
cacheTime <- getModTime cacheFile
when (origTime > cacheTime) action
------------------------------------------------------------------------
-- Reading the index file
--
-- | An index entry is either a normal package, or a local build tree reference.
data PackageEntry =
NormalPackage PackageId GenericPackageDescription ByteString BlockNo
| BuildTreeRef BuildTreeRefType
PackageId GenericPackageDescription FilePath BlockNo
-- | A build tree reference is either a link or a snapshot.
data BuildTreeRefType = SnapshotRef | LinkRef
deriving Eq
refTypeFromTypeCode :: Tar.TypeCode -> BuildTreeRefType
refTypeFromTypeCode t
| t == Tar.buildTreeRefTypeCode = LinkRef
| t == Tar.buildTreeSnapshotTypeCode = SnapshotRef
| otherwise =
error "Distribution.Client.IndexUtils.refTypeFromTypeCode: unknown type code"
typeCodeFromRefType :: BuildTreeRefType -> Tar.TypeCode
typeCodeFromRefType LinkRef = Tar.buildTreeRefTypeCode
typeCodeFromRefType SnapshotRef = Tar.buildTreeSnapshotTypeCode
type MkPackageEntry = IO PackageEntry
instance Package PackageEntry where
packageId (NormalPackage pkgid _ _ _) = pkgid
packageId (BuildTreeRef _ pkgid _ _ _) = pkgid
packageDesc :: PackageEntry -> GenericPackageDescription
packageDesc (NormalPackage _ descr _ _) = descr
packageDesc (BuildTreeRef _ _ descr _ _) = descr
-- | Read a compressed \"00-index.tar.gz\" file into a 'PackageIndex'.
--
-- This is supposed to be an \"all in one\" way to easily get at the info in
-- the Hackage package index.
--
-- It takes a function to map a 'GenericPackageDescription' into any more
-- specific instance of 'Package' that you might want to use. In the simple
-- case you can just use @\_ p -> p@ here.
--
readPackageIndexFile :: Package pkg
=> (PackageEntry -> pkg)
-> FilePath
-> IO (PackageIndex pkg, [Dependency])
readPackageIndexFile mkPkg indexFile = do
(mkPkgs, prefs) <- either fail return
. parsePackageIndex
. maybeDecompress
=<< BS.readFile indexFile
pkgEntries <- sequence mkPkgs
pkgs <- evaluate $ PackageIndex.fromList (map mkPkg pkgEntries)
return (pkgs, prefs)
-- | Parse an uncompressed \"00-index.tar\" repository index file represented
-- as a 'ByteString'.
--
parsePackageIndex :: ByteString
-> Either String ([MkPackageEntry], [Dependency])
parsePackageIndex = accum 0 [] [] . Tar.read
where
accum blockNo pkgs prefs es = case es of
Tar.Fail err -> Left err
Tar.Done -> Right (reverse pkgs, reverse prefs)
Tar.Next e es' -> accum blockNo' pkgs' prefs' es'
where
(pkgs', prefs') = extract blockNo pkgs prefs e
blockNo' = blockNo + Tar.entrySizeInBlocks e
extract blockNo pkgs prefs entry =
fromMaybe (pkgs, prefs) $
tryExtractPkg
`mplus` tryExtractPrefs
where
tryExtractPkg = do
mkPkgEntry <- extractPkg entry blockNo
return (mkPkgEntry:pkgs, prefs)
tryExtractPrefs = do
prefs' <- extractPrefs entry
return (pkgs, prefs'++prefs)
extractPkg :: Tar.Entry -> BlockNo -> Maybe MkPackageEntry
extractPkg entry blockNo = case Tar.entryContent entry of
Tar.NormalFile content _
| takeExtension fileName == ".cabal"
-> case splitDirectories (normalise fileName) of
[pkgname,vers,_] -> case simpleParse vers of
Just ver -> Just $ return (NormalPackage pkgid descr content blockNo)
where
pkgid = PackageIdentifier (PackageName pkgname) ver
parsed = parsePackageDescription . fromUTF8 . BS.Char8.unpack
$ content
descr = case parsed of
ParseOk _ d -> d
_ -> error $ "Couldn't read cabal file "
++ show fileName
_ -> Nothing
_ -> Nothing
Tar.OtherEntryType typeCode content _
| Tar.isBuildTreeRefTypeCode typeCode ->
Just $ do
let path = byteStringToFilePath content
err = "Error reading package index."
cabalFile <- tryFindAddSourcePackageDesc path err
descr <- PackageDesc.Parse.readPackageDescription normal cabalFile
return $ BuildTreeRef (refTypeFromTypeCode typeCode) (packageId descr)
descr path blockNo
_ -> Nothing
where
fileName = Tar.entryPath entry
extractPrefs :: Tar.Entry -> Maybe [Dependency]
extractPrefs entry = case Tar.entryContent entry of
Tar.NormalFile content _
| takeFileName (Tar.entryPath entry) == "preferred-versions"
-> Just . parsePreferredVersions
. BS.Char8.unpack $ content
_ -> Nothing
parsePreferredVersions :: String -> [Dependency]
parsePreferredVersions = mapMaybe simpleParse
. filter (not . isPrefixOf "--")
. lines
------------------------------------------------------------------------
-- Reading and updating the index cache
--
updatePackageIndexCacheFile :: Verbosity -> FilePath -> FilePath -> IO ()
updatePackageIndexCacheFile verbosity indexFile cacheFile = do
info verbosity "Updating the index cache file..."
(mkPkgs, prefs) <- either fail return
. parsePackageIndex
. maybeDecompress
=<< BS.readFile indexFile
pkgEntries <- sequence mkPkgs
let cache = mkCache pkgEntries prefs
writeFile cacheFile (showIndexCache cache)
where
mkCache pkgs prefs =
[ CachePreference pref | pref <- prefs ]
++ [ CachePackageId pkgid blockNo
| (NormalPackage pkgid _ _ blockNo) <- pkgs ]
++ [ CacheBuildTreeRef refType blockNo
| (BuildTreeRef refType _ _ _ blockNo) <- pkgs]
data ReadPackageIndexMode = ReadPackageIndexStrict
| ReadPackageIndexLazyIO
readPackageIndexCacheFile :: Package pkg
=> (PackageEntry -> pkg)
-> FilePath
-> FilePath
-> ReadPackageIndexMode
-> IO (PackageIndex pkg, [Dependency])
readPackageIndexCacheFile mkPkg indexFile cacheFile mode = do
cache <- liftM readIndexCache (BSS.readFile cacheFile)
myWithFile indexFile ReadMode $ \indexHnd ->
packageIndexFromCache mkPkg indexHnd cache mode
where
myWithFile f m act = case mode of
ReadPackageIndexStrict -> withFile f m act
ReadPackageIndexLazyIO -> do indexHnd <- openFile f m
act indexHnd
packageIndexFromCache :: Package pkg
=> (PackageEntry -> pkg)
-> Handle
-> [IndexCacheEntry]
-> ReadPackageIndexMode
-> IO (PackageIndex pkg, [Dependency])
packageIndexFromCache mkPkg hnd entrs mode = accum mempty [] entrs
where
accum srcpkgs prefs [] = do
-- Have to reverse entries, since in a tar file, later entries mask
-- earlier ones, and PackageIndex.fromList does the same, but we
-- accumulate the list of entries in reverse order, so need to reverse.
pkgIndex <- evaluate $ PackageIndex.fromList (reverse srcpkgs)
return (pkgIndex, prefs)
accum srcpkgs prefs (CachePackageId pkgid blockno : entries) = do
-- Given the cache entry, make a package index entry.
-- The magic here is that we use lazy IO to read the .cabal file
-- from the index tarball if it turns out that we need it.
-- Most of the time we only need the package id.
~(pkg, pkgtxt) <- unsafeInterleaveIO $ do
pkgtxt <- getEntryContent blockno
pkg <- readPackageDescription pkgtxt
return (pkg, pkgtxt)
let srcpkg = case mode of
ReadPackageIndexLazyIO ->
mkPkg (NormalPackage pkgid pkg pkgtxt blockno)
ReadPackageIndexStrict ->
pkg `seq` pkgtxt `seq` mkPkg (NormalPackage pkgid pkg
pkgtxt blockno)
accum (srcpkg:srcpkgs) prefs entries
accum srcpkgs prefs (CacheBuildTreeRef refType blockno : entries) = do
-- We have to read the .cabal file eagerly here because we can't cache the
-- package id for build tree references - the user might edit the .cabal
-- file after the reference was added to the index.
path <- liftM byteStringToFilePath . getEntryContent $ blockno
pkg <- do let err = "Error reading package index from cache."
file <- tryFindAddSourcePackageDesc path err
PackageDesc.Parse.readPackageDescription normal file
let srcpkg = mkPkg (BuildTreeRef refType (packageId pkg) pkg path blockno)
accum (srcpkg:srcpkgs) prefs entries
accum srcpkgs prefs (CachePreference pref : entries) =
accum srcpkgs (pref:prefs) entries
getEntryContent :: BlockNo -> IO ByteString
getEntryContent blockno = do
hSeek hnd AbsoluteSeek (fromIntegral (blockno * 512))
header <- BS.hGet hnd 512
size <- getEntrySize header
BS.hGet hnd (fromIntegral size)
getEntrySize :: ByteString -> IO Tar.FileSize
getEntrySize header =
case Tar.read header of
Tar.Next e _ ->
case Tar.entryContent e of
Tar.NormalFile _ size -> return size
Tar.OtherEntryType typecode _ size
| Tar.isBuildTreeRefTypeCode typecode
-> return size
_ -> interror "unexpected tar entry type"
_ -> interror "could not read tar file entry"
readPackageDescription :: ByteString -> IO GenericPackageDescription
readPackageDescription content =
case parsePackageDescription . fromUTF8 . BS.Char8.unpack $ content of
ParseOk _ d -> return d
_ -> interror "failed to parse .cabal file"
interror msg = die $ "internal error when reading package index: " ++ msg
++ "The package index or index cache is probably "
++ "corrupt. Running cabal update might fix it."
------------------------------------------------------------------------
-- Index cache data structure
--
-- | Tar files are block structured with 512 byte blocks. Every header and file
-- content starts on a block boundary.
--
type BlockNo = Int
data IndexCacheEntry = CachePackageId PackageId BlockNo
| CacheBuildTreeRef BuildTreeRefType BlockNo
| CachePreference Dependency
deriving (Eq)
packageKey, blocknoKey, buildTreeRefKey, preferredVersionKey :: String
packageKey = "pkg:"
blocknoKey = "b#"
buildTreeRefKey = "build-tree-ref:"
preferredVersionKey = "pref-ver:"
readIndexCacheEntry :: BSS.ByteString -> Maybe IndexCacheEntry
readIndexCacheEntry = \line ->
case BSS.words line of
[key, pkgnamestr, pkgverstr, sep, blocknostr]
| key == BSS.pack packageKey && sep == BSS.pack blocknoKey ->
case (parseName pkgnamestr, parseVer pkgverstr [],
parseBlockNo blocknostr) of
(Just pkgname, Just pkgver, Just blockno)
-> Just (CachePackageId (PackageIdentifier pkgname pkgver) blockno)
_ -> Nothing
[key, typecodestr, blocknostr] | key == BSS.pack buildTreeRefKey ->
case (parseRefType typecodestr, parseBlockNo blocknostr) of
(Just refType, Just blockno)
-> Just (CacheBuildTreeRef refType blockno)
_ -> Nothing
(key: remainder) | key == BSS.pack preferredVersionKey ->
fmap CachePreference (simpleParse (BSS.unpack (BSS.unwords remainder)))
_ -> Nothing
where
parseName str
| BSS.all (\c -> isAlphaNum c || c == '-') str
= Just (PackageName (BSS.unpack str))
| otherwise = Nothing
parseVer str vs =
case BSS.readInt str of
Nothing -> Nothing
Just (v, str') -> case BSS.uncons str' of
Just ('.', str'') -> parseVer str'' (v:vs)
Just _ -> Nothing
Nothing -> Just (Version (reverse (v:vs)) [])
parseBlockNo str =
case BSS.readInt str of
Just (blockno, remainder) | BSS.null remainder -> Just blockno
_ -> Nothing
parseRefType str =
case BSS.uncons str of
Just (typeCode, remainder)
| BSS.null remainder && Tar.isBuildTreeRefTypeCode typeCode
-> Just (refTypeFromTypeCode typeCode)
_ -> Nothing
showIndexCacheEntry :: IndexCacheEntry -> String
showIndexCacheEntry entry = unwords $ case entry of
CachePackageId pkgid b -> [ packageKey
, display (packageName pkgid)
, display (packageVersion pkgid)
, blocknoKey
, show b
]
CacheBuildTreeRef t b -> [ buildTreeRefKey
, [typeCodeFromRefType t]
, show b
]
CachePreference dep -> [ preferredVersionKey
, display dep
]
readIndexCache :: BSS.ByteString -> [IndexCacheEntry]
readIndexCache = mapMaybe readIndexCacheEntry . BSS.lines
showIndexCache :: [IndexCacheEntry] -> String
showIndexCache = unlines . map showIndexCacheEntry
| DavidAlphaFox/ghc | libraries/Cabal/cabal-install/Distribution/Client/IndexUtils.hs | bsd-3-clause | 24,027 | 0 | 21 | 6,309 | 4,908 | 2,547 | 2,361 | 412 | 11 |
-- {-# OPTIONS_GHC -Wno-redundant-constraints -Wno-simplifiable-class-constraints #-}
{-# LANGUAGE UndecidableInstances, MultiParamTypeClasses,
FunctionalDependencies, FlexibleInstances #-}
module T3108 where
-- Direct recursion terminates (typechecking-wise)
class C0 x
where
m0 :: x -> ()
m0 = const undefined
instance {-# OVERLAPPING #-} (C0 x, C0 y) => C0 (x,y)
instance {-# OVERLAPPING #-} C0 Bool
instance {-# OVERLAPPABLE #-} C0 (x,Bool) => C0 x
foo :: ()
foo = m0 (1::Int)
-- Indirect recursion does not terminate (typechecking-wise)
class C1 x
where
m1 :: x -> ()
m1 = const undefined
instance {-# OVERLAPPING #-} (C1 x, C1 y) => C1 (x,y)
instance {-# OVERLAPPING #-} C1 Bool
instance {-# OVERLAPPABLE #-} (C2 x y, C1 (y,Bool)) => C1 x
-- Weird test case: (C1 (y,Bool)) is simplifiable
class C2 x y | x -> y
instance C2 Int Int
-- It is this declaration that causes nontermination of typechecking.
bar :: ()
bar = m1 (1::Int)
| rahulmutt/ghcvm | tests/suite/typecheck/compile/T3108.hs | bsd-3-clause | 965 | 0 | 8 | 183 | 258 | 141 | 117 | -1 | -1 |
{-# LANGUAGE TemplateHaskell,DeriveDataTypeable,BangPatterns #-}
module Main where
import Remote
import Remote.Process (roundtripResponse,setRemoteNodeLogConfig,getConfig,PayloadDisposition(..),roundtripQuery,roundtripQueryMulti)
import KMeansCommon
import Control.Exception (try,SomeException,evaluate)
import Control.Monad (liftM)
import Control.Monad.Trans (liftIO)
import System.Random (randomR,getStdRandom)
import Data.Typeable (Typeable)
import Data.Data (Data)
import Control.Exception (IOException)
import Data.Binary (Binary,get,put,encode,decode)
import Data.Maybe (fromJust)
import Data.List (minimumBy,sortBy)
import Data.Time
import Data.Either (rights)
import qualified Data.ByteString.Lazy as B
import qualified Data.Map as Map
import System.IO
import Debug.Trace
split :: Int -> [a] -> [[a]]
split numChunks l = splitSize (ceiling $ fromIntegral (length l) / fromIntegral numChunks) l
where
splitSize i v = let (first,second) = splitAt i v
in first : splitSize i second
broadcast :: (Serializable a) => [ProcessId] -> a -> ProcessM ()
broadcast pids dat = mapM_ (\pid -> send pid dat) pids
multiSpawn :: [NodeId] -> Closure (ProcessM ()) -> ProcessM [ProcessId]
multiSpawn nodes f = mapM (\node -> spawnLink node f) nodes
where s n = do mypid <- getSelfNode
setRemoteNodeLogConfig n (LogConfig LoTrivial (LtForward mypid) LfAll)
spawnLink n f
mapperProcess :: ProcessM ()
mapperProcess =
let mapProcess :: (Maybe [Vector],Maybe [ProcessId],Map.Map Int (Int,Vector)) -> ProcessM ()
mapProcess (mvecs,mreducers,mresult) =
receiveWait
[
match (\vec -> do vecs<-liftIO $ readf vec
say $ "Mapper read data file"
return (Just vecs,mreducers,mresult)),
match (\reducers -> return (mvecs,Just reducers,mresult)),
roundtripResponse (\() -> return (mresult,(mvecs,mreducers,mresult))),
roundtripResponse
(\clusters -> let tbl = analyze (fromJust mvecs) clustersandcenters Map.empty
clustersandcenters = map (\x -> (x,clusterCenter x)) clusters
reducers = fromJust mreducers
target clust = reducers !! (clust `mod` length reducers)
sendout (clustid,(count,sum)) = send (target clustid) Cluster {clId = clustid,clCount=count, clSum=sum}
in do say $ "calculating: "++show (length reducers)++" reducers"
mapM_ sendout (Map.toList tbl)
return ((),(mvecs,mreducers,tbl))),
matchUnknownThrow
] >>= mapProcess
getit :: Handle -> IO [Vector]
getit h = do l <- liftM lines $ hGetContents h
return (map read l) -- evaluate or return?
readf fn = do h <- openFile fn ReadMode
getit h
condtrace cond s val = if cond
then trace s val
else val
analyze :: [Vector] -> [(Cluster,Vector)] -> Map.Map Int (Int,Vector) -> Map.Map Int (Int,Vector)
analyze [] _ ht = ht
analyze (v:vectors) clusters ht =
let theclust = assignToCluster clusters v
newh = ht `seq` theclust `seq` Map.insertWith' (\(a,v1) (b,v2) -> let av = addVector v1 v2 in av `seq` (a+b,av) ) theclust (1,v) ht
-- condtrace (blarg `mod` 1000 == 0) (show blarg) $
in newh `seq` analyze vectors clusters newh
assignToCluster :: [(Cluster,Vector)] -> Vector -> Int
assignToCluster clusters vector =
let distances = map (\(x,center) -> (clId x,sqDistance center vector)) clusters
in fst $ minimumBy (\(_,a) (_,b) -> compare a b) distances
doit = mapProcess (Nothing,Nothing,Map.empty)
in doit >> return ()
reducerProcess :: ProcessM ()
reducerProcess = let reduceProcess :: ([Cluster],[Cluster]) -> ProcessM ()
reduceProcess (oldclusters,clusters) =
receiveWait [
roundtripResponse (\() -> return (clusters,(clusters,[]))),
match (\x -> return (oldclusters,combineClusters clusters x)),
matchUnknownThrow] >>= reduceProcess
combineClusters :: [Cluster] -> Cluster -> [Cluster]
combineClusters [] a = [a]
combineClusters (fstclst:rest) clust | clId fstclst == clId clust = (Cluster {clId = clId fstclst,
clCount = clCount fstclst + clCount clust,
clSum = addVector (clSum fstclst) (clSum clust)}):rest
combineClusters (fstclst:res) clust = fstclst:(combineClusters res clust)
in reduceProcess ([],[]) >> return ()
$( remotable ['mapperProcess, 'reducerProcess] )
initialProcess "MASTER" =
do peers <- getPeers
-- say $ "Got peers: " ++ show peers
cfg <- getConfig
let mappers = findPeerByRole peers "MAPPER"
let reducers = findPeerByRole peers "REDUCER"
let numreducers = length reducers
let nummappers = length mappers
say $ "Got " ++ show nummappers ++ " mappers and " ++ show numreducers ++ " reducers"
clusters <- liftIO $ getClusters "kmeans-clusters"
say $ "Got "++show (length clusters)++" clusters"
mypid <- getSelfPid
mapperPids <- multiSpawn mappers mapperProcess__closure
reducerPids <- multiSpawn reducers reducerProcess__closure
broadcast mapperPids reducerPids
mapM_ (\(pid,chunk) -> send pid chunk) (zip (mapperPids) (repeat "kmeans-points"))
say "Starting iteration"
starttime <- liftIO $ getCurrentTime
let loop howmany clusters = do
liftIO $ putStrLn $ show howmany
roundtripQueryMulti PldUser mapperPids clusters :: ProcessM [Either TransmitStatus ()]
res <- roundtripQueryMulti PldUser reducerPids () :: ProcessM [Either TransmitStatus [Cluster]]
let newclusters = rights res
let newclusters2 = (sortBy (\a b -> compare (clId a) (clId b)) (concat newclusters))
if newclusters2 == clusters || howmany >= 4
then do
donetime <- liftIO $ getCurrentTime
say $ "Converged in " ++ show howmany ++ " iterations and " ++ (show $ diffUTCTime donetime starttime)
pointmaps <- mapM (\pid -> do (Right m) <- roundtripQuery PldUser pid ()
return (m::Map.Map Int (Int,Vector))) mapperPids
let pointmap = map (\x -> sum $ map fst (Map.elems x)) pointmaps
say $ "Total points: " ++ (show $ sum pointmap)
-- liftIO $ writeFile "kmeans-converged" $ readableShow (Map.toList pointmap)
--respoints <- roundtripQueryAsync PldUser mapperPids () :: ProcessM [Either TransmitStatus (Map.Map Int [Vector])]
--liftIO $ B.writeFile "kmeans-converged" $ encode $ Map.toList $ Map.unionsWith (++) (rights respoints)
else
loop (howmany+1) newclusters2
loop 0 clusters
initialProcess "MAPPER" = receiveWait []
initialProcess "REDUCER" = receiveWait []
initialProcess _ = error "Role must be MAPPER or REDUCER or MASTER"
main = remoteInit (Just "config") [Main.__remoteCallMetaData] initialProcess
| jepst/CloudHaskell | examples/kmeans/KMeans.hs | bsd-3-clause | 8,229 | 0 | 25 | 2,929 | 2,350 | 1,220 | 1,130 | 126 | 3 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- The 'Functor', 'Monad' and 'MonadPlus' classes,
-- with some useful operations on monads.
module Control.Monad
(
-- * Functor and monad classes
Functor(fmap)
, Monad((>>=), (>>), return, fail)
, MonadPlus(mzero, mplus)
-- * Functions
-- ** Naming conventions
-- $naming
-- ** Basic @Monad@ functions
, mapM
, mapM_
, forM
, forM_
, sequence
, sequence_
, (=<<)
, (>=>)
, (<=<)
, forever
, void
-- ** Generalisations of list functions
, join
, msum
, mfilter
, filterM
, mapAndUnzipM
, zipWithM
, zipWithM_
, foldM
, foldM_
, replicateM
, replicateM_
-- ** Conditional execution of monadic expressions
, guard
, when
, unless
-- ** Monadic lifting operators
, liftM
, liftM2
, liftM3
, liftM4
, liftM5
, ap
-- ** Strict monadic functions
, (<$!>)
) where
import Data.Foldable ( Foldable, sequence_, sequenceA_, msum, mapM_, foldlM, forM_ )
import Data.Functor ( void, (<$>) )
import Data.Traversable ( forM, mapM, traverse, sequence, sequenceA )
import GHC.Base hiding ( mapM, sequence )
import GHC.List ( zipWith, unzip )
import GHC.Num ( (-) )
-- -----------------------------------------------------------------------------
-- Functions mandated by the Prelude
-- | Conditional failure of 'Alternative' computations. Defined by
--
-- @
-- guard True = 'pure' ()
-- guard False = 'empty'
-- @
--
-- ==== __Examples__
--
-- Common uses of 'guard' include conditionally signaling an error in
-- an error monad and conditionally rejecting the current choice in an
-- 'Alternative'-based parser.
--
-- As an example of signaling an error in the error monad 'Maybe',
-- consider a safe division function @safeDiv x y@ that returns
-- 'Nothing' when the denominator @y@ is zero and @'Just' (x \`div\`
-- y)@ otherwise. For example:
--
-- @
-- >>> safeDiv 4 0
-- Nothing
-- >>> safeDiv 4 2
-- Just 2
-- @
--
-- A definition of @safeDiv@ using guards, but not 'guard':
--
-- @
-- safeDiv :: Int -> Int -> Maybe Int
-- safeDiv x y | y /= 0 = Just (x \`div\` y)
-- | otherwise = Nothing
-- @
--
-- A definition of @safeDiv@ using 'guard' and 'Monad' @do@-notation:
--
-- @
-- safeDiv :: Int -> Int -> Maybe Int
-- safeDiv x y = do
-- guard (y /= 0)
-- return (x \`div\` y)
-- @
guard :: (Alternative f) => Bool -> f ()
guard True = pure ()
guard False = empty
-- | This generalizes the list-based 'filter' function.
{-# INLINE filterM #-}
filterM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterM p = foldr (\ x -> liftA2 (\ flg -> if flg then (x:) else id) (p x)) (pure [])
infixr 1 <=<, >=>
-- | Left-to-right Kleisli composition of monads.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
f >=> g = \x -> f x >>= g
-- | Right-to-left Kleisli composition of monads. @('>=>')@, with the arguments flipped.
--
-- Note how this operator resembles function composition @('.')@:
--
-- > (.) :: (b -> c) -> (a -> b) -> a -> c
-- > (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
(<=<) = flip (>=>)
-- | @'forever' act@ repeats the action infinitely.
forever :: (Applicative f) => f a -> f b
{-# INLINE forever #-}
forever a = let a' = a *> a' in a'
-- Use explicit sharing here, as it prevents a space leak regardless of
-- optimizations.
-- -----------------------------------------------------------------------------
-- Other monad functions
-- | The 'mapAndUnzipM' function maps its first argument over a list, returning
-- the result as a pair of lists. This function is mainly used with complicated
-- data structures or a state-transforming monad.
mapAndUnzipM :: (Applicative m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
{-# INLINE mapAndUnzipM #-}
mapAndUnzipM f xs = unzip <$> traverse f xs
-- | The 'zipWithM' function generalizes 'zipWith' to arbitrary applicative functors.
zipWithM :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
{-# INLINE zipWithM #-}
zipWithM f xs ys = sequenceA (zipWith f xs ys)
-- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.
zipWithM_ :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m ()
{-# INLINE zipWithM_ #-}
zipWithM_ f xs ys = sequenceA_ (zipWith f xs ys)
{- | The 'foldM' function is analogous to 'foldl', except that its result is
encapsulated in a monad. Note that 'foldM' works from left-to-right over
the list arguments. This could be an issue where @('>>')@ and the `folded
function' are not commutative.
> foldM f a1 [x1, x2, ..., xm]
>
> ==
>
> do
> a2 <- f a1 x1
> a3 <- f a2 x2
> ...
> f am xm
If right-to-left evaluation is required, the input list should be reversed.
Note: 'foldM' is the same as 'foldlM'
-}
foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
{-# INLINABLE foldM #-}
{-# SPECIALISE foldM :: (a -> b -> IO a) -> a -> [b] -> IO a #-}
{-# SPECIALISE foldM :: (a -> b -> Maybe a) -> a -> [b] -> Maybe a #-}
foldM = foldlM
-- | Like 'foldM', but discards the result.
foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m ()
{-# INLINABLE foldM_ #-}
{-# SPECIALISE foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () #-}
{-# SPECIALISE foldM_ :: (a -> b -> Maybe a) -> a -> [b] -> Maybe () #-}
foldM_ f a xs = foldlM f a xs >> return ()
{-
Note [Worker/wrapper transform on replicateM/replicateM_]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The implementations of replicateM and replicateM_ both leverage the
worker/wrapper transform. The simpler implementation of replicateM_, as an
example, would be:
replicateM_ 0 _ = pure ()
replicateM_ n f = f *> replicateM_ (n - 1) f
However, the self-recursive nature of this implementation inhibits inlining,
which means we never get to specialise to the action (`f` in the code above).
By contrast, the implementation below with a local loop makes it possible to
inline the entire definition (as happens for foldr, for example) thereby
specialising for the particular action.
For further information, see this Trac comment, which includes side-by-side
Core: https://ghc.haskell.org/trac/ghc/ticket/11795#comment:6
-}
-- | @'replicateM' n act@ performs the action @n@ times,
-- gathering the results.
replicateM :: (Applicative m) => Int -> m a -> m [a]
{-# INLINABLE replicateM #-}
{-# SPECIALISE replicateM :: Int -> IO a -> IO [a] #-}
{-# SPECIALISE replicateM :: Int -> Maybe a -> Maybe [a] #-}
replicateM cnt0 f =
loop cnt0
where
loop cnt
| cnt <= 0 = pure []
| otherwise = liftA2 (:) f (loop (cnt - 1))
-- | Like 'replicateM', but discards the result.
replicateM_ :: (Applicative m) => Int -> m a -> m ()
{-# INLINABLE replicateM_ #-}
{-# SPECIALISE replicateM_ :: Int -> IO a -> IO () #-}
{-# SPECIALISE replicateM_ :: Int -> Maybe a -> Maybe () #-}
replicateM_ cnt0 f =
loop cnt0
where
loop cnt
| cnt <= 0 = pure ()
| otherwise = f *> loop (cnt - 1)
-- | The reverse of 'when'.
unless :: (Applicative f) => Bool -> f () -> f ()
{-# INLINABLE unless #-}
{-# SPECIALISE unless :: Bool -> IO () -> IO () #-}
{-# SPECIALISE unless :: Bool -> Maybe () -> Maybe () #-}
unless p s = if p then pure () else s
infixl 4 <$!>
-- | Strict version of 'Data.Functor.<$>'.
--
-- @since 4.8.0.0
(<$!>) :: Monad m => (a -> b) -> m a -> m b
{-# INLINE (<$!>) #-}
f <$!> m = do
x <- m
let z = f x
z `seq` return z
-- -----------------------------------------------------------------------------
-- Other MonadPlus functions
-- | Direct 'MonadPlus' equivalent of 'filter'
-- @'filter'@ = @(mfilter:: (a -> Bool) -> [a] -> [a]@
-- applicable to any 'MonadPlus', for example
-- @mfilter odd (Just 1) == Just 1@
-- @mfilter odd (Just 2) == Nothing@
mfilter :: (MonadPlus m) => (a -> Bool) -> m a -> m a
{-# INLINABLE mfilter #-}
mfilter p ma = do
a <- ma
if p a then return a else mzero
{- $naming
The functions in this library use the following naming conventions:
* A postfix \'@M@\' always stands for a function in the Kleisli category:
The monad type constructor @m@ is added to function results
(modulo currying) and nowhere else. So, for example,
> filter :: (a -> Bool) -> [a] -> [a]
> filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
* A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.
Thus, for example:
> sequence :: Monad m => [m a] -> m [a]
> sequence_ :: Monad m => [m a] -> m ()
* A prefix \'@m@\' generalizes an existing function to a monadic form.
Thus, for example:
> filter :: (a -> Bool) -> [a] -> [a]
> mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
-}
| rahulmutt/ghcvm | libraries/base/Control/Monad.hs | bsd-3-clause | 9,327 | 0 | 12 | 2,241 | 1,476 | 856 | 620 | 114 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor #-}
-- | CoreSyn holds all the main data types for use by for the Glasgow Haskell Compiler midsection
module CoreSyn (
-- * Main data types
Expr(..), Alt, Bind(..), AltCon(..), Arg,
Tickish(..), TickishScoping(..), TickishPlacement(..),
CoreProgram, CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..), deTagExpr,
-- ** 'Expr' construction
mkLets, mkLams,
mkApps, mkTyApps, mkCoApps, mkVarApps,
mkIntLit, mkIntLitInt,
mkWordLit, mkWordLitWord,
mkWord64LitWord64, mkInt64LitInt64,
mkCharLit, mkStringLit,
mkFloatLit, mkFloatLitFloat,
mkDoubleLit, mkDoubleLitDouble,
mkConApp, mkConApp2, mkTyBind, mkCoBind,
varToCoreExpr, varsToCoreExprs,
isId, cmpAltCon, cmpAlt, ltAlt,
-- ** Simple 'Expr' access functions and predicates
bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts,
collectBinders, collectTyAndValBinders,
collectArgs, collectArgsTicks, flattenBinds,
exprToType, exprToCoercion_maybe,
applyTypeToArg,
isValArg, isTypeArg, isTyCoArg, valArgCount, valBndrCount,
isRuntimeArg, isRuntimeVar,
tickishCounts, tickishScoped, tickishScopesLike, tickishFloatable,
tickishCanSplit, mkNoCount, mkNoScope,
tickishIsCode, tickishPlace,
tickishContains,
-- * Unfolding data types
Unfolding(..), UnfoldingGuidance(..), UnfoldingSource(..),
-- ** Constructing 'Unfolding's
noUnfolding, evaldUnfolding, mkOtherCon,
unSaturatedOk, needSaturated, boringCxtOk, boringCxtNotOk,
-- ** Predicates and deconstruction on 'Unfolding'
unfoldingTemplate, expandUnfolding_maybe,
maybeUnfoldingTemplate, otherCons,
isValueUnfolding, isEvaldUnfolding, isCheapUnfolding,
isExpandableUnfolding, isConLikeUnfolding, isCompulsoryUnfolding,
isStableUnfolding, hasStableCoreUnfolding_maybe,
isClosedUnfolding, hasSomeUnfolding,
canUnfold, neverUnfoldGuidance, isStableSource,
-- * Annotated expression data types
AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
-- ** Operations on annotated expressions
collectAnnArgs, collectAnnArgsTicks,
-- ** Operations on annotations
deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
-- * Orphanhood
IsOrphan(..), isOrphan, notOrphan, chooseOrphanAnchor,
-- * Core rule data types
CoreRule(..), RuleBase,
RuleName, RuleFun, IdUnfoldingFun, InScopeEnv,
RuleEnv(..), mkRuleEnv, emptyRuleEnv,
-- ** Operations on 'CoreRule's
ruleArity, ruleName, ruleIdName, ruleActivation,
setRuleIdName,
isBuiltinRule, isLocalRule, isAutoRule,
-- * Core vectorisation declarations data type
CoreVect(..)
) where
#include "HsVersions.h"
import CostCentre
import VarEnv( InScopeSet )
import Var
import Type
import Coercion
import Name
import NameEnv( NameEnv, emptyNameEnv )
import Literal
import DataCon
import Module
import TyCon
import BasicTypes
import DynFlags
import Outputable
import Util
import SrcLoc ( RealSrcSpan, containsSpan )
import Binary
import Data.Data hiding (TyCon)
import Data.Int
import Data.Word
infixl 4 `mkApps`, `mkTyApps`, `mkVarApps`, `App`, `mkCoApps`
-- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys)
{-
************************************************************************
* *
\subsection{The main data types}
* *
************************************************************************
These data types are the heart of the compiler
-}
-- | This is the data type that represents GHCs core intermediate language. Currently
-- GHC uses System FC <http://research.microsoft.com/~simonpj/papers/ext-f/> for this purpose,
-- which is closely related to the simpler and better known System F <http://en.wikipedia.org/wiki/System_F>.
--
-- We get from Haskell source to this Core language in a number of stages:
--
-- 1. The source code is parsed into an abstract syntax tree, which is represented
-- by the data type 'HsExpr.HsExpr' with the names being 'RdrName.RdrNames'
--
-- 2. This syntax tree is /renamed/, which attaches a 'Unique.Unique' to every 'RdrName.RdrName'
-- (yielding a 'Name.Name') to disambiguate identifiers which are lexically identical.
-- For example, this program:
--
-- @
-- f x = let f x = x + 1
-- in f (x - 2)
-- @
--
-- Would be renamed by having 'Unique's attached so it looked something like this:
--
-- @
-- f_1 x_2 = let f_3 x_4 = x_4 + 1
-- in f_3 (x_2 - 2)
-- @
-- But see Note [Shadowing] below.
--
-- 3. The resulting syntax tree undergoes type checking (which also deals with instantiating
-- type class arguments) to yield a 'HsExpr.HsExpr' type that has 'Id.Id' as it's names.
--
-- 4. Finally the syntax tree is /desugared/ from the expressive 'HsExpr.HsExpr' type into
-- this 'Expr' type, which has far fewer constructors and hence is easier to perform
-- optimization, analysis and code generation on.
--
-- The type parameter @b@ is for the type of binders in the expression tree.
--
-- The language consists of the following elements:
--
-- * Variables
--
-- * Primitive literals
--
-- * Applications: note that the argument may be a 'Type'.
--
-- See "CoreSyn#let_app_invariant" for another invariant
--
-- * Lambda abstraction
--
-- * Recursive and non recursive @let@s. Operationally
-- this corresponds to allocating a thunk for the things
-- bound and then executing the sub-expression.
--
-- #top_level_invariant#
-- #letrec_invariant#
--
-- The right hand sides of all top-level and recursive @let@s
-- /must/ be of lifted type (see "Type#type_classification" for
-- the meaning of /lifted/ vs. /unlifted/).
--
-- See Note [CoreSyn let/app invariant]
--
-- #type_let#
-- We allow a /non-recursive/ let to bind a type variable, thus:
--
-- > Let (NonRec tv (Type ty)) body
--
-- This can be very convenient for postponing type substitutions until
-- the next run of the simplifier.
--
-- At the moment, the rest of the compiler only deals with type-let
-- in a Let expression, rather than at top level. We may want to revist
-- this choice.
--
-- * Case split. Operationally this corresponds to evaluating
-- the scrutinee (expression examined) to weak head normal form
-- and then examining at most one level of resulting constructor (i.e. you
-- cannot do nested pattern matching directly with this).
--
-- The binder gets bound to the value of the scrutinee,
-- and the 'Type' must be that of all the case alternatives
--
-- #case_invariants#
-- This is one of the more complicated elements of the Core language,
-- and comes with a number of restrictions:
--
-- 1. The list of alternatives may be empty;
-- See Note [Empty case alternatives]
--
-- 2. The 'DEFAULT' case alternative must be first in the list,
-- if it occurs at all.
--
-- 3. The remaining cases are in order of increasing
-- tag (for 'DataAlts') or
-- lit (for 'LitAlts').
-- This makes finding the relevant constructor easy,
-- and makes comparison easier too.
--
-- 4. The list of alternatives must be exhaustive. An /exhaustive/ case
-- does not necessarily mention all constructors:
--
-- @
-- data Foo = Red | Green | Blue
-- ... case x of
-- Red -> True
-- other -> f (case x of
-- Green -> ...
-- Blue -> ... ) ...
-- @
--
-- The inner case does not need a @Red@ alternative, because @x@
-- can't be @Red@ at that program point.
--
-- 5. Floating-point values must not be scrutinised against literals.
-- See Trac #9238 and Note [Rules for floating-point comparisons]
-- in PrelRules for rationale.
--
-- * Cast an expression to a particular type.
-- This is used to implement @newtype@s (a @newtype@ constructor or
-- destructor just becomes a 'Cast' in Core) and GADTs.
--
-- * Notes. These allow general information to be added to expressions
-- in the syntax tree
--
-- * A type: this should only show up at the top level of an Arg
--
-- * A coercion
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Expr b
= Var Id
| Lit Literal
| App (Expr b) (Arg b)
| Lam b (Expr b)
| Let (Bind b) (Expr b)
| Case (Expr b) b Type [Alt b] -- See #case_invariant#
| Cast (Expr b) Coercion
| Tick (Tickish Id) (Expr b)
| Type Type
| Coercion Coercion
deriving (Data, Typeable)
-- | Type synonym for expressions that occur in function argument positions.
-- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not
type Arg b = Expr b
-- | A case split alternative. Consists of the constructor leading to the alternative,
-- the variables bound from the constructor, and the expression to be executed given that binding.
-- The default alternative is @(DEFAULT, [], rhs)@
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
type Alt b = (AltCon, [b], Expr b)
-- | A case alternative constructor (i.e. pattern match)
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data AltCon
= DataAlt DataCon -- ^ A plain data constructor: @case e of { Foo x -> ... }@.
-- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@
| LitAlt Literal -- ^ A literal: @case e of { 1 -> ... }@
-- Invariant: always an *unlifted* literal
-- See Note [Literal alternatives]
| DEFAULT -- ^ Trivial alternative: @case e of { _ -> ... }@
deriving (Eq, Ord, Data, Typeable)
-- | Binding, used for top level bindings in a module and local bindings in a @let@.
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Bind b = NonRec b (Expr b)
| Rec [(b, (Expr b))]
deriving (Data, Typeable)
{-
Note [Shadowing]
~~~~~~~~~~~~~~~~
While various passes attempt to rename on-the-fly in a manner that
avoids "shadowing" (thereby simplifying downstream optimizations),
neither the simplifier nor any other pass GUARANTEES that shadowing is
avoided. Thus, all passes SHOULD work fine even in the presence of
arbitrary shadowing in their inputs.
In particular, scrutinee variables `x` in expressions of the form
`Case e x t` are often renamed to variables with a prefix
"wild_". These "wild" variables may appear in the body of the
case-expression, and further, may be shadowed within the body.
So the Unique in an Var is not really unique at all. Still, it's very
useful to give a constant-time equality/ordering for Vars, and to give
a key that can be used to make sets of Vars (VarSet), or mappings from
Vars to other things (VarEnv). Moreover, if you do want to eliminate
shadowing, you can give a new Unique to an Id without changing its
printable name, which makes debugging easier.
Note [Literal alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Literal alternatives (LitAlt lit) are always for *un-lifted* literals.
We have one literal, a literal Integer, that is lifted, and we don't
allow in a LitAlt, because LitAlt cases don't do any evaluation. Also
(see Trac #5603) if you say
case 3 of
S# x -> ...
J# _ _ -> ...
(where S#, J# are the constructors for Integer) we don't want the
simplifier calling findAlt with argument (LitAlt 3). No no. Integer
literals are an opaque encoding of an algebraic data type, not of
an unlifted literal, like all the others.
Also, we do not permit case analysis with literal patterns on floating-point
types. See Trac #9238 and Note [Rules for floating-point comparisons] in
PrelRules for the rationale for this restriction.
-------------------------- CoreSyn INVARIANTS ---------------------------
Note [CoreSyn top-level invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #toplevel_invariant#
Note [CoreSyn letrec invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #letrec_invariant#
Note [CoreSyn let/app invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The let/app invariant
the right hand side of a non-recursive 'Let', and
the argument of an 'App',
/may/ be of unlifted type, but only if
the expression is ok-for-speculation.
This means that the let can be floated around
without difficulty. For example, this is OK:
y::Int# = x +# 1#
But this is not, as it may affect termination if the
expression is floated out:
y::Int# = fac 4#
In this situation you should use @case@ rather than a @let@. The function
'CoreUtils.needsCaseBinding' can help you determine which to generate, or
alternatively use 'MkCore.mkCoreLet' rather than this constructor directly,
which will generate a @case@ if necessary
Th let/app invariant is initially enforced by DsUtils.mkCoreLet and mkCoreApp
Note [CoreSyn case invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #case_invariants#
Note [CoreSyn let goal]
~~~~~~~~~~~~~~~~~~~~~~~
* The simplifier tries to ensure that if the RHS of a let is a constructor
application, its arguments are trivial, so that the constructor can be
inlined vigorously.
Note [Type let]
~~~~~~~~~~~~~~~
See #type_let#
Note [Empty case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The alternatives of a case expression should be exhaustive. But
this exhaustive list can be empty!
* A case expression can have empty alternatives if (and only if) the
scrutinee is bound to raise an exception or diverge. When do we know
this? See Note [Bottoming expressions] in CoreUtils.
* The possiblity of empty alternatives is one reason we need a type on
the case expression: if the alternatives are empty we can't get the
type from the alternatives!
* In the case of empty types (see Note [Bottoming expressions]), say
data T
we do NOT want to replace
case (x::T) of Bool {} --> error Bool "Inaccessible case"
because x might raise an exception, and *that*'s what we want to see!
(Trac #6067 is an example.) To preserve semantics we'd have to say
x `seq` error Bool "Inaccessible case"
but the 'seq' is just a case, so we are back to square 1. Or I suppose
we could say
x |> UnsafeCoerce T Bool
but that loses all trace of the fact that this originated with an empty
set of alternatives.
* We can use the empty-alternative construct to coerce error values from
one type to another. For example
f :: Int -> Int
f n = error "urk"
g :: Int -> (# Char, Bool #)
g x = case f x of { 0 -> ..., n -> ... }
Then if we inline f in g's RHS we get
case (error Int "urk") of (# Char, Bool #) { ... }
and we can discard the alternatives since the scrutinee is bottom to give
case (error Int "urk") of (# Char, Bool #) {}
This is nicer than using an unsafe coerce between Int ~ (# Char,Bool #),
if for no other reason that we don't need to instantiate the (~) at an
unboxed type.
* We treat a case expression with empty alternatives as trivial iff
its scrutinee is (see CoreUtils.exprIsTrivial). This is actually
important; see Note [Empty case is trivial] in CoreUtils
* An empty case is replaced by its scrutinee during the CoreToStg
conversion; remember STG is un-typed, so there is no need for
the empty case to do the type conversion.
************************************************************************
* *
Ticks
* *
************************************************************************
-}
-- | Allows attaching extra information to points in expressions
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Tickish id =
-- | An @{-# SCC #-}@ profiling annotation, either automatically
-- added by the desugarer as a result of -auto-all, or added by
-- the user.
ProfNote {
profNoteCC :: CostCentre, -- ^ the cost centre
profNoteCount :: !Bool, -- ^ bump the entry count?
profNoteScope :: !Bool -- ^ scopes over the enclosed expression
-- (i.e. not just a tick)
}
-- | A "tick" used by HPC to track the execution of each
-- subexpression in the original source code.
| HpcTick {
tickModule :: Module,
tickId :: !Int
}
-- | A breakpoint for the GHCi debugger. This behaves like an HPC
-- tick, but has a list of free variables which will be available
-- for inspection in GHCi when the program stops at the breakpoint.
--
-- NB. we must take account of these Ids when (a) counting free variables,
-- and (b) substituting (don't substitute for them)
| Breakpoint
{ breakpointId :: !Int
, breakpointFVs :: [id] -- ^ the order of this list is important:
-- it matches the order of the lists in the
-- appropriate entry in HscTypes.ModBreaks.
--
-- Careful about substitution! See
-- Note [substTickish] in CoreSubst.
}
-- | A source note.
--
-- Source notes are pure annotations: Their presence should neither
-- influence compilation nor execution. The semantics are given by
-- causality: The presence of a source note means that a local
-- change in the referenced source code span will possibly provoke
-- the generated code to change. On the flip-side, the functionality
-- of annotated code *must* be invariant against changes to all
-- source code *except* the spans referenced in the source notes
-- (see "Causality of optimized Haskell" paper for details).
--
-- Therefore extending the scope of any given source note is always
-- valid. Note that it is still undesirable though, as this reduces
-- their usefulness for debugging and profiling. Therefore we will
-- generally try only to make use of this property where it is
-- neccessary to enable optimizations.
| SourceNote
{ sourceSpan :: RealSrcSpan -- ^ Source covered
, sourceName :: String -- ^ Name for source location
-- (uses same names as CCs)
}
deriving (Eq, Ord, Data, Typeable)
-- | A "counting tick" (where tickishCounts is True) is one that
-- counts evaluations in some way. We cannot discard a counting tick,
-- and the compiler should preserve the number of counting ticks as
-- far as possible.
--
-- However, we still allow the simplifier to increase or decrease
-- sharing, so in practice the actual number of ticks may vary, except
-- that we never change the value from zero to non-zero or vice versa.
tickishCounts :: Tickish id -> Bool
tickishCounts n@ProfNote{} = profNoteCount n
tickishCounts HpcTick{} = True
tickishCounts Breakpoint{} = True
tickishCounts _ = False
-- | Specifies the scoping behaviour of ticks. This governs the
-- behaviour of ticks that care about the covered code and the cost
-- associated with it. Important for ticks relating to profiling.
data TickishScoping =
-- | No scoping: The tick does not care about what code it
-- covers. Transformations can freely move code inside as well as
-- outside without any additional annotation obligations
NoScope
-- | Soft scoping: We want all code that is covered to stay
-- covered. Note that this scope type does not forbid
-- transformations from happening, as as long as all results of
-- the transformations are still covered by this tick or a copy of
-- it. For example
--
-- let x = tick<...> (let y = foo in bar) in baz
-- ===>
-- let x = tick<...> bar; y = tick<...> foo in baz
--
-- Is a valid transformation as far as "bar" and "foo" is
-- concerned, because both still are scoped over by the tick.
--
-- Note though that one might object to the "let" not being
-- covered by the tick any more. However, we are generally lax
-- with this - constant costs don't matter too much, and given
-- that the "let" was effectively merged we can view it as having
-- lost its identity anyway.
--
-- Also note that this scoping behaviour allows floating a tick
-- "upwards" in pretty much any situation. For example:
--
-- case foo of x -> tick<...> bar
-- ==>
-- tick<...> case foo of x -> bar
--
-- While this is always leagl, we want to make a best effort to
-- only make us of this where it exposes transformation
-- opportunities.
| SoftScope
-- | Cost centre scoping: We don't want any costs to move to other
-- cost-centre stacks. This means we not only want no code or cost
-- to get moved out of their cost centres, but we also object to
-- code getting associated with new cost-centre ticks - or
-- changing the order in which they get applied.
--
-- A rule of thumb is that we don't want any code to gain new
-- annotations. However, there are notable exceptions, for
-- example:
--
-- let f = \y -> foo in tick<...> ... (f x) ...
-- ==>
-- tick<...> ... foo[x/y] ...
--
-- In-lining lambdas like this is always legal, because inlining a
-- function does not change the cost-centre stack when the
-- function is called.
| CostCentreScope
deriving (Eq)
-- | Returns the intended scoping rule for a Tickish
tickishScoped :: Tickish id -> TickishScoping
tickishScoped n@ProfNote{}
| profNoteScope n = CostCentreScope
| otherwise = NoScope
tickishScoped HpcTick{} = NoScope
tickishScoped Breakpoint{} = CostCentreScope
-- Breakpoints are scoped: eventually we're going to do call
-- stacks, but also this helps prevent the simplifier from moving
-- breakpoints around and changing their result type (see #1531).
tickishScoped SourceNote{} = SoftScope
-- | Returns whether the tick scoping rule is at least as permissive
-- as the given scoping rule.
tickishScopesLike :: Tickish id -> TickishScoping -> Bool
tickishScopesLike t scope = tickishScoped t `like` scope
where NoScope `like` _ = True
_ `like` NoScope = False
SoftScope `like` _ = True
_ `like` SoftScope = False
CostCentreScope `like` _ = True
-- | Returns @True@ for ticks that can be floated upwards easily even
-- where it might change execution counts, such as:
--
-- Just (tick<...> foo)
-- ==>
-- tick<...> (Just foo)
--
-- This is a combination of @tickishSoftScope@ and
-- @tickishCounts@. Note that in principle splittable ticks can become
-- floatable using @mkNoTick@ -- even though there's currently no
-- tickish for which that is the case.
tickishFloatable :: Tickish id -> Bool
tickishFloatable t = t `tickishScopesLike` SoftScope && not (tickishCounts t)
-- | Returns @True@ for a tick that is both counting /and/ scoping and
-- can be split into its (tick, scope) parts using 'mkNoScope' and
-- 'mkNoTick' respectively.
tickishCanSplit :: Tickish id -> Bool
tickishCanSplit ProfNote{profNoteScope = True, profNoteCount = True}
= True
tickishCanSplit _ = False
mkNoCount :: Tickish id -> Tickish id
mkNoCount n | not (tickishCounts n) = n
| not (tickishCanSplit n) = panic "mkNoCount: Cannot split!"
mkNoCount n@ProfNote{} = n {profNoteCount = False}
mkNoCount _ = panic "mkNoCount: Undefined split!"
mkNoScope :: Tickish id -> Tickish id
mkNoScope n | tickishScoped n == NoScope = n
| not (tickishCanSplit n) = panic "mkNoScope: Cannot split!"
mkNoScope n@ProfNote{} = n {profNoteScope = False}
mkNoScope _ = panic "mkNoScope: Undefined split!"
-- | Return @True@ if this source annotation compiles to some backend
-- code. Without this flag, the tickish is seen as a simple annotation
-- that does not have any associated evaluation code.
--
-- What this means that we are allowed to disregard the tick if doing
-- so means that we can skip generating any code in the first place. A
-- typical example is top-level bindings:
--
-- foo = tick<...> \y -> ...
-- ==>
-- foo = \y -> tick<...> ...
--
-- Here there is just no operational difference between the first and
-- the second version. Therefore code generation should simply
-- translate the code as if it found the latter.
tickishIsCode :: Tickish id -> Bool
tickishIsCode SourceNote{} = False
tickishIsCode _tickish = True -- all the rest for now
-- | Governs the kind of expression that the tick gets placed on when
-- annotating for example using @mkTick@. If we find that we want to
-- put a tickish on an expression ruled out here, we try to float it
-- inwards until we find a suitable expression.
data TickishPlacement =
-- | Place ticks exactly on run-time expressions. We can still
-- move the tick through pure compile-time constructs such as
-- other ticks, casts or type lambdas. This is the most
-- restrictive placement rule for ticks, as all tickishs have in
-- common that they want to track runtime processes. The only
-- legal placement rule for counting ticks.
PlaceRuntime
-- | As @PlaceRuntime@, but we float the tick through all
-- lambdas. This makes sense where there is little difference
-- between annotating the lambda and annotating the lambda's code.
| PlaceNonLam
-- | In addition to floating through lambdas, cost-centre style
-- tickishs can also be moved from constructors, non-function
-- variables and literals. For example:
--
-- let x = scc<...> C (scc<...> y) (scc<...> 3) in ...
--
-- Neither the constructor application, the variable or the
-- literal are likely to have any cost worth mentioning. And even
-- if y names a thunk, the call would not care about the
-- evaluation context. Therefore removing all annotations in the
-- above example is safe.
| PlaceCostCentre
deriving (Eq)
-- | Placement behaviour we want for the ticks
tickishPlace :: Tickish id -> TickishPlacement
tickishPlace n@ProfNote{}
| profNoteCount n = PlaceRuntime
| otherwise = PlaceCostCentre
tickishPlace HpcTick{} = PlaceRuntime
tickishPlace Breakpoint{} = PlaceRuntime
tickishPlace SourceNote{} = PlaceNonLam
-- | Returns whether one tick "contains" the other one, therefore
-- making the second tick redundant.
tickishContains :: Eq b => Tickish b -> Tickish b -> Bool
tickishContains (SourceNote sp1 n1) (SourceNote sp2 n2)
= n1 == n2 && containsSpan sp1 sp2
tickishContains t1 t2
= t1 == t2
{-
************************************************************************
* *
Orphans
* *
************************************************************************
-}
-- | Is this instance an orphan? If it is not an orphan, contains an 'OccName'
-- witnessing the instance's non-orphanhood.
-- See Note [Orphans]
data IsOrphan
= IsOrphan
| NotOrphan OccName -- The OccName 'n' witnesses the instance's non-orphanhood
-- In that case, the instance is fingerprinted as part
-- of the definition of 'n's definition
deriving (Data, Typeable)
-- | Returns true if 'IsOrphan' is orphan.
isOrphan :: IsOrphan -> Bool
isOrphan IsOrphan = True
isOrphan _ = False
-- | Returns true if 'IsOrphan' is not an orphan.
notOrphan :: IsOrphan -> Bool
notOrphan NotOrphan{} = True
notOrphan _ = False
chooseOrphanAnchor :: [Name] -> IsOrphan
-- Something (rule, instance) is relate to all the Names in this
-- list. Choose one of them to be an "anchor" for the orphan. We make
-- the choice deterministic to avoid gratuitious changes in the ABI
-- hash (Trac #4012). Specficially, use lexicographic comparison of
-- OccName rather than comparing Uniques
--
-- NB: 'minimum' use Ord, and (Ord OccName) works lexicographically
--
chooseOrphanAnchor local_names
| null local_names = IsOrphan
| otherwise = NotOrphan (minimum occs)
where
occs = map nameOccName local_names
instance Binary IsOrphan where
put_ bh IsOrphan = putByte bh 0
put_ bh (NotOrphan n) = do
putByte bh 1
put_ bh n
get bh = do
h <- getByte bh
case h of
0 -> return IsOrphan
_ -> do
n <- get bh
return $ NotOrphan n
{-
Note [Orphans]
~~~~~~~~~~~~~~
Class instances, rules, and family instances are divided into orphans
and non-orphans. Roughly speaking, an instance/rule is an orphan if
its left hand side mentions nothing defined in this module. Orphan-hood
has two major consequences
* A module that contains orphans is called an "orphan module". If
the module being compiled depends (transitively) on an oprhan
module M, then M.hi is read in regardless of whether M is oherwise
needed. This is to ensure that we don't miss any instance decls in
M. But it's painful, because it means we need to keep track of all
the orphan modules below us.
* A non-orphan is not finger-printed separately. Instead, for
fingerprinting purposes it is treated as part of the entity it
mentions on the LHS. For example
data T = T1 | T2
instance Eq T where ....
The instance (Eq T) is incorprated as part of T's fingerprint.
In constrast, orphans are all fingerprinted together in the
mi_orph_hash field of the ModIface.
See MkIface.addFingerprints.
Orphan-hood is computed
* For class instances:
when we make a ClsInst
(because it is needed during instance lookup)
* For rules and family instances:
when we generate an IfaceRule (MkIface.coreRuleToIfaceRule)
or IfaceFamInst (MkIface.instanceToIfaceInst)
-}
{-
************************************************************************
* *
\subsection{Transformation rules}
* *
************************************************************************
The CoreRule type and its friends are dealt with mainly in CoreRules,
but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
-}
-- | Gathers a collection of 'CoreRule's. Maps (the name of) an 'Id' to its rules
type RuleBase = NameEnv [CoreRule]
-- The rules are unordered;
-- we sort out any overlaps on lookup
-- | A full rule environment which we can apply rules from. Like a 'RuleBase',
-- but it also includes the set of visible orphans we use to filter out orphan
-- rules which are not visible (even though we can see them...)
data RuleEnv
= RuleEnv { re_base :: RuleBase
, re_visible_orphs :: ModuleSet
}
mkRuleEnv :: RuleBase -> [Module] -> RuleEnv
mkRuleEnv rules vis_orphs = RuleEnv rules (mkModuleSet vis_orphs)
emptyRuleEnv :: RuleEnv
emptyRuleEnv = RuleEnv emptyNameEnv emptyModuleSet
-- | A 'CoreRule' is:
--
-- * \"Local\" if the function it is a rule for is defined in the
-- same module as the rule itself.
--
-- * \"Orphan\" if nothing on the LHS is defined in the same module
-- as the rule itself
data CoreRule
= Rule {
ru_name :: RuleName, -- ^ Name of the rule, for communication with the user
ru_act :: Activation, -- ^ When the rule is active
-- Rough-matching stuff
-- see comments with InstEnv.ClsInst( is_cls, is_rough )
ru_fn :: Name, -- ^ Name of the 'Id.Id' at the head of this rule
ru_rough :: [Maybe Name], -- ^ Name at the head of each argument to the left hand side
-- Proper-matching stuff
-- see comments with InstEnv.ClsInst( is_tvs, is_tys )
ru_bndrs :: [CoreBndr], -- ^ Variables quantified over
ru_args :: [CoreExpr], -- ^ Left hand side arguments
-- And the right-hand side
ru_rhs :: CoreExpr, -- ^ Right hand side of the rule
-- Occurrence info is guaranteed correct
-- See Note [OccInfo in unfoldings and rules]
-- Locality
ru_auto :: Bool, -- ^ @True@ <=> this rule is auto-generated
-- @False@ <=> generated at the users behest
-- Main effect: reporting of orphan-hood
ru_origin :: !Module, -- ^ 'Module' the rule was defined in, used
-- to test if we should see an orphan rule.
ru_orphan :: !IsOrphan,
-- ^ Whether or not the rule is an orphan.
ru_local :: Bool -- ^ @True@ iff the fn at the head of the rule is
-- defined in the same module as the rule
-- and is not an implicit 'Id' (like a record selector,
-- class operation, or data constructor). This
-- is different from 'ru_orphan', where a rule
-- can avoid being an orphan if *any* Name in
-- LHS of the rule was defined in the same
-- module as the rule.
}
-- | Built-in rules are used for constant folding
-- and suchlike. They have no free variables.
-- A built-in rule is always visible (there is no such thing as
-- an orphan built-in rule.)
| BuiltinRule {
ru_name :: RuleName, -- ^ As above
ru_fn :: Name, -- ^ As above
ru_nargs :: Int, -- ^ Number of arguments that 'ru_try' consumes,
-- if it fires, including type arguments
ru_try :: RuleFun
-- ^ This function does the rewrite. It given too many
-- arguments, it simply discards them; the returned 'CoreExpr'
-- is just the rewrite of 'ru_fn' applied to the first 'ru_nargs' args
}
-- See Note [Extra args in rule matching] in Rules.hs
type RuleFun = DynFlags -> InScopeEnv -> Id -> [CoreExpr] -> Maybe CoreExpr
type InScopeEnv = (InScopeSet, IdUnfoldingFun)
type IdUnfoldingFun = Id -> Unfolding
-- A function that embodies how to unfold an Id if you need
-- to do that in the Rule. The reason we need to pass this info in
-- is that whether an Id is unfoldable depends on the simplifier phase
isBuiltinRule :: CoreRule -> Bool
isBuiltinRule (BuiltinRule {}) = True
isBuiltinRule _ = False
isAutoRule :: CoreRule -> Bool
isAutoRule (BuiltinRule {}) = False
isAutoRule (Rule { ru_auto = is_auto }) = is_auto
-- | The number of arguments the 'ru_fn' must be applied
-- to before the rule can match on it
ruleArity :: CoreRule -> Int
ruleArity (BuiltinRule {ru_nargs = n}) = n
ruleArity (Rule {ru_args = args}) = length args
ruleName :: CoreRule -> RuleName
ruleName = ru_name
ruleActivation :: CoreRule -> Activation
ruleActivation (BuiltinRule { }) = AlwaysActive
ruleActivation (Rule { ru_act = act }) = act
-- | The 'Name' of the 'Id.Id' at the head of the rule left hand side
ruleIdName :: CoreRule -> Name
ruleIdName = ru_fn
isLocalRule :: CoreRule -> Bool
isLocalRule = ru_local
-- | Set the 'Name' of the 'Id.Id' at the head of the rule left hand side
setRuleIdName :: Name -> CoreRule -> CoreRule
setRuleIdName nm ru = ru { ru_fn = nm }
{-
************************************************************************
* *
\subsection{Vectorisation declarations}
* *
************************************************************************
Representation of desugared vectorisation declarations that are fed to the vectoriser (via
'ModGuts').
-}
data CoreVect = Vect Id CoreExpr
| NoVect Id
| VectType Bool TyCon (Maybe TyCon)
| VectClass TyCon -- class tycon
| VectInst Id -- instance dfun (always SCALAR) !!!FIXME: should be superfluous now
{-
************************************************************************
* *
Unfoldings
* *
************************************************************************
The @Unfolding@ type is declared here to avoid numerous loops
-}
-- | Records the /unfolding/ of an identifier, which is approximately the form the
-- identifier would have if we substituted its definition in for the identifier.
-- This type should be treated as abstract everywhere except in "CoreUnfold"
data Unfolding
= NoUnfolding -- ^ We have no information about the unfolding
| OtherCon [AltCon] -- ^ It ain't one of these constructors.
-- @OtherCon xs@ also indicates that something has been evaluated
-- and hence there's no point in re-evaluating it.
-- @OtherCon []@ is used even for non-data-type values
-- to indicated evaluated-ness. Notably:
--
-- > data C = C !(Int -> Int)
-- > case x of { C f -> ... }
--
-- Here, @f@ gets an @OtherCon []@ unfolding.
| DFunUnfolding { -- The Unfolding of a DFunId
-- See Note [DFun unfoldings]
-- df = /\a1..am. \d1..dn. MkD t1 .. tk
-- (op1 a1..am d1..dn)
-- (op2 a1..am d1..dn)
df_bndrs :: [Var], -- The bound variables [a1..m],[d1..dn]
df_con :: DataCon, -- The dictionary data constructor (never a newtype datacon)
df_args :: [CoreExpr] -- Args of the data con: types, superclasses and methods,
} -- in positional order
| CoreUnfolding { -- An unfolding for an Id with no pragma,
-- or perhaps a NOINLINE pragma
-- (For NOINLINE, the phase, if any, is in the
-- InlinePragInfo for this Id.)
uf_tmpl :: CoreExpr, -- Template; occurrence info is correct
uf_src :: UnfoldingSource, -- Where the unfolding came from
uf_is_top :: Bool, -- True <=> top level binding
uf_is_value :: Bool, -- exprIsHNF template (cached); it is ok to discard
-- a `seq` on this variable
uf_is_conlike :: Bool, -- True <=> applicn of constructor or CONLIKE function
-- Cached version of exprIsConLike
uf_is_work_free :: Bool, -- True <=> doesn't waste (much) work to expand
-- inside an inlining
-- Cached version of exprIsCheap
uf_expandable :: Bool, -- True <=> can expand in RULE matching
-- Cached version of exprIsExpandable
uf_guidance :: UnfoldingGuidance -- Tells about the *size* of the template.
}
-- ^ An unfolding with redundant cached information. Parameters:
--
-- uf_tmpl: Template used to perform unfolding;
-- NB: Occurrence info is guaranteed correct:
-- see Note [OccInfo in unfoldings and rules]
--
-- uf_is_top: Is this a top level binding?
--
-- uf_is_value: 'exprIsHNF' template (cached); it is ok to discard a 'seq' on
-- this variable
--
-- uf_is_work_free: Does this waste only a little work if we expand it inside an inlining?
-- Basically this is a cached version of 'exprIsWorkFree'
--
-- uf_guidance: Tells us about the /size/ of the unfolding template
------------------------------------------------
data UnfoldingSource
= -- See also Note [Historical note: unfoldings for wrappers]
InlineRhs -- The current rhs of the function
-- Replace uf_tmpl each time around
| InlineStable -- From an INLINE or INLINABLE pragma
-- INLINE if guidance is UnfWhen
-- INLINABLE if guidance is UnfIfGoodArgs/UnfoldNever
-- (well, technically an INLINABLE might be made
-- UnfWhen if it was small enough, and then
-- it will behave like INLINE outside the current
-- module, but that is the way automatic unfoldings
-- work so it is consistent with the intended
-- meaning of INLINABLE).
--
-- uf_tmpl may change, but only as a result of
-- gentle simplification, it doesn't get updated
-- to the current RHS during compilation as with
-- InlineRhs.
--
-- See Note [InlineRules]
| InlineCompulsory -- Something that *has* no binding, so you *must* inline it
-- Only a few primop-like things have this property
-- (see MkId.hs, calls to mkCompulsoryUnfolding).
-- Inline absolutely always, however boring the context.
-- | 'UnfoldingGuidance' says when unfolding should take place
data UnfoldingGuidance
= UnfWhen { -- Inline without thinking about the *size* of the uf_tmpl
-- Used (a) for small *and* cheap unfoldings
-- (b) for INLINE functions
-- See Note [INLINE for small functions] in CoreUnfold
ug_arity :: Arity, -- Number of value arguments expected
ug_unsat_ok :: Bool, -- True <=> ok to inline even if unsaturated
ug_boring_ok :: Bool -- True <=> ok to inline even if the context is boring
-- So True,True means "always"
}
| UnfIfGoodArgs { -- Arose from a normal Id; the info here is the
-- result of a simple analysis of the RHS
ug_args :: [Int], -- Discount if the argument is evaluated.
-- (i.e., a simplification will definitely
-- be possible). One elt of the list per *value* arg.
ug_size :: Int, -- The "size" of the unfolding.
ug_res :: Int -- Scrutinee discount: the discount to substract if the thing is in
} -- a context (case (thing args) of ...),
-- (where there are the right number of arguments.)
| UnfNever -- The RHS is big, so don't inline it
deriving (Eq)
{-
Note [Historical note: unfoldings for wrappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used to have a nice clever scheme in interface files for
wrappers. A wrapper's unfolding can be reconstructed from its worker's
id and its strictness. This decreased .hi file size (sometimes
significantly, for modules like GHC.Classes with many high-arity w/w
splits) and had a slight corresponding effect on compile times.
However, when we added the second demand analysis, this scheme lead to
some Core lint errors. The second analysis could change the strictness
signatures, which sometimes resulted in a wrapper's regenerated
unfolding applying the wrapper to too many arguments.
Instead of repairing the clever .hi scheme, we abandoned it in favor
of simplicity. The .hi sizes are usually insignificant (excluding the
+1M for base libraries), and compile time barely increases (~+1% for
nofib). The nicer upshot is that the UnfoldingSource no longer mentions
an Id, so, eg, substitutions need not traverse them.
Note [DFun unfoldings]
~~~~~~~~~~~~~~~~~~~~~~
The Arity in a DFunUnfolding is total number of args (type and value)
that the DFun needs to produce a dictionary. That's not necessarily
related to the ordinary arity of the dfun Id, esp if the class has
one method, so the dictionary is represented by a newtype. Example
class C a where { op :: a -> Int }
instance C a -> C [a] where op xs = op (head xs)
The instance translates to
$dfCList :: forall a. C a => C [a] -- Arity 2!
$dfCList = /\a.\d. $copList {a} d |> co
$copList :: forall a. C a => [a] -> Int -- Arity 2!
$copList = /\a.\d.\xs. op {a} d (head xs)
Now we might encounter (op (dfCList {ty} d) a1 a2)
and we want the (op (dfList {ty} d)) rule to fire, because $dfCList
has all its arguments, even though its (value) arity is 2. That's
why we record the number of expected arguments in the DFunUnfolding.
Note that although it's an Arity, it's most convenient for it to give
the *total* number of arguments, both type and value. See the use
site in exprIsConApp_maybe.
-}
-- Constants for the UnfWhen constructor
needSaturated, unSaturatedOk :: Bool
needSaturated = False
unSaturatedOk = True
boringCxtNotOk, boringCxtOk :: Bool
boringCxtOk = True
boringCxtNotOk = False
------------------------------------------------
noUnfolding :: Unfolding
-- ^ There is no known 'Unfolding'
evaldUnfolding :: Unfolding
-- ^ This unfolding marks the associated thing as being evaluated
noUnfolding = NoUnfolding
evaldUnfolding = OtherCon []
mkOtherCon :: [AltCon] -> Unfolding
mkOtherCon = OtherCon
isStableSource :: UnfoldingSource -> Bool
-- Keep the unfolding template
isStableSource InlineCompulsory = True
isStableSource InlineStable = True
isStableSource InlineRhs = False
-- | Retrieves the template of an unfolding: panics if none is known
unfoldingTemplate :: Unfolding -> CoreExpr
unfoldingTemplate = uf_tmpl
-- | Retrieves the template of an unfolding if possible
-- maybeUnfoldingTemplate is used mainly wnen specialising, and we do
-- want to specialise DFuns, so it's important to return a template
-- for DFunUnfoldings
maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
maybeUnfoldingTemplate (CoreUnfolding { uf_tmpl = expr })
= Just expr
maybeUnfoldingTemplate (DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args })
= Just (mkLams bndrs (mkApps (Var (dataConWorkId con)) args))
maybeUnfoldingTemplate _
= Nothing
-- | The constructors that the unfolding could never be:
-- returns @[]@ if no information is available
otherCons :: Unfolding -> [AltCon]
otherCons (OtherCon cons) = cons
otherCons _ = []
-- | Determines if it is certainly the case that the unfolding will
-- yield a value (something in HNF): returns @False@ if unsure
isValueUnfolding :: Unfolding -> Bool
-- Returns False for OtherCon
isValueUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
isValueUnfolding _ = False
-- | Determines if it possibly the case that the unfolding will
-- yield a value. Unlike 'isValueUnfolding' it returns @True@
-- for 'OtherCon'
isEvaldUnfolding :: Unfolding -> Bool
-- Returns True for OtherCon
isEvaldUnfolding (OtherCon _) = True
isEvaldUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
isEvaldUnfolding _ = False
-- | @True@ if the unfolding is a constructor application, the application
-- of a CONLIKE function or 'OtherCon'
isConLikeUnfolding :: Unfolding -> Bool
isConLikeUnfolding (OtherCon _) = True
isConLikeUnfolding (CoreUnfolding { uf_is_conlike = con }) = con
isConLikeUnfolding _ = False
-- | Is the thing we will unfold into certainly cheap?
isCheapUnfolding :: Unfolding -> Bool
isCheapUnfolding (CoreUnfolding { uf_is_work_free = is_wf }) = is_wf
isCheapUnfolding _ = False
isExpandableUnfolding :: Unfolding -> Bool
isExpandableUnfolding (CoreUnfolding { uf_expandable = is_expable }) = is_expable
isExpandableUnfolding _ = False
expandUnfolding_maybe :: Unfolding -> Maybe CoreExpr
-- Expand an expandable unfolding; this is used in rule matching
-- See Note [Expanding variables] in Rules.hs
-- The key point here is that CONLIKE things can be expanded
expandUnfolding_maybe (CoreUnfolding { uf_expandable = True, uf_tmpl = rhs }) = Just rhs
expandUnfolding_maybe _ = Nothing
hasStableCoreUnfolding_maybe :: Unfolding -> Maybe Bool
-- Just True <=> has stable inlining, very keen to inline (eg. INLINE pragma)
-- Just False <=> has stable inlining, open to inlining it (eg. INLINEABLE pragma)
-- Nothing <=> not stable, or cannot inline it anyway
hasStableCoreUnfolding_maybe (CoreUnfolding { uf_src = src, uf_guidance = guide })
| isStableSource src
= case guide of
UnfWhen {} -> Just True
UnfIfGoodArgs {} -> Just False
UnfNever -> Nothing
hasStableCoreUnfolding_maybe _ = Nothing
isCompulsoryUnfolding :: Unfolding -> Bool
isCompulsoryUnfolding (CoreUnfolding { uf_src = InlineCompulsory }) = True
isCompulsoryUnfolding _ = False
isStableUnfolding :: Unfolding -> Bool
-- True of unfoldings that should not be overwritten
-- by a CoreUnfolding for the RHS of a let-binding
isStableUnfolding (CoreUnfolding { uf_src = src }) = isStableSource src
isStableUnfolding (DFunUnfolding {}) = True
isStableUnfolding _ = False
isClosedUnfolding :: Unfolding -> Bool -- No free variables
isClosedUnfolding (CoreUnfolding {}) = False
isClosedUnfolding (DFunUnfolding {}) = False
isClosedUnfolding _ = True
-- | Only returns False if there is no unfolding information available at all
hasSomeUnfolding :: Unfolding -> Bool
hasSomeUnfolding NoUnfolding = False
hasSomeUnfolding _ = True
neverUnfoldGuidance :: UnfoldingGuidance -> Bool
neverUnfoldGuidance UnfNever = True
neverUnfoldGuidance _ = False
canUnfold :: Unfolding -> Bool
canUnfold (CoreUnfolding { uf_guidance = g }) = not (neverUnfoldGuidance g)
canUnfold _ = False
{-
Note [InlineRules]
~~~~~~~~~~~~~~~~~
When you say
{-# INLINE f #-}
f x = <rhs>
you intend that calls (f e) are replaced by <rhs>[e/x] So we
should capture (\x.<rhs>) in the Unfolding of 'f', and never meddle
with it. Meanwhile, we can optimise <rhs> to our heart's content,
leaving the original unfolding intact in Unfolding of 'f'. For example
all xs = foldr (&&) True xs
any p = all . map p {-# INLINE any #-}
We optimise any's RHS fully, but leave the InlineRule saying "all . map p",
which deforests well at the call site.
So INLINE pragma gives rise to an InlineRule, which captures the original RHS.
Moreover, it's only used when 'f' is applied to the
specified number of arguments; that is, the number of argument on
the LHS of the '=' sign in the original source definition.
For example, (.) is now defined in the libraries like this
{-# INLINE (.) #-}
(.) f g = \x -> f (g x)
so that it'll inline when applied to two arguments. If 'x' appeared
on the left, thus
(.) f g x = f (g x)
it'd only inline when applied to three arguments. This slightly-experimental
change was requested by Roman, but it seems to make sense.
See also Note [Inlining an InlineRule] in CoreUnfold.
Note [OccInfo in unfoldings and rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In unfoldings and rules, we guarantee that the template is occ-analysed,
so that the occurrence info on the binders is correct. This is important,
because the Simplifier does not re-analyse the template when using it. If
the occurrence info is wrong
- We may get more simpifier iterations than necessary, because
once-occ info isn't there
- More seriously, we may get an infinite loop if there's a Rec
without a loop breaker marked
************************************************************************
* *
AltCon
* *
************************************************************************
-}
-- The Ord is needed for the FiniteMap used in the lookForConstructor
-- in SimplEnv. If you declared that lookForConstructor *ignores*
-- constructor-applications with LitArg args, then you could get
-- rid of this Ord.
instance Outputable AltCon where
ppr (DataAlt dc) = ppr dc
ppr (LitAlt lit) = ppr lit
ppr DEFAULT = text "__DEFAULT"
cmpAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Ordering
cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
ltAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Bool
ltAlt a1 a2 = (a1 `cmpAlt` a2) == LT
cmpAltCon :: AltCon -> AltCon -> Ordering
-- ^ Compares 'AltCon's within a single list of alternatives
cmpAltCon DEFAULT DEFAULT = EQ
cmpAltCon DEFAULT _ = LT
cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
cmpAltCon (DataAlt _) DEFAULT = GT
cmpAltCon (LitAlt l1) (LitAlt l2) = l1 `compare` l2
cmpAltCon (LitAlt _) DEFAULT = GT
cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+>
ppr con1 <+> ppr con2 )
LT
{-
************************************************************************
* *
\subsection{Useful synonyms}
* *
************************************************************************
Note [CoreProgram]
~~~~~~~~~~~~~~~~~~
The top level bindings of a program, a CoreProgram, are represented as
a list of CoreBind
* Later bindings in the list can refer to earlier ones, but not vice
versa. So this is OK
NonRec { x = 4 }
Rec { p = ...q...x...
; q = ...p...x }
Rec { f = ...p..x..f.. }
NonRec { g = ..f..q...x.. }
But it would NOT be ok for 'f' to refer to 'g'.
* The occurrence analyser does strongly-connected component analysis
on each Rec binding, and splits it into a sequence of smaller
bindings where possible. So the program typically starts life as a
single giant Rec, which is then dependency-analysed into smaller
chunks.
-}
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
type CoreProgram = [CoreBind] -- See Note [CoreProgram]
-- | The common case for the type of binders and variables when
-- we are manipulating the Core language within GHC
type CoreBndr = Var
-- | Expressions where binders are 'CoreBndr's
type CoreExpr = Expr CoreBndr
-- | Argument expressions where binders are 'CoreBndr's
type CoreArg = Arg CoreBndr
-- | Binding groups where binders are 'CoreBndr's
type CoreBind = Bind CoreBndr
-- | Case alternatives where binders are 'CoreBndr's
type CoreAlt = Alt CoreBndr
{-
************************************************************************
* *
\subsection{Tagging}
* *
************************************************************************
-}
-- | Binders are /tagged/ with a t
data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
type TaggedBind t = Bind (TaggedBndr t)
type TaggedExpr t = Expr (TaggedBndr t)
type TaggedArg t = Arg (TaggedBndr t)
type TaggedAlt t = Alt (TaggedBndr t)
instance Outputable b => Outputable (TaggedBndr b) where
ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
instance Outputable b => OutputableBndr (TaggedBndr b) where
pprBndr _ b = ppr b -- Simple
pprInfixOcc b = ppr b
pprPrefixOcc b = ppr b
deTagExpr :: TaggedExpr t -> CoreExpr
deTagExpr (Var v) = Var v
deTagExpr (Lit l) = Lit l
deTagExpr (Type ty) = Type ty
deTagExpr (Coercion co) = Coercion co
deTagExpr (App e1 e2) = App (deTagExpr e1) (deTagExpr e2)
deTagExpr (Lam (TB b _) e) = Lam b (deTagExpr e)
deTagExpr (Let bind body) = Let (deTagBind bind) (deTagExpr body)
deTagExpr (Case e (TB b _) ty alts) = Case (deTagExpr e) b ty (map deTagAlt alts)
deTagExpr (Tick t e) = Tick t (deTagExpr e)
deTagExpr (Cast e co) = Cast (deTagExpr e) co
deTagBind :: TaggedBind t -> CoreBind
deTagBind (NonRec (TB b _) rhs) = NonRec b (deTagExpr rhs)
deTagBind (Rec prs) = Rec [(b, deTagExpr rhs) | (TB b _, rhs) <- prs]
deTagAlt :: TaggedAlt t -> CoreAlt
deTagAlt (con, bndrs, rhs) = (con, [b | TB b _ <- bndrs], deTagExpr rhs)
{-
************************************************************************
* *
\subsection{Core-constructing functions with checking}
* *
************************************************************************
-}
-- | Apply a list of argument expressions to a function expression in a nested fashion. Prefer to
-- use 'MkCore.mkCoreApps' if possible
mkApps :: Expr b -> [Arg b] -> Expr b
-- | Apply a list of type argument expressions to a function expression in a nested fashion
mkTyApps :: Expr b -> [Type] -> Expr b
-- | Apply a list of coercion argument expressions to a function expression in a nested fashion
mkCoApps :: Expr b -> [Coercion] -> Expr b
-- | Apply a list of type or value variables to a function expression in a nested fashion
mkVarApps :: Expr b -> [Var] -> Expr b
-- | Apply a list of argument expressions to a data constructor in a nested fashion. Prefer to
-- use 'MkCore.mkCoreConApps' if possible
mkConApp :: DataCon -> [Arg b] -> Expr b
mkApps f args = foldl App f args
mkCoApps f args = foldl (\ e a -> App e (Coercion a)) f args
mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
mkConApp con args = mkApps (Var (dataConWorkId con)) args
mkTyApps f args = foldl (\ e a -> App e (typeOrCoercion a)) f args
where
typeOrCoercion ty
| Just co <- isCoercionTy_maybe ty = Coercion co
| otherwise = Type ty
mkConApp2 :: DataCon -> [Type] -> [Var] -> Expr b
mkConApp2 con tys arg_ids = Var (dataConWorkId con)
`mkApps` map Type tys
`mkApps` map varToCoreExpr arg_ids
-- | Create a machine integer literal expression of type @Int#@ from an @Integer@.
-- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
mkIntLit :: DynFlags -> Integer -> Expr b
-- | Create a machine integer literal expression of type @Int#@ from an @Int@.
-- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
mkIntLitInt :: DynFlags -> Int -> Expr b
mkIntLit dflags n = Lit (mkMachInt dflags n)
mkIntLitInt dflags n = Lit (mkMachInt dflags (toInteger n))
-- | Create a machine word literal expression of type @Word#@ from an @Integer@.
-- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
mkWordLit :: DynFlags -> Integer -> Expr b
-- | Create a machine word literal expression of type @Word#@ from a @Word@.
-- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
mkWordLitWord :: DynFlags -> Word -> Expr b
mkWordLit dflags w = Lit (mkMachWord dflags w)
mkWordLitWord dflags w = Lit (mkMachWord dflags (toInteger w))
mkWord64LitWord64 :: Word64 -> Expr b
mkWord64LitWord64 w = Lit (mkMachWord64 (toInteger w))
mkInt64LitInt64 :: Int64 -> Expr b
mkInt64LitInt64 w = Lit (mkMachInt64 (toInteger w))
-- | Create a machine character literal expression of type @Char#@.
-- If you want an expression of type @Char@ use 'MkCore.mkCharExpr'
mkCharLit :: Char -> Expr b
-- | Create a machine string literal expression of type @Addr#@.
-- If you want an expression of type @String@ use 'MkCore.mkStringExpr'
mkStringLit :: String -> Expr b
mkCharLit c = Lit (mkMachChar c)
mkStringLit s = Lit (mkMachString s)
-- | Create a machine single precision literal expression of type @Float#@ from a @Rational@.
-- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
mkFloatLit :: Rational -> Expr b
-- | Create a machine single precision literal expression of type @Float#@ from a @Float@.
-- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
mkFloatLitFloat :: Float -> Expr b
mkFloatLit f = Lit (mkMachFloat f)
mkFloatLitFloat f = Lit (mkMachFloat (toRational f))
-- | Create a machine double precision literal expression of type @Double#@ from a @Rational@.
-- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
mkDoubleLit :: Rational -> Expr b
-- | Create a machine double precision literal expression of type @Double#@ from a @Double@.
-- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
mkDoubleLitDouble :: Double -> Expr b
mkDoubleLit d = Lit (mkMachDouble d)
mkDoubleLitDouble d = Lit (mkMachDouble (toRational d))
-- | Bind all supplied binding groups over an expression in a nested let expression. Assumes
-- that the rhs satisfies the let/app invariant. Prefer to use 'MkCore.mkCoreLets' if
-- possible, which does guarantee the invariant
mkLets :: [Bind b] -> Expr b -> Expr b
-- | Bind all supplied binders over an expression in a nested lambda expression. Prefer to
-- use 'MkCore.mkCoreLams' if possible
mkLams :: [b] -> Expr b -> Expr b
mkLams binders body = foldr Lam body binders
mkLets binds body = foldr Let body binds
-- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
-- this can only be used to bind something in a non-recursive @let@ expression
mkTyBind :: TyVar -> Type -> CoreBind
mkTyBind tv ty = NonRec tv (Type ty)
-- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
-- this can only be used to bind something in a non-recursive @let@ expression
mkCoBind :: CoVar -> Coercion -> CoreBind
mkCoBind cv co = NonRec cv (Coercion co)
-- | Convert a binder into either a 'Var' or 'Type' 'Expr' appropriately
varToCoreExpr :: CoreBndr -> Expr b
varToCoreExpr v | isTyVar v = Type (mkTyVarTy v)
| isCoVar v = Coercion (mkCoVarCo v)
| otherwise = ASSERT( isId v ) Var v
varsToCoreExprs :: [CoreBndr] -> [Expr b]
varsToCoreExprs vs = map varToCoreExpr vs
{-
************************************************************************
* *
Getting a result type
* *
************************************************************************
These are defined here to avoid a module loop between CoreUtils and CoreFVs
-}
applyTypeToArg :: Type -> CoreExpr -> Type
-- ^ Determines the type resulting from applying an expression with given type
-- to a given argument expression
applyTypeToArg fun_ty arg = piResultTy fun_ty (exprToType arg)
-- | If the expression is a 'Type', converts. Otherwise,
-- panics. NB: This does /not/ convert 'Coercion' to 'CoercionTy'.
exprToType :: CoreExpr -> Type
exprToType (Type ty) = ty
exprToType _bad = pprPanic "exprToType" empty
-- | If the expression is a 'Coercion', converts.
exprToCoercion_maybe :: CoreExpr -> Maybe Coercion
exprToCoercion_maybe (Coercion co) = Just co
exprToCoercion_maybe _ = Nothing
{-
************************************************************************
* *
\subsection{Simple access functions}
* *
************************************************************************
-}
-- | Extract every variable by this group
bindersOf :: Bind b -> [b]
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
bindersOf (NonRec binder _) = [binder]
bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
-- | 'bindersOf' applied to a list of binding groups
bindersOfBinds :: [Bind b] -> [b]
bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
rhssOfBind :: Bind b -> [Expr b]
rhssOfBind (NonRec _ rhs) = [rhs]
rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
rhssOfAlts :: [Alt b] -> [Expr b]
rhssOfAlts alts = [e | (_,_,e) <- alts]
-- | Collapse all the bindings in the supplied groups into a single
-- list of lhs\/rhs pairs suitable for binding in a 'Rec' binding group
flattenBinds :: [Bind b] -> [(b, Expr b)]
flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
flattenBinds [] = []
-- | We often want to strip off leading lambdas before getting down to
-- business. This function is your friend.
collectBinders :: Expr b -> ([b], Expr b)
-- | Collect type and value binders from nested lambdas, stopping
-- right before any "forall"s within a non-forall. For example,
-- forall (a :: *) (b :: Foo ~ Bar) (c :: *). Baz -> forall (d :: *). Blob
-- will pull out the binders for a, b, c, and Baz, but not for d or anything
-- within Blob. This is to coordinate with tcSplitSigmaTy.
collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
collectBinders expr
= go [] expr
where
go bs (Lam b e) = go (b:bs) e
go bs e = (reverse bs, e)
collectTyAndValBinders expr
= go_forall [] [] expr
where go_forall tvs ids (Lam b e)
| isTyVar b = go_forall (b:tvs) ids e
| isCoVar b = go_forall tvs (b:ids) e
go_forall tvs ids e = go_fun tvs ids e
go_fun tvs ids (Lam b e)
| isId b = go_fun tvs (b:ids) e
go_fun tvs ids e = (reverse tvs, reverse ids, e)
-- | Takes a nested application expression and returns the the function
-- being applied and the arguments to which it is applied
collectArgs :: Expr b -> (Expr b, [Arg b])
collectArgs expr
= go expr []
where
go (App f a) as = go f (a:as)
go e as = (e, as)
-- | Like @collectArgs@, but also collects looks through floatable
-- ticks if it means that we can find more arguments.
collectArgsTicks :: (Tickish Id -> Bool) -> Expr b
-> (Expr b, [Arg b], [Tickish Id])
collectArgsTicks skipTick expr
= go expr [] []
where
go (App f a) as ts = go f (a:as) ts
go (Tick t e) as ts
| skipTick t = go e as (t:ts)
go e as ts = (e, as, reverse ts)
{-
************************************************************************
* *
\subsection{Predicates}
* *
************************************************************************
At one time we optionally carried type arguments through to runtime.
@isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
i.e. if type applications are actual lambdas because types are kept around
at runtime. Similarly isRuntimeArg.
-}
-- | Will this variable exist at runtime?
isRuntimeVar :: Var -> Bool
isRuntimeVar = isId
-- | Will this argument expression exist at runtime?
isRuntimeArg :: CoreExpr -> Bool
isRuntimeArg = isValArg
-- | Returns @True@ for value arguments, false for type args
-- NB: coercions are value arguments (zero width, to be sure,
-- like State#, but still value args).
isValArg :: Expr b -> Bool
isValArg e = not (isTypeArg e)
-- | Returns @True@ iff the expression is a 'Type' or 'Coercion'
-- expression at its top level
isTyCoArg :: Expr b -> Bool
isTyCoArg (Type {}) = True
isTyCoArg (Coercion {}) = True
isTyCoArg _ = False
-- | Returns @True@ iff the expression is a 'Type' expression at its
-- top level. Note this does NOT include 'Coercion's.
isTypeArg :: Expr b -> Bool
isTypeArg (Type {}) = True
isTypeArg _ = False
-- | The number of binders that bind values rather than types
valBndrCount :: [CoreBndr] -> Int
valBndrCount = count isId
-- | The number of argument expressions that are values rather than types at their top level
valArgCount :: [Arg b] -> Int
valArgCount = count isValArg
{-
************************************************************************
* *
\subsection{Annotated core}
* *
************************************************************************
-}
-- | Annotated core: allows annotation at every node in the tree
type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
-- | A clone of the 'Expr' type but allowing annotation at every tree node
data AnnExpr' bndr annot
= AnnVar Id
| AnnLit Literal
| AnnLam bndr (AnnExpr bndr annot)
| AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
| AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
| AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
| AnnCast (AnnExpr bndr annot) (annot, Coercion)
-- Put an annotation on the (root of) the coercion
| AnnTick (Tickish Id) (AnnExpr bndr annot)
| AnnType Type
| AnnCoercion Coercion
-- | A clone of the 'Alt' type but allowing annotation at every tree node
type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
-- | A clone of the 'Bind' type but allowing annotation at every tree node
data AnnBind bndr annot
= AnnNonRec bndr (AnnExpr bndr annot)
| AnnRec [(bndr, AnnExpr bndr annot)]
-- | Takes a nested application expression and returns the the function
-- being applied and the arguments to which it is applied
collectAnnArgs :: AnnExpr b a -> (AnnExpr b a, [AnnExpr b a])
collectAnnArgs expr
= go expr []
where
go (_, AnnApp f a) as = go f (a:as)
go e as = (e, as)
collectAnnArgsTicks :: (Tickish Var -> Bool) -> AnnExpr b a
-> (AnnExpr b a, [AnnExpr b a], [Tickish Var])
collectAnnArgsTicks tickishOk expr
= go expr [] []
where
go (_, AnnApp f a) as ts = go f (a:as) ts
go (_, AnnTick t e) as ts | tickishOk t
= go e as (t:ts)
go e as ts = (e, as, reverse ts)
deAnnotate :: AnnExpr bndr annot -> Expr bndr
deAnnotate (_, e) = deAnnotate' e
deAnnotate' :: AnnExpr' bndr annot -> Expr bndr
deAnnotate' (AnnType t) = Type t
deAnnotate' (AnnCoercion co) = Coercion co
deAnnotate' (AnnVar v) = Var v
deAnnotate' (AnnLit lit) = Lit lit
deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
deAnnotate' (AnnCast e (_,co)) = Cast (deAnnotate e) co
deAnnotate' (AnnTick tick body) = Tick tick (deAnnotate body)
deAnnotate' (AnnLet bind body)
= Let (deAnnBind bind) (deAnnotate body)
where
deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
deAnnotate' (AnnCase scrut v t alts)
= Case (deAnnotate scrut) v t (map deAnnAlt alts)
deAnnAlt :: AnnAlt bndr annot -> Alt bndr
deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
-- | As 'collectBinders' but for 'AnnExpr' rather than 'Expr'
collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
collectAnnBndrs e
= collect [] e
where
collect bs (_, AnnLam b body) = collect (b:bs) body
collect bs body = (reverse bs, body)
| nushio3/ghc | compiler/coreSyn/CoreSyn.hs | bsd-3-clause | 73,179 | 0 | 14 | 19,898 | 8,479 | 4,816 | 3,663 | 593 | 5 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/IntMap/Internal.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash, DeriveDataTypeable, StandaloneDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.IntMap.Internal
-- Copyright : (c) Daan Leijen 2002
-- (c) Andriy Palamarchuk 2008
-- (c) wren romano 2016
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : portable
--
-- = WARNING
--
-- This module is considered __internal__.
--
-- The Package Versioning Policy __does not apply__.
--
-- This contents of this module may change __in any way whatsoever__
-- and __without any warning__ between minor versions of this package.
--
-- Authors importing this module are expected to track development
-- closely.
--
-- = Description
--
-- This defines the data structures and core (hidden) manipulations
-- on representations.
-----------------------------------------------------------------------------
-- [Note: INLINE bit fiddling]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- It is essential that the bit fiddling functions like mask, zero, branchMask
-- etc are inlined. If they do not, the memory allocation skyrockets. The GHC
-- usually gets it right, but it is disastrous if it does not. Therefore we
-- explicitly mark these functions INLINE.
-- [Note: Local 'go' functions and capturing]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Care must be taken when using 'go' function which captures an argument.
-- Sometimes (for example when the argument is passed to a data constructor,
-- as in insert), GHC heap-allocates more than necessary. Therefore C-- code
-- must be checked for increased allocation when creating and modifying such
-- functions.
-- [Note: Order of constructors]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The order of constructors of IntMap matters when considering performance.
-- Currently in GHC 7.0, when type has 3 constructors, they are matched from
-- the first to the last -- the best performance is achieved when the
-- constructors are ordered by frequency.
-- On GHC 7.0, reordering constructors from Nil | Tip | Bin to Bin | Tip | Nil
-- improves the benchmark by circa 10%.
module Data.IntMap.Internal (
-- * Map type
IntMap(..), Key -- instance Eq,Show
-- * Operators
, (!), (\\)
-- * Query
, null
, size
, member
, notMember
, lookup
, findWithDefault
, lookupLT
, lookupGT
, lookupLE
, lookupGE
-- * Construction
, empty
, singleton
-- ** Insertion
, insert
, insertWith
, insertWithKey
, insertLookupWithKey
-- ** Delete\/Update
, delete
, adjust
, adjustWithKey
, update
, updateWithKey
, updateLookupWithKey
, alter
, alterF
-- * Combine
-- ** Union
, union
, unionWith
, unionWithKey
, unions
, unionsWith
-- ** Difference
, difference
, differenceWith
, differenceWithKey
-- ** Intersection
, intersection
, intersectionWith
, intersectionWithKey
-- ** General combining function
, SimpleWhenMissing
, SimpleWhenMatched
, runWhenMatched
, runWhenMissing
, merge
-- *** @WhenMatched@ tactics
, zipWithMaybeMatched
, zipWithMatched
-- *** @WhenMissing@ tactics
, mapMaybeMissing
, dropMissing
, preserveMissing
, mapMissing
, filterMissing
-- ** Applicative general combining function
, WhenMissing (..)
, WhenMatched (..)
, mergeA
-- *** @WhenMatched@ tactics
-- | The tactics described for 'merge' work for
-- 'mergeA' as well. Furthermore, the following
-- are available.
, zipWithMaybeAMatched
, zipWithAMatched
-- *** @WhenMissing@ tactics
-- | The tactics described for 'merge' work for
-- 'mergeA' as well. Furthermore, the following
-- are available.
, traverseMaybeMissing
, traverseMissing
, filterAMissing
-- ** Deprecated general combining function
, mergeWithKey
, mergeWithKey'
-- * Traversal
-- ** Map
, map
, mapWithKey
, traverseWithKey
, mapAccum
, mapAccumWithKey
, mapAccumRWithKey
, mapKeys
, mapKeysWith
, mapKeysMonotonic
-- * Folds
, foldr
, foldl
, foldrWithKey
, foldlWithKey
, foldMapWithKey
-- ** Strict folds
, foldr'
, foldl'
, foldrWithKey'
, foldlWithKey'
-- * Conversion
, elems
, keys
, assocs
, keysSet
, fromSet
-- ** Lists
, toList
, fromList
, fromListWith
, fromListWithKey
-- ** Ordered lists
, toAscList
, toDescList
, fromAscList
, fromAscListWith
, fromAscListWithKey
, fromDistinctAscList
-- * Filter
, filter
, filterWithKey
, restrictKeys
, withoutKeys
, partition
, partitionWithKey
, mapMaybe
, mapMaybeWithKey
, mapEither
, mapEitherWithKey
, split
, splitLookup
, splitRoot
-- * Submap
, isSubmapOf, isSubmapOfBy
, isProperSubmapOf, isProperSubmapOfBy
-- * Min\/Max
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, updateMin
, updateMax
, updateMinWithKey
, updateMaxWithKey
, minView
, maxView
, minViewWithKey
, maxViewWithKey
-- * Debugging
, showTree
, showTreeWith
-- * Internal types
, Mask, Prefix, Nat
-- * Utility
, natFromInt
, intFromNat
, link
, bin
, binCheckLeft
, binCheckRight
, zero
, nomatch
, match
, mask
, maskW
, shorter
, branchMask
, highestBitMask
-- * Used by "IntMap.Merge.Lazy" and "IntMap.Merge.Strict"
, mapWhenMissing
, mapWhenMatched
, lmapWhenMissing
, contramapFirstWhenMatched
, contramapSecondWhenMatched
, mapGentlyWhenMissing
, mapGentlyWhenMatched
) where
import Data.Functor.Identity (Identity (..))
import Control.Applicative (liftA2)
import Data.Semigroup (Semigroup((<>), stimes), stimesIdempotentMonoid)
import Data.Functor.Classes
import Control.DeepSeq (NFData(rnf))
import Control.Monad (liftM)
import Data.Bits
import qualified Data.Foldable as Foldable
import Data.Maybe (fromMaybe)
import Data.Typeable
import Prelude hiding (lookup, map, filter, foldr, foldl, null)
import Data.IntSet.Internal (Key)
import qualified Data.IntSet.Internal as IntSet
import Utils.Containers.Internal.BitUtil
import Utils.Containers.Internal.StrictFold
import Utils.Containers.Internal.StrictPair
import Data.Data (Data(..), Constr, mkConstr, constrIndex, Fixity(Prefix),
DataType, mkDataType)
import GHC.Exts (build)
import qualified GHC.Exts as GHCExts
import Text.Read
import qualified Control.Category as Category
import Data.Coerce
-- A "Nat" is a natural machine word (an unsigned Int)
type Nat = Word
natFromInt :: Key -> Nat
natFromInt = fromIntegral
{-# INLINE natFromInt #-}
intFromNat :: Nat -> Key
intFromNat = fromIntegral
{-# INLINE intFromNat #-}
{--------------------------------------------------------------------
Types
--------------------------------------------------------------------}
-- | A map of integers to values @a@.
-- See Note: Order of constructors
data IntMap a = Bin {-# UNPACK #-} !Prefix
{-# UNPACK #-} !Mask
!(IntMap a)
!(IntMap a)
| Tip {-# UNPACK #-} !Key a
| Nil
type Prefix = Int
type Mask = Int
-- Some stuff from "Data.IntSet.Internal", for 'restrictKeys' and
-- 'withoutKeys' to use.
type IntSetPrefix = Int
type IntSetBitMap = Word
bitmapOf :: Int -> IntSetBitMap
bitmapOf x = shiftLL 1 (x .&. IntSet.suffixBitMask)
{-# INLINE bitmapOf #-}
{--------------------------------------------------------------------
Operators
--------------------------------------------------------------------}
-- | /O(min(n,W))/. Find the value at a key.
-- Calls 'error' when the element can not be found.
--
-- > fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map
-- > fromList [(5,'a'), (3,'b')] ! 5 == 'a'
(!) :: IntMap a -> Key -> a
(!) m k = find k m
-- | Same as 'difference'.
(\\) :: IntMap a -> IntMap b -> IntMap a
m1 \\ m2 = difference m1 m2
infixl 9 \\{-This comment teaches CPP correct behaviour -}
{--------------------------------------------------------------------
Types
--------------------------------------------------------------------}
instance Monoid (IntMap a) where
mempty = empty
mconcat = unions
mappend = (<>)
instance Semigroup (IntMap a) where
(<>) = union
stimes = stimesIdempotentMonoid
instance Foldable.Foldable IntMap where
fold = go
where go Nil = mempty
go (Tip _ v) = v
go (Bin _ _ l r) = go l `mappend` go r
{-# INLINABLE fold #-}
foldr = foldr
{-# INLINE foldr #-}
foldl = foldl
{-# INLINE foldl #-}
foldMap f t = go t
where go Nil = mempty
go (Tip _ v) = f v
go (Bin _ _ l r) = go l `mappend` go r
{-# INLINE foldMap #-}
foldl' = foldl'
{-# INLINE foldl' #-}
foldr' = foldr'
{-# INLINE foldr' #-}
length = size
{-# INLINE length #-}
null = null
{-# INLINE null #-}
toList = elems -- NB: Foldable.toList /= IntMap.toList
{-# INLINE toList #-}
elem = go
where go !_ Nil = False
go x (Tip _ y) = x == y
go x (Bin _ _ l r) = go x l || go x r
{-# INLINABLE elem #-}
maximum = start
where start Nil = error "Data.Foldable.maximum (for Data.IntMap): empty map"
start (Tip _ y) = y
start (Bin _ _ l r) = go (start l) r
go !m Nil = m
go m (Tip _ y) = max m y
go m (Bin _ _ l r) = go (go m l) r
{-# INLINABLE maximum #-}
minimum = start
where start Nil = error "Data.Foldable.minimum (for Data.IntMap): empty map"
start (Tip _ y) = y
start (Bin _ _ l r) = go (start l) r
go !m Nil = m
go m (Tip _ y) = min m y
go m (Bin _ _ l r) = go (go m l) r
{-# INLINABLE minimum #-}
sum = foldl' (+) 0
{-# INLINABLE sum #-}
product = foldl' (*) 1
{-# INLINABLE product #-}
instance Traversable IntMap where
traverse f = traverseWithKey (\_ -> f)
{-# INLINE traverse #-}
instance NFData a => NFData (IntMap a) where
rnf Nil = ()
rnf (Tip _ v) = rnf v
rnf (Bin _ _ l r) = rnf l `seq` rnf r
{--------------------------------------------------------------------
A Data instance
--------------------------------------------------------------------}
-- This instance preserves data abstraction at the cost of inefficiency.
-- We provide limited reflection services for the sake of data abstraction.
instance Data a => Data (IntMap a) where
gfoldl f z im = z fromList `f` (toList im)
toConstr _ = fromListConstr
gunfold k z c = case constrIndex c of
1 -> k (z fromList)
_ -> error "gunfold"
dataTypeOf _ = intMapDataType
dataCast1 f = gcast1 f
fromListConstr :: Constr
fromListConstr = mkConstr intMapDataType "fromList" [] Prefix
intMapDataType :: DataType
intMapDataType = mkDataType "Data.IntMap.Internal.IntMap" [fromListConstr]
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(1)/. Is the map empty?
--
-- > Data.IntMap.null (empty) == True
-- > Data.IntMap.null (singleton 1 'a') == False
null :: IntMap a -> Bool
null Nil = True
null _ = False
{-# INLINE null #-}
-- | /O(n)/. Number of elements in the map.
--
-- > size empty == 0
-- > size (singleton 1 'a') == 1
-- > size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3
size :: IntMap a -> Int
size = go 0
where
go !acc (Bin _ _ l r) = go (go acc l) r
go acc (Tip _ _) = 1 + acc
go acc Nil = acc
-- | /O(min(n,W))/. Is the key a member of the map?
--
-- > member 5 (fromList [(5,'a'), (3,'b')]) == True
-- > member 1 (fromList [(5,'a'), (3,'b')]) == False
-- See Note: Local 'go' functions and capturing]
member :: Key -> IntMap a -> Bool
member !k = go
where
go (Bin p m l r) | nomatch k p m = False
| zero k m = go l
| otherwise = go r
go (Tip kx _) = k == kx
go Nil = False
-- | /O(min(n,W))/. Is the key not a member of the map?
--
-- > notMember 5 (fromList [(5,'a'), (3,'b')]) == False
-- > notMember 1 (fromList [(5,'a'), (3,'b')]) == True
notMember :: Key -> IntMap a -> Bool
notMember k m = not $ member k m
-- | /O(min(n,W))/. Lookup the value at a key in the map. See also 'Data.Map.lookup'.
-- See Note: Local 'go' functions and capturing]
lookup :: Key -> IntMap a -> Maybe a
lookup !k = go
where
go (Bin p m l r) | nomatch k p m = Nothing
| zero k m = go l
| otherwise = go r
go (Tip kx x) | k == kx = Just x
| otherwise = Nothing
go Nil = Nothing
-- See Note: Local 'go' functions and capturing]
find :: Key -> IntMap a -> a
find !k = go
where
go (Bin p m l r) | nomatch k p m = not_found
| zero k m = go l
| otherwise = go r
go (Tip kx x) | k == kx = x
| otherwise = not_found
go Nil = not_found
not_found = error ("IntMap.!: key " ++ show k ++ " is not an element of the map")
-- | /O(min(n,W))/. The expression @('findWithDefault' def k map)@
-- returns the value at key @k@ or returns @def@ when the key is not an
-- element of the map.
--
-- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
-- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
-- See Note: Local 'go' functions and capturing]
findWithDefault :: a -> Key -> IntMap a -> a
findWithDefault def !k = go
where
go (Bin p m l r) | nomatch k p m = def
| zero k m = go l
| otherwise = go r
go (Tip kx x) | k == kx = x
| otherwise = def
go Nil = def
-- | /O(log n)/. Find largest key smaller than the given one and return the
-- corresponding (key, value) pair.
--
-- > lookupLT 3 (fromList [(3,'a'), (5,'b')]) == Nothing
-- > lookupLT 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
-- See Note: Local 'go' functions and capturing.
lookupLT :: Key -> IntMap a -> Maybe (Key, a)
lookupLT !k t = case t of
Bin _ m l r | m < 0 -> if k >= 0 then go r l else go Nil r
_ -> go Nil t
where
go def (Bin p m l r)
| nomatch k p m = if k < p then unsafeFindMax def else unsafeFindMax r
| zero k m = go def l
| otherwise = go l r
go def (Tip ky y)
| k <= ky = unsafeFindMax def
| otherwise = Just (ky, y)
go def Nil = unsafeFindMax def
-- | /O(log n)/. Find smallest key greater than the given one and return the
-- corresponding (key, value) pair.
--
-- > lookupGT 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
-- > lookupGT 5 (fromList [(3,'a'), (5,'b')]) == Nothing
-- See Note: Local 'go' functions and capturing.
lookupGT :: Key -> IntMap a -> Maybe (Key, a)
lookupGT !k t = case t of
Bin _ m l r | m < 0 -> if k >= 0 then go Nil l else go l r
_ -> go Nil t
where
go def (Bin p m l r)
| nomatch k p m = if k < p then unsafeFindMin l else unsafeFindMin def
| zero k m = go r l
| otherwise = go def r
go def (Tip ky y)
| k >= ky = unsafeFindMin def
| otherwise = Just (ky, y)
go def Nil = unsafeFindMin def
-- | /O(log n)/. Find largest key smaller or equal to the given one and return
-- the corresponding (key, value) pair.
--
-- > lookupLE 2 (fromList [(3,'a'), (5,'b')]) == Nothing
-- > lookupLE 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
-- > lookupLE 5 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
-- See Note: Local 'go' functions and capturing.
lookupLE :: Key -> IntMap a -> Maybe (Key, a)
lookupLE !k t = case t of
Bin _ m l r | m < 0 -> if k >= 0 then go r l else go Nil r
_ -> go Nil t
where
go def (Bin p m l r)
| nomatch k p m = if k < p then unsafeFindMax def else unsafeFindMax r
| zero k m = go def l
| otherwise = go l r
go def (Tip ky y)
| k < ky = unsafeFindMax def
| otherwise = Just (ky, y)
go def Nil = unsafeFindMax def
-- | /O(log n)/. Find smallest key greater or equal to the given one and return
-- the corresponding (key, value) pair.
--
-- > lookupGE 3 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
-- > lookupGE 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
-- > lookupGE 6 (fromList [(3,'a'), (5,'b')]) == Nothing
-- See Note: Local 'go' functions and capturing.
lookupGE :: Key -> IntMap a -> Maybe (Key, a)
lookupGE !k t = case t of
Bin _ m l r | m < 0 -> if k >= 0 then go Nil l else go l r
_ -> go Nil t
where
go def (Bin p m l r)
| nomatch k p m = if k < p then unsafeFindMin l else unsafeFindMin def
| zero k m = go r l
| otherwise = go def r
go def (Tip ky y)
| k > ky = unsafeFindMin def
| otherwise = Just (ky, y)
go def Nil = unsafeFindMin def
-- Helper function for lookupGE and lookupGT. It assumes that if a Bin node is
-- given, it has m > 0.
unsafeFindMin :: IntMap a -> Maybe (Key, a)
unsafeFindMin Nil = Nothing
unsafeFindMin (Tip ky y) = Just (ky, y)
unsafeFindMin (Bin _ _ l _) = unsafeFindMin l
-- Helper function for lookupLE and lookupLT. It assumes that if a Bin node is
-- given, it has m > 0.
unsafeFindMax :: IntMap a -> Maybe (Key, a)
unsafeFindMax Nil = Nothing
unsafeFindMax (Tip ky y) = Just (ky, y)
unsafeFindMax (Bin _ _ _ r) = unsafeFindMax r
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. The empty map.
--
-- > empty == fromList []
-- > size empty == 0
empty :: IntMap a
empty
= Nil
{-# INLINE empty #-}
-- | /O(1)/. A map of one element.
--
-- > singleton 1 'a' == fromList [(1, 'a')]
-- > size (singleton 1 'a') == 1
singleton :: Key -> a -> IntMap a
singleton k x
= Tip k x
{-# INLINE singleton #-}
{--------------------------------------------------------------------
Insert
--------------------------------------------------------------------}
-- | /O(min(n,W))/. Insert a new key\/value pair in the map.
-- If the key is already present in the map, the associated value is
-- replaced with the supplied value, i.e. 'insert' is equivalent to
-- @'insertWith' 'const'@.
--
-- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
-- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
-- > insert 5 'x' empty == singleton 5 'x'
insert :: Key -> a -> IntMap a -> IntMap a
insert !k x t@(Bin p m l r)
| nomatch k p m = link k (Tip k x) p t
| zero k m = Bin p m (insert k x l) r
| otherwise = Bin p m l (insert k x r)
insert k x t@(Tip ky _)
| k==ky = Tip k x
| otherwise = link k (Tip k x) ky t
insert k x Nil = Tip k x
-- right-biased insertion, used by 'union'
-- | /O(min(n,W))/. Insert with a combining function.
-- @'insertWith' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert @f new_value old_value@.
--
-- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
-- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
insertWith :: (a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
insertWith f k x t
= insertWithKey (\_ x' y' -> f x' y') k x t
-- | /O(min(n,W))/. Insert with a combining function.
-- @'insertWithKey' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert @f key new_value old_value@.
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
-- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
insertWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
insertWithKey f !k x t@(Bin p m l r)
| nomatch k p m = link k (Tip k x) p t
| zero k m = Bin p m (insertWithKey f k x l) r
| otherwise = Bin p m l (insertWithKey f k x r)
insertWithKey f k x t@(Tip ky y)
| k == ky = Tip k (f k x y)
| otherwise = link k (Tip k x) ky t
insertWithKey _ k x Nil = Tip k x
-- | /O(min(n,W))/. The expression (@'insertLookupWithKey' f k x map@)
-- is a pair where the first element is equal to (@'lookup' k map@)
-- and the second element equal to (@'insertWithKey' f k x map@).
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
-- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
-- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
--
-- This is how to define @insertLookup@ using @insertLookupWithKey@:
--
-- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
-- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
-- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
insertLookupWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> (Maybe a, IntMap a)
insertLookupWithKey f !k x t@(Bin p m l r)
| nomatch k p m = (Nothing,link k (Tip k x) p t)
| zero k m = let (found,l') = insertLookupWithKey f k x l
in (found,Bin p m l' r)
| otherwise = let (found,r') = insertLookupWithKey f k x r
in (found,Bin p m l r')
insertLookupWithKey f k x t@(Tip ky y)
| k == ky = (Just y,Tip k (f k x y))
| otherwise = (Nothing,link k (Tip k x) ky t)
insertLookupWithKey _ k x Nil = (Nothing,Tip k x)
{--------------------------------------------------------------------
Deletion
--------------------------------------------------------------------}
-- | /O(min(n,W))/. Delete a key and its value from the map. When the key is not
-- a member of the map, the original map is returned.
--
-- > delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > delete 5 empty == empty
delete :: Key -> IntMap a -> IntMap a
delete !k t@(Bin p m l r)
| nomatch k p m = t
| zero k m = binCheckLeft p m (delete k l) r
| otherwise = binCheckRight p m l (delete k r)
delete k t@(Tip ky _)
| k == ky = Nil
| otherwise = t
delete _k Nil = Nil
-- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
--
-- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjust ("new " ++) 7 empty == empty
adjust :: (a -> a) -> Key -> IntMap a -> IntMap a
adjust f k m
= adjustWithKey (\_ x -> f x) k m
-- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
--
-- > let f key x = (show key) ++ ":new " ++ x
-- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjustWithKey f 7 empty == empty
adjustWithKey :: (Key -> a -> a) -> Key -> IntMap a -> IntMap a
adjustWithKey f !k t@(Bin p m l r)
| nomatch k p m = t
| zero k m = Bin p m (adjustWithKey f k l) r
| otherwise = Bin p m l (adjustWithKey f k r)
adjustWithKey f k t@(Tip ky y)
| k == ky = Tip ky (f k y)
| otherwise = t
adjustWithKey _ _ Nil = Nil
-- | /O(min(n,W))/. The expression (@'update' f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
-- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
update :: (a -> Maybe a) -> Key -> IntMap a -> IntMap a
update f
= updateWithKey (\_ x -> f x)
-- | /O(min(n,W))/. The expression (@'update' f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f k x@) is 'Nothing', the element is
-- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> IntMap a
updateWithKey f !k t@(Bin p m l r)
| nomatch k p m = t
| zero k m = binCheckLeft p m (updateWithKey f k l) r
| otherwise = binCheckRight p m l (updateWithKey f k r)
updateWithKey f k t@(Tip ky y)
| k == ky = case (f k y) of
Just y' -> Tip ky y'
Nothing -> Nil
| otherwise = t
updateWithKey _ _ Nil = Nil
-- | /O(min(n,W))/. Lookup and update.
-- The function returns original value, if it is updated.
-- This is different behavior than 'Data.Map.updateLookupWithKey'.
-- Returns the original key value if the map entry is deleted.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:new a")])
-- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
-- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
updateLookupWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> (Maybe a,IntMap a)
updateLookupWithKey f !k t@(Bin p m l r)
| nomatch k p m = (Nothing,t)
| zero k m = let !(found,l') = updateLookupWithKey f k l
in (found,binCheckLeft p m l' r)
| otherwise = let !(found,r') = updateLookupWithKey f k r
in (found,binCheckRight p m l r')
updateLookupWithKey f k t@(Tip ky y)
| k==ky = case (f k y) of
Just y' -> (Just y,Tip ky y')
Nothing -> (Just y,Nil)
| otherwise = (Nothing,t)
updateLookupWithKey _ _ Nil = (Nothing,Nil)
-- | /O(min(n,W))/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
-- 'alter' can be used to insert, delete, or update a value in an 'IntMap'.
-- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
alter :: (Maybe a -> Maybe a) -> Key -> IntMap a -> IntMap a
alter f !k t@(Bin p m l r)
| nomatch k p m = case f Nothing of
Nothing -> t
Just x -> link k (Tip k x) p t
| zero k m = binCheckLeft p m (alter f k l) r
| otherwise = binCheckRight p m l (alter f k r)
alter f k t@(Tip ky y)
| k==ky = case f (Just y) of
Just x -> Tip ky x
Nothing -> Nil
| otherwise = case f Nothing of
Just x -> link k (Tip k x) ky t
Nothing -> Tip ky y
alter f k Nil = case f Nothing of
Just x -> Tip k x
Nothing -> Nil
-- | /O(log n)/. The expression (@'alterF' f k map@) alters the value @x@ at
-- @k@, or absence thereof. 'alterF' can be used to inspect, insert, delete,
-- or update a value in an 'IntMap'. In short : @'lookup' k <$> 'alterF' f k m = f
-- ('lookup' k m)@.
--
-- Example:
--
-- @
-- interactiveAlter :: Int -> IntMap String -> IO (IntMap String)
-- interactiveAlter k m = alterF f k m where
-- f Nothing -> do
-- putStrLn $ show k ++
-- " was not found in the map. Would you like to add it?"
-- getUserResponse1 :: IO (Maybe String)
-- f (Just old) -> do
-- putStrLn "The key is currently bound to " ++ show old ++
-- ". Would you like to change or delete it?"
-- getUserresponse2 :: IO (Maybe String)
-- @
--
-- 'alterF' is the most general operation for working with an individual
-- key that may or may not be in a given map.
--
-- Note: 'alterF' is a flipped version of the 'at' combinator from
-- 'Control.Lens.At'.
--
-- @since 0.5.8
alterF :: Functor f
=> (Maybe a -> f (Maybe a)) -> Key -> IntMap a -> f (IntMap a)
-- This implementation was stolen from 'Control.Lens.At'.
alterF f k m = (<$> f mv) $ \fres ->
case fres of
Nothing -> maybe m (const (delete k m)) mv
Just v' -> insert k v' m
where mv = lookup k m
{--------------------------------------------------------------------
Union
--------------------------------------------------------------------}
-- | The union of a list of maps.
--
-- > unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "b"), (5, "a"), (7, "C")]
-- > unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])]
-- > == fromList [(3, "B3"), (5, "A3"), (7, "C")]
unions :: [IntMap a] -> IntMap a
unions xs
= foldlStrict union empty xs
-- | The union of a list of maps, with a combining operation.
--
-- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
unionsWith :: (a->a->a) -> [IntMap a] -> IntMap a
unionsWith f ts
= foldlStrict (unionWith f) empty ts
-- | /O(n+m)/. The (left-biased) union of two maps.
-- It prefers the first map when duplicate keys are encountered,
-- i.e. (@'union' == 'unionWith' 'const'@).
--
-- > union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]
union :: IntMap a -> IntMap a -> IntMap a
union m1 m2
= mergeWithKey' Bin const id id m1 m2
-- | /O(n+m)/. The union with a combining function.
--
-- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
unionWith :: (a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
unionWith f m1 m2
= unionWithKey (\_ x y -> f x y) m1 m2
-- | /O(n+m)/. The union with a combining function.
--
-- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
-- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
unionWithKey :: (Key -> a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
unionWithKey f m1 m2
= mergeWithKey' Bin (\(Tip k1 x1) (Tip _k2 x2) -> Tip k1 (f k1 x1 x2)) id id m1 m2
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
-- | /O(n+m)/. Difference between two maps (based on keys).
--
-- > difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"
difference :: IntMap a -> IntMap b -> IntMap a
difference m1 m2
= mergeWithKey (\_ _ _ -> Nothing) id (const Nil) m1 m2
-- | /O(n+m)/. Difference with a combining function.
--
-- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
-- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
-- > == singleton 3 "b:B"
differenceWith :: (a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
differenceWith f m1 m2
= differenceWithKey (\_ x y -> f x y) m1 m2
-- | /O(n+m)/. Difference with a combining function. When two equal keys are
-- encountered, the combining function is applied to the key and both values.
-- If it returns 'Nothing', the element is discarded (proper set difference).
-- If it returns (@'Just' y@), the element is updated with a new value @y@.
--
-- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
-- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
-- > == singleton 3 "3:b|B"
differenceWithKey :: (Key -> a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
differenceWithKey f m1 m2
= mergeWithKey f id (const Nil) m1 m2
-- TODO(wrengr): re-verify that asymptotic bound
-- | /O(n+m)/. Remove all the keys in a given set from a map.
--
-- @
-- m `withoutKeys` s = 'filterWithKey' (\k _ -> k `'IntSet.notMember'` s) m
-- @
--
-- @since 0.5.8
withoutKeys :: IntMap a -> IntSet.IntSet -> IntMap a
withoutKeys t1@(Bin p1 m1 l1 r1) t2@(IntSet.Bin p2 m2 l2 r2)
| shorter m1 m2 = difference1
| shorter m2 m1 = difference2
| p1 == p2 = bin p1 m1 (withoutKeys l1 l2) (withoutKeys r1 r2)
| otherwise = t1
where
difference1
| nomatch p2 p1 m1 = t1
| zero p2 m1 = binCheckLeft p1 m1 (withoutKeys l1 t2) r1
| otherwise = binCheckRight p1 m1 l1 (withoutKeys r1 t2)
difference2
| nomatch p1 p2 m2 = t1
| zero p1 m2 = withoutKeys t1 l2
| otherwise = withoutKeys t1 r2
withoutKeys t1@(Bin p1 m1 _ _) (IntSet.Tip p2 bm2) =
let minbit = bitmapOf p1
lt_minbit = minbit - 1
maxbit = bitmapOf (p1 .|. (m1 .|. (m1 - 1)))
gt_maxbit = maxbit `xor` complement (maxbit - 1)
-- TODO(wrengr): should we manually inline/unroll 'updatePrefix'
-- and 'withoutBM' here, in order to avoid redundant case analyses?
in updatePrefix p2 t1 $ withoutBM (bm2 .|. lt_minbit .|. gt_maxbit)
withoutKeys t1@(Bin _ _ _ _) IntSet.Nil = t1
withoutKeys t1@(Tip k1 _) t2
| k1 `IntSet.member` t2 = Nil
| otherwise = t1
withoutKeys Nil _ = Nil
updatePrefix
:: IntSetPrefix -> IntMap a -> (IntMap a -> IntMap a) -> IntMap a
updatePrefix !kp t@(Bin p m l r) f
| m .&. IntSet.suffixBitMask /= 0 =
if p .&. IntSet.prefixBitMask == kp then f t else t
| nomatch kp p m = t
| zero kp m = binCheckLeft p m (updatePrefix kp l f) r
| otherwise = binCheckRight p m l (updatePrefix kp r f)
updatePrefix kp t@(Tip kx _) f
| kx .&. IntSet.prefixBitMask == kp = f t
| otherwise = t
updatePrefix _ Nil _ = Nil
withoutBM :: IntSetBitMap -> IntMap a -> IntMap a
withoutBM 0 t = t
withoutBM bm (Bin p m l r) =
let leftBits = bitmapOf (p .|. m) - 1
bmL = bm .&. leftBits
bmR = bm `xor` bmL -- = (bm .&. complement leftBits)
in bin p m (withoutBM bmL l) (withoutBM bmR r)
withoutBM bm t@(Tip k _)
-- TODO(wrengr): need we manually inline 'IntSet.Member' here?
| k `IntSet.member` IntSet.Tip (k .&. IntSet.prefixBitMask) bm = Nil
| otherwise = t
withoutBM _ Nil = Nil
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
-- | /O(n+m)/. The (left-biased) intersection of two maps (based on keys).
--
-- > intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a"
intersection :: IntMap a -> IntMap b -> IntMap a
intersection m1 m2
= mergeWithKey' bin const (const Nil) (const Nil) m1 m2
-- TODO(wrengr): re-verify that asymptotic bound
-- | /O(n+m)/. The restriction of a map to the keys in a set.
--
-- @
-- m `restrictKeys` s = 'filterWithKey' (\k _ -> k `'IntSet.member'` s) m
-- @
--
-- @since 0.5.8
restrictKeys :: IntMap a -> IntSet.IntSet -> IntMap a
restrictKeys t1@(Bin p1 m1 l1 r1) t2@(IntSet.Bin p2 m2 l2 r2)
| shorter m1 m2 = intersection1
| shorter m2 m1 = intersection2
| p1 == p2 = bin p1 m1 (restrictKeys l1 l2) (restrictKeys r1 r2)
| otherwise = Nil
where
intersection1
| nomatch p2 p1 m1 = Nil
| zero p2 m1 = restrictKeys l1 t2
| otherwise = restrictKeys r1 t2
intersection2
| nomatch p1 p2 m2 = Nil
| zero p1 m2 = restrictKeys t1 l2
| otherwise = restrictKeys t1 r2
restrictKeys t1@(Bin p1 m1 _ _) (IntSet.Tip p2 bm2) =
let minbit = bitmapOf p1
ge_minbit = complement (minbit - 1)
maxbit = bitmapOf (p1 .|. (m1 .|. (m1 - 1)))
le_maxbit = maxbit .|. (maxbit - 1)
-- TODO(wrengr): should we manually inline/unroll 'lookupPrefix'
-- and 'restrictBM' here, in order to avoid redundant case analyses?
in restrictBM (bm2 .&. ge_minbit .&. le_maxbit) (lookupPrefix p2 t1)
restrictKeys (Bin _ _ _ _) IntSet.Nil = Nil
restrictKeys t1@(Tip k1 _) t2
| k1 `IntSet.member` t2 = t1
| otherwise = Nil
restrictKeys Nil _ = Nil
-- | /O(min(n,W))/. Restrict to the sub-map with all keys matching
-- a key prefix.
lookupPrefix :: IntSetPrefix -> IntMap a -> IntMap a
lookupPrefix !kp t@(Bin p m l r)
| m .&. IntSet.suffixBitMask /= 0 =
if p .&. IntSet.prefixBitMask == kp then t else Nil
| nomatch kp p m = Nil
| zero kp m = lookupPrefix kp l
| otherwise = lookupPrefix kp r
lookupPrefix kp t@(Tip kx _)
| (kx .&. IntSet.prefixBitMask) == kp = t
| otherwise = Nil
lookupPrefix _ Nil = Nil
restrictBM :: IntSetBitMap -> IntMap a -> IntMap a
restrictBM 0 _ = Nil
restrictBM bm (Bin p m l r) =
let leftBits = bitmapOf (p .|. m) - 1
bmL = bm .&. leftBits
bmR = bm `xor` bmL -- = (bm .&. complement leftBits)
in bin p m (restrictBM bmL l) (restrictBM bmR r)
restrictBM bm t@(Tip k _)
-- TODO(wrengr): need we manually inline 'IntSet.Member' here?
| k `IntSet.member` IntSet.Tip (k .&. IntSet.prefixBitMask) bm = t
| otherwise = Nil
restrictBM _ Nil = Nil
-- | /O(n+m)/. The intersection with a combining function.
--
-- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
intersectionWith :: (a -> b -> c) -> IntMap a -> IntMap b -> IntMap c
intersectionWith f m1 m2
= intersectionWithKey (\_ x y -> f x y) m1 m2
-- | /O(n+m)/. The intersection with a combining function.
--
-- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
-- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
intersectionWithKey :: (Key -> a -> b -> c) -> IntMap a -> IntMap b -> IntMap c
intersectionWithKey f m1 m2
= mergeWithKey' bin (\(Tip k1 x1) (Tip _k2 x2) -> Tip k1 (f k1 x1 x2)) (const Nil) (const Nil) m1 m2
{--------------------------------------------------------------------
MergeWithKey
--------------------------------------------------------------------}
-- | /O(n+m)/. A high-performance universal combining function. Using
-- 'mergeWithKey', all combining functions can be defined without any loss of
-- efficiency (with exception of 'union', 'difference' and 'intersection',
-- where sharing of some nodes is lost with 'mergeWithKey').
--
-- Please make sure you know what is going on when using 'mergeWithKey',
-- otherwise you can be surprised by unexpected code growth or even
-- corruption of the data structure.
--
-- When 'mergeWithKey' is given three arguments, it is inlined to the call
-- site. You should therefore use 'mergeWithKey' only to define your custom
-- combining functions. For example, you could define 'unionWithKey',
-- 'differenceWithKey' and 'intersectionWithKey' as
--
-- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
-- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
-- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
--
-- When calling @'mergeWithKey' combine only1 only2@, a function combining two
-- 'IntMap's is created, such that
--
-- * if a key is present in both maps, it is passed with both corresponding
-- values to the @combine@ function. Depending on the result, the key is either
-- present in the result with specified value, or is left out;
--
-- * a nonempty subtree present only in the first map is passed to @only1@ and
-- the output is added to the result;
--
-- * a nonempty subtree present only in the second map is passed to @only2@ and
-- the output is added to the result.
--
-- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
-- The values can be modified arbitrarily. Most common variants of @only1@ and
-- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
-- @'filterWithKey' f@ could be used for any @f@.
mergeWithKey :: (Key -> a -> b -> Maybe c) -> (IntMap a -> IntMap c) -> (IntMap b -> IntMap c)
-> IntMap a -> IntMap b -> IntMap c
mergeWithKey f g1 g2 = mergeWithKey' bin combine g1 g2
where -- We use the lambda form to avoid non-exhaustive pattern matches warning.
combine = \(Tip k1 x1) (Tip _k2 x2) ->
case f k1 x1 x2 of
Nothing -> Nil
Just x -> Tip k1 x
{-# INLINE combine #-}
{-# INLINE mergeWithKey #-}
-- Slightly more general version of mergeWithKey. It differs in the following:
--
-- * the combining function operates on maps instead of keys and values. The
-- reason is to enable sharing in union, difference and intersection.
--
-- * mergeWithKey' is given an equivalent of bin. The reason is that in union*,
-- Bin constructor can be used, because we know both subtrees are nonempty.
mergeWithKey' :: (Prefix -> Mask -> IntMap c -> IntMap c -> IntMap c)
-> (IntMap a -> IntMap b -> IntMap c) -> (IntMap a -> IntMap c) -> (IntMap b -> IntMap c)
-> IntMap a -> IntMap b -> IntMap c
mergeWithKey' bin' f g1 g2 = go
where
go t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
| shorter m1 m2 = merge1
| shorter m2 m1 = merge2
| p1 == p2 = bin' p1 m1 (go l1 l2) (go r1 r2)
| otherwise = maybe_link p1 (g1 t1) p2 (g2 t2)
where
merge1 | nomatch p2 p1 m1 = maybe_link p1 (g1 t1) p2 (g2 t2)
| zero p2 m1 = bin' p1 m1 (go l1 t2) (g1 r1)
| otherwise = bin' p1 m1 (g1 l1) (go r1 t2)
merge2 | nomatch p1 p2 m2 = maybe_link p1 (g1 t1) p2 (g2 t2)
| zero p1 m2 = bin' p2 m2 (go t1 l2) (g2 r2)
| otherwise = bin' p2 m2 (g2 l2) (go t1 r2)
go t1'@(Bin _ _ _ _) t2'@(Tip k2' _) = merge0 t2' k2' t1'
where
merge0 t2 k2 t1@(Bin p1 m1 l1 r1)
| nomatch k2 p1 m1 = maybe_link p1 (g1 t1) k2 (g2 t2)
| zero k2 m1 = bin' p1 m1 (merge0 t2 k2 l1) (g1 r1)
| otherwise = bin' p1 m1 (g1 l1) (merge0 t2 k2 r1)
merge0 t2 k2 t1@(Tip k1 _)
| k1 == k2 = f t1 t2
| otherwise = maybe_link k1 (g1 t1) k2 (g2 t2)
merge0 t2 _ Nil = g2 t2
go t1@(Bin _ _ _ _) Nil = g1 t1
go t1'@(Tip k1' _) t2' = merge0 t1' k1' t2'
where
merge0 t1 k1 t2@(Bin p2 m2 l2 r2)
| nomatch k1 p2 m2 = maybe_link k1 (g1 t1) p2 (g2 t2)
| zero k1 m2 = bin' p2 m2 (merge0 t1 k1 l2) (g2 r2)
| otherwise = bin' p2 m2 (g2 l2) (merge0 t1 k1 r2)
merge0 t1 k1 t2@(Tip k2 _)
| k1 == k2 = f t1 t2
| otherwise = maybe_link k1 (g1 t1) k2 (g2 t2)
merge0 t1 _ Nil = g1 t1
go Nil t2 = g2 t2
maybe_link _ Nil _ t2 = t2
maybe_link _ t1 _ Nil = t1
maybe_link p1 t1 p2 t2 = link p1 t1 p2 t2
{-# INLINE maybe_link #-}
{-# INLINE mergeWithKey' #-}
{--------------------------------------------------------------------
mergeA
--------------------------------------------------------------------}
-- | A tactic for dealing with keys present in one map but not the
-- other in 'merge' or 'mergeA'.
--
-- A tactic of type @WhenMissing f k x z@ is an abstract representation
-- of a function of type @Key -> x -> f (Maybe z)@.
data WhenMissing f x y = WhenMissing
{ missingSubtree :: IntMap x -> f (IntMap y)
, missingKey :: Key -> x -> f (Maybe y)}
instance (Applicative f, Monad f) => Functor (WhenMissing f x) where
fmap = mapWhenMissing
{-# INLINE fmap #-}
instance (Applicative f, Monad f) => Category.Category (WhenMissing f)
where
id = preserveMissing
f . g =
traverseMaybeMissing $ \ k x -> do
y <- missingKey g k x
case y of
Nothing -> pure Nothing
Just q -> missingKey f k q
{-# INLINE id #-}
{-# INLINE (.) #-}
-- | Equivalent to @ReaderT k (ReaderT x (MaybeT f))@.
instance (Applicative f, Monad f) => Applicative (WhenMissing f x) where
pure x = mapMissing (\ _ _ -> x)
f <*> g =
traverseMaybeMissing $ \k x -> do
res1 <- missingKey f k x
case res1 of
Nothing -> pure Nothing
Just r -> (pure $!) . fmap r =<< missingKey g k x
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
-- | Equivalent to @ReaderT k (ReaderT x (MaybeT f))@.
instance (Applicative f, Monad f) => Monad (WhenMissing f x) where
m >>= f =
traverseMaybeMissing $ \k x -> do
res1 <- missingKey m k x
case res1 of
Nothing -> pure Nothing
Just r -> missingKey (f r) k x
{-# INLINE (>>=) #-}
-- | Map covariantly over a @'WhenMissing' f x@.
mapWhenMissing
:: (Applicative f, Monad f)
=> (a -> b)
-> WhenMissing f x a
-> WhenMissing f x b
mapWhenMissing f t = WhenMissing
{ missingSubtree = \m -> missingSubtree t m >>= \m' -> pure $! fmap f m'
, missingKey = \k x -> missingKey t k x >>= \q -> (pure $! fmap f q) }
{-# INLINE mapWhenMissing #-}
-- | Map covariantly over a @'WhenMissing' f x@, using only a
-- 'Functor f' constraint.
mapGentlyWhenMissing
:: Functor f
=> (a -> b)
-> WhenMissing f x a
-> WhenMissing f x b
mapGentlyWhenMissing f t = WhenMissing
{ missingSubtree = \m -> fmap f <$> missingSubtree t m
, missingKey = \k x -> fmap f <$> missingKey t k x }
{-# INLINE mapGentlyWhenMissing #-}
-- | Map covariantly over a @'WhenMatched' f k x@, using only a
-- 'Functor f' constraint.
mapGentlyWhenMatched
:: Functor f
=> (a -> b)
-> WhenMatched f x y a
-> WhenMatched f x y b
mapGentlyWhenMatched f t =
zipWithMaybeAMatched $ \k x y -> fmap f <$> runWhenMatched t k x y
{-# INLINE mapGentlyWhenMatched #-}
-- | Map contravariantly over a @'WhenMissing' f _ x@.
lmapWhenMissing :: (b -> a) -> WhenMissing f a x -> WhenMissing f b x
lmapWhenMissing f t = WhenMissing
{ missingSubtree = \m -> missingSubtree t (fmap f m)
, missingKey = \k x -> missingKey t k (f x) }
{-# INLINE lmapWhenMissing #-}
-- | Map contravariantly over a @'WhenMatched' f _ y z@.
contramapFirstWhenMatched
:: (b -> a)
-> WhenMatched f a y z
-> WhenMatched f b y z
contramapFirstWhenMatched f t =
WhenMatched $ \k x y -> runWhenMatched t k (f x) y
{-# INLINE contramapFirstWhenMatched #-}
-- | Map contravariantly over a @'WhenMatched' f x _ z@.
contramapSecondWhenMatched
:: (b -> a)
-> WhenMatched f x a z
-> WhenMatched f x b z
contramapSecondWhenMatched f t =
WhenMatched $ \k x y -> runWhenMatched t k x (f y)
{-# INLINE contramapSecondWhenMatched #-}
-- | A tactic for dealing with keys present in one map but not the
-- other in 'merge'.
--
-- A tactic of type @SimpleWhenMissing x z@ is an abstract
-- representation of a function of type @Key -> x -> Maybe z@.
type SimpleWhenMissing = WhenMissing Identity
-- | A tactic for dealing with keys present in both maps in 'merge'
-- or 'mergeA'.
--
-- A tactic of type @WhenMatched f x y z@ is an abstract representation
-- of a function of type @Key -> x -> y -> f (Maybe z)@.
newtype WhenMatched f x y z = WhenMatched
{ matchedKey :: Key -> x -> y -> f (Maybe z) }
-- | Along with zipWithMaybeAMatched, witnesses the isomorphism
-- between @WhenMatched f x y z@ and @Key -> x -> y -> f (Maybe z)@.
runWhenMatched :: WhenMatched f x y z -> Key -> x -> y -> f (Maybe z)
runWhenMatched = matchedKey
{-# INLINE runWhenMatched #-}
-- | Along with traverseMaybeMissing, witnesses the isomorphism
-- between @WhenMissing f x y@ and @Key -> x -> f (Maybe y)@.
runWhenMissing :: WhenMissing f x y -> Key-> x -> f (Maybe y)
runWhenMissing = missingKey
{-# INLINE runWhenMissing #-}
instance Functor f => Functor (WhenMatched f x y) where
fmap = mapWhenMatched
{-# INLINE fmap #-}
instance (Monad f, Applicative f) => Category.Category (WhenMatched f x)
where
id = zipWithMatched (\_ _ y -> y)
f . g =
zipWithMaybeAMatched $ \k x y -> do
res <- runWhenMatched g k x y
case res of
Nothing -> pure Nothing
Just r -> runWhenMatched f k x r
{-# INLINE id #-}
{-# INLINE (.) #-}
-- | Equivalent to @ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))@
instance (Monad f, Applicative f) => Applicative (WhenMatched f x y) where
pure x = zipWithMatched (\_ _ _ -> x)
fs <*> xs =
zipWithMaybeAMatched $ \k x y -> do
res <- runWhenMatched fs k x y
case res of
Nothing -> pure Nothing
Just r -> (pure $!) . fmap r =<< runWhenMatched xs k x y
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
-- | Equivalent to @ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))@
instance (Monad f, Applicative f) => Monad (WhenMatched f x y) where
m >>= f =
zipWithMaybeAMatched $ \k x y -> do
res <- runWhenMatched m k x y
case res of
Nothing -> pure Nothing
Just r -> runWhenMatched (f r) k x y
{-# INLINE (>>=) #-}
-- | Map covariantly over a @'WhenMatched' f x y@.
mapWhenMatched
:: Functor f
=> (a -> b)
-> WhenMatched f x y a
-> WhenMatched f x y b
mapWhenMatched f (WhenMatched g) =
WhenMatched $ \k x y -> fmap (fmap f) (g k x y)
{-# INLINE mapWhenMatched #-}
-- | A tactic for dealing with keys present in both maps in 'merge'.
--
-- A tactic of type @SimpleWhenMatched x y z@ is an abstract
-- representation of a function of type @Key -> x -> y -> Maybe z@.
type SimpleWhenMatched = WhenMatched Identity
-- | When a key is found in both maps, apply a function to the key
-- and values and use the result in the merged map.
--
-- > zipWithMatched
-- > :: (Key -> x -> y -> z)
-- > -> SimpleWhenMatched x y z
zipWithMatched
:: Applicative f
=> (Key -> x -> y -> z)
-> WhenMatched f x y z
zipWithMatched f = WhenMatched $ \ k x y -> pure . Just $ f k x y
{-# INLINE zipWithMatched #-}
-- | When a key is found in both maps, apply a function to the key
-- and values to produce an action and use its result in the merged
-- map.
zipWithAMatched
:: Applicative f
=> (Key -> x -> y -> f z)
-> WhenMatched f x y z
zipWithAMatched f = WhenMatched $ \ k x y -> Just <$> f k x y
{-# INLINE zipWithAMatched #-}
-- | When a key is found in both maps, apply a function to the key
-- and values and maybe use the result in the merged map.
--
-- > zipWithMaybeMatched
-- > :: (Key -> x -> y -> Maybe z)
-- > -> SimpleWhenMatched x y z
zipWithMaybeMatched
:: Applicative f
=> (Key -> x -> y -> Maybe z)
-> WhenMatched f x y z
zipWithMaybeMatched f = WhenMatched $ \ k x y -> pure $ f k x y
{-# INLINE zipWithMaybeMatched #-}
-- | When a key is found in both maps, apply a function to the key
-- and values, perform the resulting action, and maybe use the
-- result in the merged map.
--
-- This is the fundamental 'WhenMatched' tactic.
zipWithMaybeAMatched
:: (Key -> x -> y -> f (Maybe z))
-> WhenMatched f x y z
zipWithMaybeAMatched f = WhenMatched $ \ k x y -> f k x y
{-# INLINE zipWithMaybeAMatched #-}
-- | Drop all the entries whose keys are missing from the other
-- map.
--
-- > dropMissing :: SimpleWhenMissing x y
--
-- prop> dropMissing = mapMaybeMissing (\_ _ -> Nothing)
--
-- but @dropMissing@ is much faster.
dropMissing :: Applicative f => WhenMissing f x y
dropMissing = WhenMissing
{ missingSubtree = const (pure Nil)
, missingKey = \_ _ -> pure Nothing }
{-# INLINE dropMissing #-}
-- | Preserve, unchanged, the entries whose keys are missing from
-- the other map.
--
-- > preserveMissing :: SimpleWhenMissing x x
--
-- prop> preserveMissing = Merge.Lazy.mapMaybeMissing (\_ x -> Just x)
--
-- but @preserveMissing@ is much faster.
preserveMissing :: Applicative f => WhenMissing f x x
preserveMissing = WhenMissing
{ missingSubtree = pure
, missingKey = \_ v -> pure (Just v) }
{-# INLINE preserveMissing #-}
-- | Map over the entries whose keys are missing from the other map.
--
-- > mapMissing :: (k -> x -> y) -> SimpleWhenMissing x y
--
-- prop> mapMissing f = mapMaybeMissing (\k x -> Just $ f k x)
--
-- but @mapMissing@ is somewhat faster.
mapMissing :: Applicative f => (Key -> x -> y) -> WhenMissing f x y
mapMissing f = WhenMissing
{ missingSubtree = \m -> pure $! mapWithKey f m
, missingKey = \k x -> pure $ Just (f k x) }
{-# INLINE mapMissing #-}
-- | Map over the entries whose keys are missing from the other
-- map, optionally removing some. This is the most powerful
-- 'SimpleWhenMissing' tactic, but others are usually more efficient.
--
-- > mapMaybeMissing :: (Key -> x -> Maybe y) -> SimpleWhenMissing x y
--
-- prop> mapMaybeMissing f = traverseMaybeMissing (\k x -> pure (f k x))
--
-- but @mapMaybeMissing@ uses fewer unnecessary 'Applicative'
-- operations.
mapMaybeMissing
:: Applicative f => (Key -> x -> Maybe y) -> WhenMissing f x y
mapMaybeMissing f = WhenMissing
{ missingSubtree = \m -> pure $! mapMaybeWithKey f m
, missingKey = \k x -> pure $! f k x }
{-# INLINE mapMaybeMissing #-}
-- | Filter the entries whose keys are missing from the other map.
--
-- > filterMissing :: (k -> x -> Bool) -> SimpleWhenMissing x x
--
-- prop> filterMissing f = Merge.Lazy.mapMaybeMissing $ \k x -> guard (f k x) *> Just x
--
-- but this should be a little faster.
filterMissing
:: Applicative f => (Key -> x -> Bool) -> WhenMissing f x x
filterMissing f = WhenMissing
{ missingSubtree = \m -> pure $! filterWithKey f m
, missingKey = \k x -> pure $! if f k x then Just x else Nothing }
{-# INLINE filterMissing #-}
-- | Filter the entries whose keys are missing from the other map
-- using some 'Applicative' action.
--
-- > filterAMissing f = Merge.Lazy.traverseMaybeMissing $
-- > \k x -> (\b -> guard b *> Just x) <$> f k x
--
-- but this should be a little faster.
filterAMissing
:: Applicative f => (Key -> x -> f Bool) -> WhenMissing f x x
filterAMissing f = WhenMissing
{ missingSubtree = \m -> filterWithKeyA f m
, missingKey = \k x -> bool Nothing (Just x) <$> f k x }
{-# INLINE filterAMissing #-}
-- | /O(n)/. Filter keys and values using an 'Applicative' predicate.
filterWithKeyA
:: Applicative f => (Key -> a -> f Bool) -> IntMap a -> f (IntMap a)
filterWithKeyA _ Nil = pure Nil
filterWithKeyA f t@(Tip k x) = (\b -> if b then t else Nil) <$> f k x
filterWithKeyA f (Bin p m l r) =
liftA2 (bin p m) (filterWithKeyA f l) (filterWithKeyA f r)
-- | This wasn't in Data.Bool until 4.7.0, so we define it here
bool :: a -> a -> Bool -> a
bool f _ False = f
bool _ t True = t
-- | Traverse over the entries whose keys are missing from the other
-- map.
traverseMissing
:: Applicative f => (Key -> x -> f y) -> WhenMissing f x y
traverseMissing f = WhenMissing
{ missingSubtree = traverseWithKey f
, missingKey = \k x -> Just <$> f k x }
{-# INLINE traverseMissing #-}
-- | Traverse over the entries whose keys are missing from the other
-- map, optionally producing values to put in the result. This is
-- the most powerful 'WhenMissing' tactic, but others are usually
-- more efficient.
traverseMaybeMissing
:: Applicative f => (Key -> x -> f (Maybe y)) -> WhenMissing f x y
traverseMaybeMissing f = WhenMissing
{ missingSubtree = traverseMaybeWithKey f
, missingKey = f }
{-# INLINE traverseMaybeMissing #-}
-- | /O(n)/. Traverse keys\/values and collect the 'Just' results.
traverseMaybeWithKey
:: Applicative f => (Key -> a -> f (Maybe b)) -> IntMap a -> f (IntMap b)
traverseMaybeWithKey f = go
where
go Nil = pure Nil
go (Tip k x) = maybe Nil (Tip k) <$> f k x
go (Bin p m l r) = liftA2 (bin p m) (go l) (go r)
-- | Merge two maps.
--
-- @merge@ takes two 'WhenMissing' tactics, a 'WhenMatched' tactic
-- and two maps. It uses the tactics to merge the maps. Its behavior
-- is best understood via its fundamental tactics, 'mapMaybeMissing'
-- and 'zipWithMaybeMatched'.
--
-- Consider
--
-- @
-- merge (mapMaybeMissing g1)
-- (mapMaybeMissing g2)
-- (zipWithMaybeMatched f)
-- m1 m2
-- @
--
-- Take, for example,
--
-- @
-- m1 = [(0, 'a'), (1, 'b'), (3,'c'), (4, 'd')]
-- m2 = [(1, "one"), (2, "two"), (4, "three")]
-- @
--
-- @merge@ will first ''align'' these maps by key:
--
-- @
-- m1 = [(0, 'a'), (1, 'b'), (3,'c'), (4, 'd')]
-- m2 = [(1, "one"), (2, "two"), (4, "three")]
-- @
--
-- It will then pass the individual entries and pairs of entries
-- to @g1@, @g2@, or @f@ as appropriate:
--
-- @
-- maybes = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"]
-- @
--
-- This produces a 'Maybe' for each key:
--
-- @
-- keys = 0 1 2 3 4
-- results = [Nothing, Just True, Just False, Nothing, Just True]
-- @
--
-- Finally, the @Just@ results are collected into a map:
--
-- @
-- return value = [(1, True), (2, False), (4, True)]
-- @
--
-- The other tactics below are optimizations or simplifications of
-- 'mapMaybeMissing' for special cases. Most importantly,
--
-- * 'dropMissing' drops all the keys.
-- * 'preserveMissing' leaves all the entries alone.
--
-- When 'merge' is given three arguments, it is inlined at the call
-- site. To prevent excessive inlining, you should typically use
-- 'merge' to define your custom combining functions.
--
--
-- Examples:
--
-- prop> unionWithKey f = merge preserveMissing preserveMissing (zipWithMatched f)
-- prop> intersectionWithKey f = merge dropMissing dropMissing (zipWithMatched f)
-- prop> differenceWith f = merge diffPreserve diffDrop f
-- prop> symmetricDifference = merge diffPreserve diffPreserve (\ _ _ _ -> Nothing)
-- prop> mapEachPiece f g h = merge (diffMapWithKey f) (diffMapWithKey g)
--
-- @since 0.5.8
merge
:: SimpleWhenMissing a c -- ^ What to do with keys in @m1@ but not @m2@
-> SimpleWhenMissing b c -- ^ What to do with keys in @m2@ but not @m1@
-> SimpleWhenMatched a b c -- ^ What to do with keys in both @m1@ and @m2@
-> IntMap a -- ^ Map @m1@
-> IntMap b -- ^ Map @m2@
-> IntMap c
merge g1 g2 f m1 m2 =
runIdentity $ mergeA g1 g2 f m1 m2
{-# INLINE merge #-}
-- | An applicative version of 'merge'.
--
-- @mergeA@ takes two 'WhenMissing' tactics, a 'WhenMatched'
-- tactic and two maps. It uses the tactics to merge the maps.
-- Its behavior is best understood via its fundamental tactics,
-- 'traverseMaybeMissing' and 'zipWithMaybeAMatched'.
--
-- Consider
--
-- @
-- mergeA (traverseMaybeMissing g1)
-- (traverseMaybeMissing g2)
-- (zipWithMaybeAMatched f)
-- m1 m2
-- @
--
-- Take, for example,
--
-- @
-- m1 = [(0, 'a'), (1, 'b'), (3,'c'), (4, 'd')]
-- m2 = [(1, "one"), (2, "two"), (4, "three")]
-- @
--
-- @mergeA@ will first ''align'' these maps by key:
--
-- @
-- m1 = [(0, 'a'), (1, 'b'), (3,'c'), (4, 'd')]
-- m2 = [(1, "one"), (2, "two"), (4, "three")]
-- @
--
-- It will then pass the individual entries and pairs of entries
-- to @g1@, @g2@, or @f@ as appropriate:
--
-- @
-- actions = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"]
-- @
--
-- Next, it will perform the actions in the @actions@ list in order from
-- left to right.
--
-- @
-- keys = 0 1 2 3 4
-- results = [Nothing, Just True, Just False, Nothing, Just True]
-- @
--
-- Finally, the @Just@ results are collected into a map:
--
-- @
-- return value = [(1, True), (2, False), (4, True)]
-- @
--
-- The other tactics below are optimizations or simplifications of
-- 'traverseMaybeMissing' for special cases. Most importantly,
--
-- * 'dropMissing' drops all the keys.
-- * 'preserveMissing' leaves all the entries alone.
-- * 'mapMaybeMissing' does not use the 'Applicative' context.
--
-- When 'mergeA' is given three arguments, it is inlined at the call
-- site. To prevent excessive inlining, you should generally only use
-- 'mergeA' to define custom combining functions.
--
-- @since 0.5.8
mergeA
:: (Applicative f)
=> WhenMissing f a c -- ^ What to do with keys in @m1@ but not @m2@
-> WhenMissing f b c -- ^ What to do with keys in @m2@ but not @m1@
-> WhenMatched f a b c -- ^ What to do with keys in both @m1@ and @m2@
-> IntMap a -- ^ Map @m1@
-> IntMap b -- ^ Map @m2@
-> f (IntMap c)
mergeA
WhenMissing{missingSubtree = g1t, missingKey = g1k}
WhenMissing{missingSubtree = g2t, missingKey = g2k}
WhenMatched{matchedKey = f}
= go
where
go t1 Nil = g1t t1
go Nil t2 = g2t t2
-- This case is already covered below.
-- go (Tip k1 x1) (Tip k2 x2) = mergeTips k1 x1 k2 x2
go (Tip k1 x1) t2' = merge2 t2'
where
merge2 t2@(Bin p2 m2 l2 r2)
| nomatch k1 p2 m2 = linkA k1 (subsingletonBy g1k k1 x1) p2 (g2t t2)
| zero k1 m2 = liftA2 (bin p2 m2) (merge2 l2) (g2t r2)
| otherwise = liftA2 (bin p2 m2) (g2t l2) (merge2 r2)
merge2 (Tip k2 x2) = mergeTips k1 x1 k2 x2
merge2 Nil = subsingletonBy g1k k1 x1
go t1' (Tip k2 x2) = merge1 t1'
where
merge1 t1@(Bin p1 m1 l1 r1)
| nomatch k2 p1 m1 = linkA p1 (g1t t1) k2 (subsingletonBy g2k k2 x2)
| zero k2 m1 = liftA2 (bin p1 m1) (merge1 l1) (g1t r1)
| otherwise = liftA2 (bin p1 m1) (g1t l1) (merge1 r1)
merge1 (Tip k1 x1) = mergeTips k1 x1 k2 x2
merge1 Nil = subsingletonBy g2k k2 x2
go t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
| shorter m1 m2 = merge1
| shorter m2 m1 = merge2
| p1 == p2 = liftA2 (bin p1 m1) (go l1 l2) (go r1 r2)
| otherwise = liftA2 (link_ p1 p2) (g1t t1) (g2t t2)
where
merge1 | nomatch p2 p1 m1 = liftA2 (link_ p1 p2) (g1t t1) (g2t t2)
| zero p2 m1 = liftA2 (bin p1 m1) (go l1 t2) (g1t r1)
| otherwise = liftA2 (bin p1 m1) (g1t l1) (go r1 t2)
merge2 | nomatch p1 p2 m2 = liftA2 (link_ p1 p2) (g1t t1) (g2t t2)
| zero p1 m2 = liftA2 (bin p2 m2) (go t1 l2) (g2t r2)
| otherwise = liftA2 (bin p2 m2) (g2t l2) (go t1 r2)
subsingletonBy gk k x = maybe Nil (Tip k) <$> gk k x
{-# INLINE subsingletonBy #-}
mergeTips k1 x1 k2 x2
| k1 == k2 = maybe Nil (Tip k1) <$> f k1 x1 x2
| k1 < k2 = liftA2 (subdoubleton k1 k2) (g1k k1 x1) (g2k k2 x2)
{-
= link_ k1 k2 <$> subsingletonBy g1k k1 x1 <*> subsingletonBy g2k k2 x2
-}
| otherwise = liftA2 (subdoubleton k2 k1) (g2k k2 x2) (g1k k1 x1)
{-# INLINE mergeTips #-}
subdoubleton _ _ Nothing Nothing = Nil
subdoubleton _ k2 Nothing (Just y2) = Tip k2 y2
subdoubleton k1 _ (Just y1) Nothing = Tip k1 y1
subdoubleton k1 k2 (Just y1) (Just y2) = link k1 (Tip k1 y1) k2 (Tip k2 y2)
{-# INLINE subdoubleton #-}
link_ _ _ Nil t2 = t2
link_ _ _ t1 Nil = t1
link_ p1 p2 t1 t2 = link p1 t1 p2 t2
{-# INLINE link_ #-}
-- | A variant of 'link_' which makes sure to execute side-effects
-- in the right order.
linkA
:: Applicative f
=> Prefix -> f (IntMap a)
-> Prefix -> f (IntMap a)
-> f (IntMap a)
linkA p1 t1 p2 t2
| zero p1 m = liftA2 (bin p m) t1 t2
| otherwise = liftA2 (bin p m) t2 t1
where
m = branchMask p1 p2
p = mask p1 m
{-# INLINE linkA #-}
{-# INLINE mergeA #-}
{--------------------------------------------------------------------
Min\/Max
--------------------------------------------------------------------}
-- | /O(min(n,W))/. Update the value at the minimal key.
--
-- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
-- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMinWithKey :: (Key -> a -> Maybe a) -> IntMap a -> IntMap a
updateMinWithKey f t =
case t of Bin p m l r | m < 0 -> binCheckRight p m l (go f r)
_ -> go f t
where
go f' (Bin p m l r) = binCheckLeft p m (go f' l) r
go f' (Tip k y) = case f' k y of
Just y' -> Tip k y'
Nothing -> Nil
go _ Nil = error "updateMinWithKey Nil"
-- | /O(min(n,W))/. Update the value at the maximal key.
--
-- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
-- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMaxWithKey :: (Key -> a -> Maybe a) -> IntMap a -> IntMap a
updateMaxWithKey f t =
case t of Bin p m l r | m < 0 -> binCheckLeft p m (go f l) r
_ -> go f t
where
go f' (Bin p m l r) = binCheckRight p m l (go f' r)
go f' (Tip k y) = case f' k y of
Just y' -> Tip k y'
Nothing -> Nil
go _ Nil = error "updateMaxWithKey Nil"
data View a = View {-# UNPACK #-} !Key a !(IntMap a)
-- | /O(min(n,W))/. Retrieves the maximal (key,value) pair of the map, and
-- the map stripped of that element, or 'Nothing' if passed an empty map.
--
-- > maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b")
-- > maxViewWithKey empty == Nothing
maxViewWithKey :: IntMap a -> Maybe ((Key, a), IntMap a)
maxViewWithKey t =
case t of
Nil -> Nothing
Bin p m l r | m < 0 ->
Just $ case go l of View k a l' -> ((k, a), binCheckLeft p m l' r)
_ -> Just $ case go t of View k a t' -> ((k, a), t')
where
go (Bin p m l r) =
case go r of View k a r' -> View k a (binCheckRight p m l r')
go (Tip k y) = View k y Nil
go Nil = error "maxViewWithKey Nil"
-- | /O(min(n,W))/. Retrieves the minimal (key,value) pair of the map, and
-- the map stripped of that element, or 'Nothing' if passed an empty map.
--
-- > minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a")
-- > minViewWithKey empty == Nothing
minViewWithKey :: IntMap a -> Maybe ((Key, a), IntMap a)
minViewWithKey t =
case t of
Nil -> Nothing
Bin p m l r | m < 0 ->
Just $ case go r of View k a r' -> ((k, a), binCheckRight p m l r')
_ -> Just $ case go t of View k a t' -> ((k, a), t')
where
go (Bin p m l r) =
case go l of View k a l' -> View k a (binCheckLeft p m l' r)
go (Tip k y) = View k y Nil
go Nil = error "minViewWithKey Nil"
-- | /O(min(n,W))/. Update the value at the maximal key.
--
-- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
-- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMax :: (a -> Maybe a) -> IntMap a -> IntMap a
updateMax f = updateMaxWithKey (const f)
-- | /O(min(n,W))/. Update the value at the minimal key.
--
-- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
-- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMin :: (a -> Maybe a) -> IntMap a -> IntMap a
updateMin f = updateMinWithKey (const f)
-- Similar to the Arrow instance.
first :: (a -> c) -> (a, b) -> (c, b)
first f (x,y) = (f x,y)
-- | /O(min(n,W))/. Retrieves the maximal key of the map, and the map
-- stripped of that element, or 'Nothing' if passed an empty map.
maxView :: IntMap a -> Maybe (a, IntMap a)
maxView t = liftM (first snd) (maxViewWithKey t)
-- | /O(min(n,W))/. Retrieves the minimal key of the map, and the map
-- stripped of that element, or 'Nothing' if passed an empty map.
minView :: IntMap a -> Maybe (a, IntMap a)
minView t = liftM (first snd) (minViewWithKey t)
-- | /O(min(n,W))/. Delete and find the maximal element.
deleteFindMax :: IntMap a -> ((Key, a), IntMap a)
deleteFindMax = fromMaybe (error "deleteFindMax: empty map has no maximal element") . maxViewWithKey
-- | /O(min(n,W))/. Delete and find the minimal element.
deleteFindMin :: IntMap a -> ((Key, a), IntMap a)
deleteFindMin = fromMaybe (error "deleteFindMin: empty map has no minimal element") . minViewWithKey
-- | /O(min(n,W))/. The minimal key of the map.
findMin :: IntMap a -> (Key, a)
findMin Nil = error $ "findMin: empty map has no minimal element"
findMin (Tip k v) = (k,v)
findMin (Bin _ m l r)
| m < 0 = go r
| otherwise = go l
where go (Tip k v) = (k,v)
go (Bin _ _ l' _) = go l'
go Nil = error "findMax Nil"
-- | /O(min(n,W))/. The maximal key of the map.
findMax :: IntMap a -> (Key, a)
findMax Nil = error $ "findMax: empty map has no maximal element"
findMax (Tip k v) = (k,v)
findMax (Bin _ m l r)
| m < 0 = go l
| otherwise = go r
where go (Tip k v) = (k,v)
go (Bin _ _ _ r') = go r'
go Nil = error "findMax Nil"
-- | /O(min(n,W))/. Delete the minimal key. Returns an empty map if the map is empty.
--
-- Note that this is a change of behaviour for consistency with 'Data.Map.Map' –
-- versions prior to 0.5 threw an error if the 'IntMap' was already empty.
deleteMin :: IntMap a -> IntMap a
deleteMin = maybe Nil snd . minView
-- | /O(min(n,W))/. Delete the maximal key. Returns an empty map if the map is empty.
--
-- Note that this is a change of behaviour for consistency with 'Data.Map.Map' –
-- versions prior to 0.5 threw an error if the 'IntMap' was already empty.
deleteMax :: IntMap a -> IntMap a
deleteMax = maybe Nil snd . maxView
{--------------------------------------------------------------------
Submap
--------------------------------------------------------------------}
-- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
-- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
isProperSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
isProperSubmapOf m1 m2
= isProperSubmapOfBy (==) m1 m2
{- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
@m1@ and @m2@ are not equal,
all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
applied to their respective values. For example, the following
expressions are all 'True':
> isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
> isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
But the following are all 'False':
> isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
> isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
> isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
-}
isProperSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
isProperSubmapOfBy predicate t1 t2
= case submapCmp predicate t1 t2 of
LT -> True
_ -> False
submapCmp :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Ordering
submapCmp predicate t1@(Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
| shorter m1 m2 = GT
| shorter m2 m1 = submapCmpLt
| p1 == p2 = submapCmpEq
| otherwise = GT -- disjoint
where
submapCmpLt | nomatch p1 p2 m2 = GT
| zero p1 m2 = submapCmp predicate t1 l2
| otherwise = submapCmp predicate t1 r2
submapCmpEq = case (submapCmp predicate l1 l2, submapCmp predicate r1 r2) of
(GT,_ ) -> GT
(_ ,GT) -> GT
(EQ,EQ) -> EQ
_ -> LT
submapCmp _ (Bin _ _ _ _) _ = GT
submapCmp predicate (Tip kx x) (Tip ky y)
| (kx == ky) && predicate x y = EQ
| otherwise = GT -- disjoint
submapCmp predicate (Tip k x) t
= case lookup k t of
Just y | predicate x y -> LT
_ -> GT -- disjoint
submapCmp _ Nil Nil = EQ
submapCmp _ Nil _ = LT
-- | /O(n+m)/. Is this a submap?
-- Defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
isSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
isSubmapOf m1 m2
= isSubmapOfBy (==) m1 m2
{- | /O(n+m)/.
The expression (@'isSubmapOfBy' f m1 m2@) returns 'True' if
all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
applied to their respective values. For example, the following
expressions are all 'True':
> isSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
> isSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
> isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
But the following are all 'False':
> isSubmapOfBy (==) (fromList [(1,2)]) (fromList [(1,1),(2,2)])
> isSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
> isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
-}
isSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
isSubmapOfBy predicate t1@(Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
| shorter m1 m2 = False
| shorter m2 m1 = match p1 p2 m2 &&
if zero p1 m2
then isSubmapOfBy predicate t1 l2
else isSubmapOfBy predicate t1 r2
| otherwise = (p1==p2) && isSubmapOfBy predicate l1 l2 && isSubmapOfBy predicate r1 r2
isSubmapOfBy _ (Bin _ _ _ _) _ = False
isSubmapOfBy predicate (Tip k x) t = case lookup k t of
Just y -> predicate x y
Nothing -> False
isSubmapOfBy _ Nil _ = True
{--------------------------------------------------------------------
Mapping
--------------------------------------------------------------------}
-- | /O(n)/. Map a function over all values in the map.
--
-- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
map :: (a -> b) -> IntMap a -> IntMap b
map f = go
where
go (Bin p m l r) = Bin p m (go l) (go r)
go (Tip k x) = Tip k (f x)
go Nil = Nil
{-# NOINLINE [1] map #-}
{-# RULES
"map/map" forall f g xs . map f (map g xs) = map (f . g) xs
#-}
-- Safe coercions were introduced in 7.8, but did not play well with RULES yet.
{-# RULES
"map/coerce" map coerce = coerce
#-}
-- | /O(n)/. Map a function over all values in the map.
--
-- > let f key x = (show key) ++ ":" ++ x
-- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
mapWithKey :: (Key -> a -> b) -> IntMap a -> IntMap b
mapWithKey f t
= case t of
Bin p m l r -> Bin p m (mapWithKey f l) (mapWithKey f r)
Tip k x -> Tip k (f k x)
Nil -> Nil
{-# NOINLINE [1] mapWithKey #-}
{-# RULES
"mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
mapWithKey (\k a -> f k (g k a)) xs
"mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
mapWithKey (\k a -> f k (g a)) xs
"map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
mapWithKey (\k a -> f (g k a)) xs
#-}
-- | /O(n)/.
-- @'traverseWithKey' f s == 'fromList' <$> 'traverse' (\(k, v) -> (,) k <$> f k v) ('toList' m)@
-- That is, behaves exactly like a regular 'traverse' except that the traversing
-- function also has access to the key associated with a value.
--
-- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')])
-- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == Nothing
traverseWithKey :: Applicative t => (Key -> a -> t b) -> IntMap a -> t (IntMap b)
traverseWithKey f = go
where
go Nil = pure Nil
go (Tip k v) = Tip k <$> f k v
go (Bin p m l r) = liftA2 (Bin p m) (go l) (go r)
{-# INLINE traverseWithKey #-}
-- | /O(n)/. The function @'mapAccum'@ threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a b = (a ++ b, b ++ "X")
-- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
mapAccum :: (a -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
mapAccum f = mapAccumWithKey (\a' _ x -> f a' x)
-- | /O(n)/. The function @'mapAccumWithKey'@ threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
-- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
mapAccumWithKey :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
mapAccumWithKey f a t
= mapAccumL f a t
-- | /O(n)/. The function @'mapAccumL'@ threads an accumulating
-- argument through the map in ascending order of keys.
mapAccumL :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
mapAccumL f a t
= case t of
Bin p m l r -> let (a1,l') = mapAccumL f a l
(a2,r') = mapAccumL f a1 r
in (a2,Bin p m l' r')
Tip k x -> let (a',x') = f a k x in (a',Tip k x')
Nil -> (a,Nil)
-- | /O(n)/. The function @'mapAccumR'@ threads an accumulating
-- argument through the map in descending order of keys.
mapAccumRWithKey :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
mapAccumRWithKey f a t
= case t of
Bin p m l r -> let (a1,r') = mapAccumRWithKey f a r
(a2,l') = mapAccumRWithKey f a1 l
in (a2,Bin p m l' r')
Tip k x -> let (a',x') = f a k x in (a',Tip k x')
Nil -> (a,Nil)
-- | /O(n*min(n,W))/.
-- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the value at the greatest of the
-- original keys is retained.
--
-- > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")]
-- > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
-- > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"
mapKeys :: (Key->Key) -> IntMap a -> IntMap a
mapKeys f = fromList . foldrWithKey (\k x xs -> (f k, x) : xs) []
-- | /O(n*min(n,W))/.
-- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the associated values will be
-- combined using @c@.
--
-- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
-- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
mapKeysWith :: (a -> a -> a) -> (Key->Key) -> IntMap a -> IntMap a
mapKeysWith c f
= fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
-- | /O(n*min(n,W))/.
-- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
-- is strictly monotonic.
-- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@.
-- /The precondition is not checked./
-- Semi-formally, we have:
--
-- > and [x < y ==> f x < f y | x <- ls, y <- ls]
-- > ==> mapKeysMonotonic f s == mapKeys f s
-- > where ls = keys s
--
-- This means that @f@ maps distinct original keys to distinct resulting keys.
-- This function has slightly better performance than 'mapKeys'.
--
-- > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]
mapKeysMonotonic :: (Key->Key) -> IntMap a -> IntMap a
mapKeysMonotonic f
= fromDistinctAscList . foldrWithKey (\k x xs -> (f k, x) : xs) []
{--------------------------------------------------------------------
Filter
--------------------------------------------------------------------}
-- | /O(n)/. Filter all values that satisfy some predicate.
--
-- > filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty
-- > filter (< "a") (fromList [(5,"a"), (3,"b")]) == empty
filter :: (a -> Bool) -> IntMap a -> IntMap a
filter p m
= filterWithKey (\_ x -> p x) m
-- | /O(n)/. Filter all keys\/values that satisfy some predicate.
--
-- > filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
filterWithKey :: (Key -> a -> Bool) -> IntMap a -> IntMap a
filterWithKey predicate = go
where
go Nil = Nil
go t@(Tip k x) = if predicate k x then t else Nil
go (Bin p m l r) = bin p m (go l) (go r)
-- | /O(n)/. Partition the map according to some predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
--
-- > partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
-- > partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
-- > partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
partition :: (a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
partition p m
= partitionWithKey (\_ x -> p x) m
-- | /O(n)/. Partition the map according to some predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
--
-- > partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b")
-- > partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
-- > partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
partitionWithKey :: (Key -> a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
partitionWithKey predicate0 t0 = toPair $ go predicate0 t0
where
go predicate t =
case t of
Bin p m l r ->
let (l1 :*: l2) = go predicate l
(r1 :*: r2) = go predicate r
in bin p m l1 r1 :*: bin p m l2 r2
Tip k x
| predicate k x -> (t :*: Nil)
| otherwise -> (Nil :*: t)
Nil -> (Nil :*: Nil)
-- | /O(n)/. Map values and collect the 'Just' results.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
mapMaybe :: (a -> Maybe b) -> IntMap a -> IntMap b
mapMaybe f = mapMaybeWithKey (\_ x -> f x)
-- | /O(n)/. Map keys\/values and collect the 'Just' results.
--
-- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
-- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
mapMaybeWithKey :: (Key -> a -> Maybe b) -> IntMap a -> IntMap b
mapMaybeWithKey f (Bin p m l r)
= bin p m (mapMaybeWithKey f l) (mapMaybeWithKey f r)
mapMaybeWithKey f (Tip k x) = case f k x of
Just y -> Tip k y
Nothing -> Nil
mapMaybeWithKey _ Nil = Nil
-- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
--
-- > let f a = if a < "c" then Left a else Right a
-- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
-- >
-- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
mapEither :: (a -> Either b c) -> IntMap a -> (IntMap b, IntMap c)
mapEither f m
= mapEitherWithKey (\_ x -> f x) m
-- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
--
-- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
-- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
-- >
-- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
mapEitherWithKey :: (Key -> a -> Either b c) -> IntMap a -> (IntMap b, IntMap c)
mapEitherWithKey f0 t0 = toPair $ go f0 t0
where
go f (Bin p m l r) =
bin p m l1 r1 :*: bin p m l2 r2
where
(l1 :*: l2) = go f l
(r1 :*: r2) = go f r
go f (Tip k x) = case f k x of
Left y -> (Tip k y :*: Nil)
Right z -> (Nil :*: Tip k z)
go _ Nil = (Nil :*: Nil)
-- | /O(min(n,W))/. The expression (@'split' k map@) is a pair @(map1,map2)@
-- where all keys in @map1@ are lower than @k@ and all keys in
-- @map2@ larger than @k@. Any key equal to @k@ is found in neither @map1@ nor @map2@.
--
-- > split 2 (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3,"b"), (5,"a")])
-- > split 3 (fromList [(5,"a"), (3,"b")]) == (empty, singleton 5 "a")
-- > split 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
-- > split 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", empty)
-- > split 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], empty)
split :: Key -> IntMap a -> (IntMap a, IntMap a)
split k t =
case t of
Bin _ m l r
| m < 0 ->
if k >= 0 -- handle negative numbers.
then
case go k l of
(lt :*: gt) ->
let !lt' = union r lt
in (lt', gt)
else
case go k r of
(lt :*: gt) ->
let !gt' = union gt l
in (lt, gt')
_ -> case go k t of
(lt :*: gt) -> (lt, gt)
where
go k' t'@(Bin p m l r)
| nomatch k' p m = if k' > p then t' :*: Nil else Nil :*: t'
| zero k' m = case go k' l of (lt :*: gt) -> lt :*: union gt r
| otherwise = case go k' r of (lt :*: gt) -> union l lt :*: gt
go k' t'@(Tip ky _)
| k' > ky = (t' :*: Nil)
| k' < ky = (Nil :*: t')
| otherwise = (Nil :*: Nil)
go _ Nil = (Nil :*: Nil)
data SplitLookup a = SplitLookup !(IntMap a) !(Maybe a) !(IntMap a)
mapLT :: (IntMap a -> IntMap a) -> SplitLookup a -> SplitLookup a
mapLT f (SplitLookup lt fnd gt) = SplitLookup (f lt) fnd gt
{-# INLINE mapLT #-}
mapGT :: (IntMap a -> IntMap a) -> SplitLookup a -> SplitLookup a
mapGT f (SplitLookup lt fnd gt) = SplitLookup lt fnd (f gt)
{-# INLINE mapGT #-}
-- | /O(min(n,W))/. Performs a 'split' but also returns whether the pivot
-- key was found in the original map.
--
-- > splitLookup 2 (fromList [(5,"a"), (3,"b")]) == (empty, Nothing, fromList [(3,"b"), (5,"a")])
-- > splitLookup 3 (fromList [(5,"a"), (3,"b")]) == (empty, Just "b", singleton 5 "a")
-- > splitLookup 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Nothing, singleton 5 "a")
-- > splitLookup 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Just "a", empty)
-- > splitLookup 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], Nothing, empty)
splitLookup :: Key -> IntMap a -> (IntMap a, Maybe a, IntMap a)
splitLookup k t =
case
case t of
Bin _ m l r
| m < 0 ->
if k >= 0 -- handle negative numbers.
then mapLT (union r) (go k l)
else mapGT (`union` l) (go k r)
_ -> go k t
of SplitLookup lt fnd gt -> (lt, fnd, gt)
where
go k' t'@(Bin p m l r)
| nomatch k' p m =
if k' > p
then SplitLookup t' Nothing Nil
else SplitLookup Nil Nothing t'
| zero k' m = mapGT (`union` r) (go k' l)
| otherwise = mapLT (union l) (go k' r)
go k' t'@(Tip ky y)
| k' > ky = SplitLookup t' Nothing Nil
| k' < ky = SplitLookup Nil Nothing t'
| otherwise = SplitLookup Nil (Just y) Nil
go _ Nil = SplitLookup Nil Nothing Nil
{--------------------------------------------------------------------
Fold
--------------------------------------------------------------------}
-- | /O(n)/. Fold the values in the map using the given right-associative
-- binary operator, such that @'foldr' f z == 'Prelude.foldr' f z . 'elems'@.
--
-- For example,
--
-- > elems map = foldr (:) [] map
--
-- > let f a len = len + (length a)
-- > foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
foldr :: (a -> b -> b) -> b -> IntMap a -> b
foldr f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z l) r -- put negative numbers before
| otherwise -> go (go z r) l
_ -> go z t
where
go z' Nil = z'
go z' (Tip _ x) = f x z'
go z' (Bin _ _ l r) = go (go z' r) l
{-# INLINE foldr #-}
-- | /O(n)/. A strict version of 'foldr'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldr' :: (a -> b -> b) -> b -> IntMap a -> b
foldr' f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z l) r -- put negative numbers before
| otherwise -> go (go z r) l
_ -> go z t
where
go !z' Nil = z'
go z' (Tip _ x) = f x z'
go z' (Bin _ _ l r) = go (go z' r) l
{-# INLINE foldr' #-}
-- | /O(n)/. Fold the values in the map using the given left-associative
-- binary operator, such that @'foldl' f z == 'Prelude.foldl' f z . 'elems'@.
--
-- For example,
--
-- > elems = reverse . foldl (flip (:)) []
--
-- > let f len a = len + (length a)
-- > foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
foldl :: (a -> b -> a) -> a -> IntMap b -> a
foldl f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z r) l -- put negative numbers before
| otherwise -> go (go z l) r
_ -> go z t
where
go z' Nil = z'
go z' (Tip _ x) = f z' x
go z' (Bin _ _ l r) = go (go z' l) r
{-# INLINE foldl #-}
-- | /O(n)/. A strict version of 'foldl'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldl' :: (a -> b -> a) -> a -> IntMap b -> a
foldl' f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z r) l -- put negative numbers before
| otherwise -> go (go z l) r
_ -> go z t
where
go !z' Nil = z'
go z' (Tip _ x) = f z' x
go z' (Bin _ _ l r) = go (go z' l) r
{-# INLINE foldl' #-}
-- | /O(n)/. Fold the keys and values in the map using the given right-associative
-- binary operator, such that
-- @'foldrWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
--
-- For example,
--
-- > keys map = foldrWithKey (\k x ks -> k:ks) [] map
--
-- > let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
-- > foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"
foldrWithKey :: (Key -> a -> b -> b) -> b -> IntMap a -> b
foldrWithKey f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z l) r -- put negative numbers before
| otherwise -> go (go z r) l
_ -> go z t
where
go z' Nil = z'
go z' (Tip kx x) = f kx x z'
go z' (Bin _ _ l r) = go (go z' r) l
{-# INLINE foldrWithKey #-}
-- | /O(n)/. A strict version of 'foldrWithKey'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldrWithKey' :: (Key -> a -> b -> b) -> b -> IntMap a -> b
foldrWithKey' f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z l) r -- put negative numbers before
| otherwise -> go (go z r) l
_ -> go z t
where
go !z' Nil = z'
go z' (Tip kx x) = f kx x z'
go z' (Bin _ _ l r) = go (go z' r) l
{-# INLINE foldrWithKey' #-}
-- | /O(n)/. Fold the keys and values in the map using the given left-associative
-- binary operator, such that
-- @'foldlWithKey' f z == 'Prelude.foldl' (\\z' (kx, x) -> f z' kx x) z . 'toAscList'@.
--
-- For example,
--
-- > keys = reverse . foldlWithKey (\ks k x -> k:ks) []
--
-- > let f result k a = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
-- > foldlWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (3:b)(5:a)"
foldlWithKey :: (a -> Key -> b -> a) -> a -> IntMap b -> a
foldlWithKey f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z r) l -- put negative numbers before
| otherwise -> go (go z l) r
_ -> go z t
where
go z' Nil = z'
go z' (Tip kx x) = f z' kx x
go z' (Bin _ _ l r) = go (go z' l) r
{-# INLINE foldlWithKey #-}
-- | /O(n)/. A strict version of 'foldlWithKey'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldlWithKey' :: (a -> Key -> b -> a) -> a -> IntMap b -> a
foldlWithKey' f z = \t -> -- Use lambda t to be inlinable with two arguments only.
case t of
Bin _ m l r
| m < 0 -> go (go z r) l -- put negative numbers before
| otherwise -> go (go z l) r
_ -> go z t
where
go !z' Nil = z'
go z' (Tip kx x) = f z' kx x
go z' (Bin _ _ l r) = go (go z' l) r
{-# INLINE foldlWithKey' #-}
-- | /O(n)/. Fold the keys and values in the map using the given monoid, such that
--
-- @'foldMapWithKey' f = 'Prelude.fold' . 'mapWithKey' f@
--
-- This can be an asymptotically faster than 'foldrWithKey' or 'foldlWithKey' for some monoids.
foldMapWithKey :: Monoid m => (Key -> a -> m) -> IntMap a -> m
foldMapWithKey f = go
where
go Nil = mempty
go (Tip kx x) = f kx x
go (Bin _ _ l r) = go l `mappend` go r
{-# INLINE foldMapWithKey #-}
{--------------------------------------------------------------------
List variations
--------------------------------------------------------------------}
-- | /O(n)/.
-- Return all elements of the map in the ascending order of their keys.
-- Subject to list fusion.
--
-- > elems (fromList [(5,"a"), (3,"b")]) == ["b","a"]
-- > elems empty == []
elems :: IntMap a -> [a]
elems = foldr (:) []
-- | /O(n)/. Return all keys of the map in ascending order. Subject to list
-- fusion.
--
-- > keys (fromList [(5,"a"), (3,"b")]) == [3,5]
-- > keys empty == []
keys :: IntMap a -> [Key]
keys = foldrWithKey (\k _ ks -> k : ks) []
-- | /O(n)/. An alias for 'toAscList'. Returns all key\/value pairs in the
-- map in ascending key order. Subject to list fusion.
--
-- > assocs (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
-- > assocs empty == []
assocs :: IntMap a -> [(Key,a)]
assocs = toAscList
-- | /O(n*min(n,W))/. The set of all keys of the map.
--
-- > keysSet (fromList [(5,"a"), (3,"b")]) == Data.IntSet.fromList [3,5]
-- > keysSet empty == Data.IntSet.empty
keysSet :: IntMap a -> IntSet.IntSet
keysSet Nil = IntSet.Nil
keysSet (Tip kx _) = IntSet.singleton kx
keysSet (Bin p m l r)
| m .&. IntSet.suffixBitMask == 0 = IntSet.Bin p m (keysSet l) (keysSet r)
| otherwise = IntSet.Tip (p .&. IntSet.prefixBitMask) (computeBm (computeBm 0 l) r)
where computeBm !acc (Bin _ _ l' r') = computeBm (computeBm acc l') r'
computeBm acc (Tip kx _) = acc .|. IntSet.bitmapOf kx
computeBm _ Nil = error "Data.IntSet.keysSet: Nil"
-- | /O(n)/. Build a map from a set of keys and a function which for each key
-- computes its value.
--
-- > fromSet (\k -> replicate k 'a') (Data.IntSet.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
-- > fromSet undefined Data.IntSet.empty == empty
fromSet :: (Key -> a) -> IntSet.IntSet -> IntMap a
fromSet _ IntSet.Nil = Nil
fromSet f (IntSet.Bin p m l r) = Bin p m (fromSet f l) (fromSet f r)
fromSet f (IntSet.Tip kx bm) = buildTree f kx bm (IntSet.suffixBitMask + 1)
where
-- This is slightly complicated, as we to convert the dense
-- representation of IntSet into tree representation of IntMap.
--
-- We are given a nonzero bit mask 'bmask' of 'bits' bits with
-- prefix 'prefix'. We split bmask into halves corresponding
-- to left and right subtree. If they are both nonempty, we
-- create a Bin node, otherwise exactly one of them is nonempty
-- and we construct the IntMap from that half.
buildTree g !prefix !bmask bits = case bits of
0 -> Tip prefix (g prefix)
_ -> case intFromNat ((natFromInt bits) `shiftRL` 1) of
bits2
| bmask .&. ((1 `shiftLL` bits2) - 1) == 0 ->
buildTree g (prefix + bits2) (bmask `shiftRL` bits2) bits2
| (bmask `shiftRL` bits2) .&. ((1 `shiftLL` bits2) - 1) == 0 ->
buildTree g prefix bmask bits2
| otherwise ->
Bin prefix bits2
(buildTree g prefix bmask bits2)
(buildTree g (prefix + bits2) (bmask `shiftRL` bits2) bits2)
{--------------------------------------------------------------------
Lists
--------------------------------------------------------------------}
instance GHCExts.IsList (IntMap a) where
type Item (IntMap a) = (Key,a)
fromList = fromList
toList = toList
-- | /O(n)/. Convert the map to a list of key\/value pairs. Subject to list
-- fusion.
--
-- > toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
-- > toList empty == []
toList :: IntMap a -> [(Key,a)]
toList = toAscList
-- | /O(n)/. Convert the map to a list of key\/value pairs where the
-- keys are in ascending order. Subject to list fusion.
--
-- > toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
toAscList :: IntMap a -> [(Key,a)]
toAscList = foldrWithKey (\k x xs -> (k,x):xs) []
-- | /O(n)/. Convert the map to a list of key\/value pairs where the keys
-- are in descending order. Subject to list fusion.
--
-- > toDescList (fromList [(5,"a"), (3,"b")]) == [(5,"a"), (3,"b")]
toDescList :: IntMap a -> [(Key,a)]
toDescList = foldlWithKey (\xs k x -> (k,x):xs) []
-- List fusion for the list generating functions.
-- The foldrFB and foldlFB are fold{r,l}WithKey equivalents, used for list fusion.
-- They are important to convert unfused methods back, see mapFB in prelude.
foldrFB :: (Key -> a -> b -> b) -> b -> IntMap a -> b
foldrFB = foldrWithKey
{-# INLINE[0] foldrFB #-}
foldlFB :: (a -> Key -> b -> a) -> a -> IntMap b -> a
foldlFB = foldlWithKey
{-# INLINE[0] foldlFB #-}
-- Inline assocs and toList, so that we need to fuse only toAscList.
{-# INLINE assocs #-}
{-# INLINE toList #-}
-- The fusion is enabled up to phase 2 included. If it does not succeed,
-- convert in phase 1 the expanded elems,keys,to{Asc,Desc}List calls back to
-- elems,keys,to{Asc,Desc}List. In phase 0, we inline fold{lr}FB (which were
-- used in a list fusion, otherwise it would go away in phase 1), and let compiler
-- do whatever it wants with elems,keys,to{Asc,Desc}List -- it was forbidden to
-- inline it before phase 0, otherwise the fusion rules would not fire at all.
{-# NOINLINE[0] elems #-}
{-# NOINLINE[0] keys #-}
{-# NOINLINE[0] toAscList #-}
{-# NOINLINE[0] toDescList #-}
{-# RULES "IntMap.elems" [~1] forall m . elems m = build (\c n -> foldrFB (\_ x xs -> c x xs) n m) #-}
{-# RULES "IntMap.elemsBack" [1] foldrFB (\_ x xs -> x : xs) [] = elems #-}
{-# RULES "IntMap.keys" [~1] forall m . keys m = build (\c n -> foldrFB (\k _ xs -> c k xs) n m) #-}
{-# RULES "IntMap.keysBack" [1] foldrFB (\k _ xs -> k : xs) [] = keys #-}
{-# RULES "IntMap.toAscList" [~1] forall m . toAscList m = build (\c n -> foldrFB (\k x xs -> c (k,x) xs) n m) #-}
{-# RULES "IntMap.toAscListBack" [1] foldrFB (\k x xs -> (k, x) : xs) [] = toAscList #-}
{-# RULES "IntMap.toDescList" [~1] forall m . toDescList m = build (\c n -> foldlFB (\xs k x -> c (k,x) xs) n m) #-}
{-# RULES "IntMap.toDescListBack" [1] foldlFB (\xs k x -> (k, x) : xs) [] = toDescList #-}
-- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs.
--
-- > fromList [] == empty
-- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
-- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
fromList :: [(Key,a)] -> IntMap a
fromList xs
= foldlStrict ins empty xs
where
ins t (k,x) = insert k x t
-- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
--
-- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "ab"), (5, "cba")]
-- > fromListWith (++) [] == empty
fromListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a
fromListWith f xs
= fromListWithKey (\_ x y -> f x y) xs
-- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs with a combining function. See also fromAscListWithKey'.
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "3:a|b"), (5, "5:c|5:b|a")]
-- > fromListWithKey f [] == empty
fromListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a
fromListWithKey f xs
= foldlStrict ins empty xs
where
ins t (k,x) = insertWithKey f k x t
-- | /O(n)/. Build a map from a list of key\/value pairs where
-- the keys are in ascending order.
--
-- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
fromAscList :: [(Key,a)] -> IntMap a
fromAscList xs
= fromAscListWithKey (\_ x _ -> x) xs
-- | /O(n)/. Build a map from a list of key\/value pairs where
-- the keys are in ascending order, with a combining function on equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
fromAscListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a
fromAscListWith f xs
= fromAscListWithKey (\_ x y -> f x y) xs
-- | /O(n)/. Build a map from a list of key\/value pairs where
-- the keys are in ascending order, with a combining function on equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "5:b|a")]
fromAscListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a
fromAscListWithKey _ [] = Nil
fromAscListWithKey f (x0 : xs0) = fromDistinctAscList (combineEq x0 xs0)
where
-- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
combineEq z [] = [z]
combineEq z@(kz,zz) (x@(kx,xx):xs)
| kx==kz = let yy = f kx xx zz in combineEq (kx,yy) xs
| otherwise = z:combineEq x xs
-- | /O(n)/. Build a map from a list of key\/value pairs where
-- the keys are in ascending order and all distinct.
-- /The precondition (input list is strictly ascending) is not checked./
--
-- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
fromDistinctAscList :: forall a. [(Key,a)] -> IntMap a
fromDistinctAscList [] = Nil
fromDistinctAscList (z0 : zs0) = work z0 zs0 Nada
where
work (kx,vx) [] stk = finish kx (Tip kx vx) stk
work (kx,vx) (z@(kz,_):zs) stk = reduce z zs (branchMask kx kz) kx (Tip kx vx) stk
reduce :: (Key,a) -> [(Key,a)] -> Mask -> Prefix -> IntMap a -> Stack a -> IntMap a
reduce z zs _ px tx Nada = work z zs (Push px tx Nada)
reduce z zs m px tx stk@(Push py ty stk') =
let mxy = branchMask px py
pxy = mask px mxy
in if shorter m mxy
then reduce z zs m pxy (Bin pxy mxy ty tx) stk'
else work z zs (Push px tx stk)
finish _ t Nada = t
finish px tx (Push py ty stk) = finish p (link py ty px tx) stk
where m = branchMask px py
p = mask px m
data Stack a = Push {-# UNPACK #-} !Prefix !(IntMap a) !(Stack a) | Nada
{--------------------------------------------------------------------
Eq
--------------------------------------------------------------------}
instance Eq a => Eq (IntMap a) where
t1 == t2 = equal t1 t2
t1 /= t2 = nequal t1 t2
equal :: Eq a => IntMap a -> IntMap a -> Bool
equal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
= (m1 == m2) && (p1 == p2) && (equal l1 l2) && (equal r1 r2)
equal (Tip kx x) (Tip ky y)
= (kx == ky) && (x==y)
equal Nil Nil = True
equal _ _ = False
nequal :: Eq a => IntMap a -> IntMap a -> Bool
nequal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
= (m1 /= m2) || (p1 /= p2) || (nequal l1 l2) || (nequal r1 r2)
nequal (Tip kx x) (Tip ky y)
= (kx /= ky) || (x/=y)
nequal Nil Nil = False
nequal _ _ = True
instance Eq1 IntMap where
liftEq eq (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
= (m1 == m2) && (p1 == p2) && (liftEq eq l1 l2) && (liftEq eq r1 r2)
liftEq eq (Tip kx x) (Tip ky y)
= (kx == ky) && (eq x y)
liftEq _eq Nil Nil = True
liftEq _eq _ _ = False
{--------------------------------------------------------------------
Ord
--------------------------------------------------------------------}
instance Ord a => Ord (IntMap a) where
compare m1 m2 = compare (toList m1) (toList m2)
instance Ord1 IntMap where
liftCompare cmp m n =
liftCompare (liftCompare cmp) (toList m) (toList n)
{--------------------------------------------------------------------
Functor
--------------------------------------------------------------------}
instance Functor IntMap where
fmap = map
a <$ Bin p m l r = Bin p m (a <$ l) (a <$ r)
a <$ Tip k _ = Tip k a
_ <$ Nil = Nil
{--------------------------------------------------------------------
Show
--------------------------------------------------------------------}
instance Show a => Show (IntMap a) where
showsPrec d m = showParen (d > 10) $
showString "fromList " . shows (toList m)
instance Show1 IntMap where
liftShowsPrec sp sl d m =
showsUnaryWith (liftShowsPrec sp' sl') "fromList" d (toList m)
where
sp' = liftShowsPrec sp sl
sl' = liftShowList sp sl
{--------------------------------------------------------------------
Read
--------------------------------------------------------------------}
instance (Read e) => Read (IntMap e) where
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
instance Read1 IntMap where
liftReadsPrec rp rl = readsData $
readsUnaryWith (liftReadsPrec rp' rl') "fromList" fromList
where
rp' = liftReadsPrec rp rl
rl' = liftReadList rp rl
{--------------------------------------------------------------------
Typeable
--------------------------------------------------------------------}
deriving instance Typeable IntMap
{--------------------------------------------------------------------
Helpers
--------------------------------------------------------------------}
{--------------------------------------------------------------------
Link
--------------------------------------------------------------------}
link :: Prefix -> IntMap a -> Prefix -> IntMap a -> IntMap a
link p1 t1 p2 t2
| zero p1 m = Bin p m t1 t2
| otherwise = Bin p m t2 t1
where
m = branchMask p1 p2
p = mask p1 m
{-# INLINE link #-}
{--------------------------------------------------------------------
@bin@ assures that we never have empty trees within a tree.
--------------------------------------------------------------------}
bin :: Prefix -> Mask -> IntMap a -> IntMap a -> IntMap a
bin _ _ l Nil = l
bin _ _ Nil r = r
bin p m l r = Bin p m l r
{-# INLINE bin #-}
-- binCheckLeft only checks that the left subtree is non-empty
binCheckLeft :: Prefix -> Mask -> IntMap a -> IntMap a -> IntMap a
binCheckLeft _ _ Nil r = r
binCheckLeft p m l r = Bin p m l r
{-# INLINE binCheckLeft #-}
-- binCheckRight only checks that the right subtree is non-empty
binCheckRight :: Prefix -> Mask -> IntMap a -> IntMap a -> IntMap a
binCheckRight _ _ l Nil = l
binCheckRight p m l r = Bin p m l r
{-# INLINE binCheckRight #-}
{--------------------------------------------------------------------
Endian independent bit twiddling
--------------------------------------------------------------------}
-- | Should this key follow the left subtree of a 'Bin' with switching
-- bit @m@? N.B., the answer is only valid when @match i p m@ is true.
zero :: Key -> Mask -> Bool
zero i m
= (natFromInt i) .&. (natFromInt m) == 0
{-# INLINE zero #-}
nomatch,match :: Key -> Prefix -> Mask -> Bool
-- | Does the key @i@ differ from the prefix @p@ before getting to
-- the switching bit @m@?
nomatch i p m
= (mask i m) /= p
{-# INLINE nomatch #-}
-- | Does the key @i@ match the prefix @p@ (up to but not including
-- bit @m@)?
match i p m
= (mask i m) == p
{-# INLINE match #-}
-- | The prefix of key @i@ up to (but not including) the switching
-- bit @m@.
mask :: Key -> Mask -> Prefix
mask i m
= maskW (natFromInt i) (natFromInt m)
{-# INLINE mask #-}
{--------------------------------------------------------------------
Big endian operations
--------------------------------------------------------------------}
-- | The prefix of key @i@ up to (but not including) the switching
-- bit @m@.
maskW :: Nat -> Nat -> Prefix
maskW i m
= intFromNat (i .&. (complement (m-1) `xor` m))
{-# INLINE maskW #-}
-- | Does the left switching bit specify a shorter prefix?
shorter :: Mask -> Mask -> Bool
shorter m1 m2
= (natFromInt m1) > (natFromInt m2)
{-# INLINE shorter #-}
-- | The first switching bit where the two prefixes disagree.
branchMask :: Prefix -> Prefix -> Mask
branchMask p1 p2
= intFromNat (highestBitMask (natFromInt p1 `xor` natFromInt p2))
{-# INLINE branchMask #-}
{--------------------------------------------------------------------
Utilities
--------------------------------------------------------------------}
-- | /O(1)/. Decompose a map into pieces based on the structure
-- of the underlying tree. This function is useful for consuming a
-- map in parallel.
--
-- No guarantee is made as to the sizes of the pieces; an internal, but
-- deterministic process determines this. However, it is guaranteed that the
-- pieces returned will be in ascending order (all elements in the first submap
-- less than all elements in the second, and so on).
--
-- Examples:
--
-- > splitRoot (fromList (zip [1..6::Int] ['a'..])) ==
-- > [fromList [(1,'a'),(2,'b'),(3,'c')],fromList [(4,'d'),(5,'e'),(6,'f')]]
--
-- > splitRoot empty == []
--
-- Note that the current implementation does not return more than two submaps,
-- but you should not depend on this behaviour because it can change in the
-- future without notice.
splitRoot :: IntMap a -> [IntMap a]
splitRoot orig =
case orig of
Nil -> []
x@(Tip _ _) -> [x]
Bin _ m l r | m < 0 -> [r, l]
| otherwise -> [l, r]
{-# INLINE splitRoot #-}
{--------------------------------------------------------------------
Debugging
--------------------------------------------------------------------}
-- | /O(n)/. Show the tree that implements the map. The tree is shown
-- in a compressed, hanging format.
showTree :: Show a => IntMap a -> String
showTree s
= showTreeWith True False s
{- | /O(n)/. The expression (@'showTreeWith' hang wide map@) shows
the tree that implements the map. If @hang@ is
'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
@wide@ is 'True', an extra wide version is shown.
-}
showTreeWith :: Show a => Bool -> Bool -> IntMap a -> String
showTreeWith hang wide t
| hang = (showsTreeHang wide [] t) ""
| otherwise = (showsTree wide [] [] t) ""
showsTree :: Show a => Bool -> [String] -> [String] -> IntMap a -> ShowS
showsTree wide lbars rbars t = case t of
Bin p m l r ->
showsTree wide (withBar rbars) (withEmpty rbars) r .
showWide wide rbars .
showsBars lbars . showString (showBin p m) . showString "\n" .
showWide wide lbars .
showsTree wide (withEmpty lbars) (withBar lbars) l
Tip k x ->
showsBars lbars .
showString " " . shows k . showString ":=" . shows x . showString "\n"
Nil -> showsBars lbars . showString "|\n"
showsTreeHang :: Show a => Bool -> [String] -> IntMap a -> ShowS
showsTreeHang wide bars t = case t of
Bin p m l r ->
showsBars bars . showString (showBin p m) . showString "\n" .
showWide wide bars .
showsTreeHang wide (withBar bars) l .
showWide wide bars .
showsTreeHang wide (withEmpty bars) r
Tip k x ->
showsBars bars .
showString " " . shows k . showString ":=" . shows x . showString "\n"
Nil -> showsBars bars . showString "|\n"
showBin :: Prefix -> Mask -> String
showBin _ _
= "*" -- ++ show (p,m)
showWide :: Bool -> [String] -> String -> String
showWide wide bars
| wide = showString (concat (reverse bars)) . showString "|\n"
| otherwise = id
showsBars :: [String] -> ShowS
showsBars bars
= case bars of
[] -> id
_ -> showString (concat (reverse (tail bars))) . showString node
node :: String
node = "+--"
withBar, withEmpty :: [String] -> [String]
withBar bars = "| ":bars
withEmpty bars = " ":bars
| phischu/fragnix | tests/packages/scotty/Data.IntMap.Internal.hs | bsd-3-clause | 114,732 | 0 | 21 | 29,173 | 27,075 | 14,011 | 13,064 | 1,603 | 14 |
{-# OPTIONS_JHC -fffi -funboxed-values #-}
module Data.Typeable(TypeRep(),Typeable(..),Typeable1(..),Typeable2(..)) where
import Jhc.Prim
import Jhc.String
type String_ = BitsPtr_
data TypeRep = TypeRep String_ [TypeRep]
showsAddr__ :: String_ -> [Char] -> [Char]
showsAddr__ a xs = unpackStringFoldr a (:) xs
instance Show TypeRep where
showsPrec _ (TypeRep a []) = showsAddr__ a
showsPrec n (TypeRep a xs) = showParen (n > 9) $ spacesep (showsAddr__ a:map (showsPrec 10) xs) where
spacesep [] = id
spacesep [x] = x
spacesep (x:xs) = x . showChar ' ' . spacesep xs
instance Eq TypeRep where
TypeRep a xs == TypeRep b ys = case c_strcmp (Addr_ a) (Addr_ b) of
0 -> xs == ys
_ -> False
foreign import ccall "strcmp" c_strcmp :: Addr_ -> Addr_ -> Int
{-
foreign import primitive ptypeOf :: a -> TypeRep
foreign import primitive ptypeOf1 :: t a -> TypeRep
foreign import primitive ptypeOf2 :: t a b -> TypeRep
foreign import primitive ptypeOf3 :: t a b c -> TypeRep
foreign import primitive ptypeOf4 :: t a b c d -> TypeRep
foreign import primitive ptypeOf5 :: t a b c d e -> TypeRep
foreign import primitive ptypeOf6 :: t a b c d e f -> TypeRep
foreign import primitive ptypeOf7 :: t a b c d e f g -> TypeRep
foreign import primitive typeRepEq :: TypeRep -> TypeRep -> Bool
-}
class Typeable a where
typeOf :: a -> TypeRep
class Typeable1 f where
typeOf1 :: f a -> TypeRep
class Typeable2 f where
typeOf2 :: f a b -> TypeRep
instance Typeable1 [] where
typeOf1 _ = TypeRep "[]"# []
instance Typeable a => Typeable [a] where
typeOf x = typeOfDefault x
{-
instance (Typeable a,Typeable b) => Typeable (a -> b) where
typeOf x = (typeOf2 x `mkAppTy` arg1 x) `mkAppTy` arg2 x where
arg1 :: (x -> y) -> x
arg2 :: (x -> y) -> y
arg1 = undefined
arg2 = undefined
instance (Typeable a) => Typeable1 ((->) a) where
typeOf1 x = typeOf1Default x
instance Typeable2 (->) where
typeOf2 _ = TypeRep "->"# []
-}
instance Typeable2 (,) where
typeOf2 _ = TypeRep "(,)"# []
instance Typeable a => Typeable1 ((,) a) where
typeOf1 x = typeOf1Default x
instance (Typeable b,Typeable a) => Typeable (a,b) where
typeOf x = typeOfDefault x
instance Typeable Char where
typeOf _ = TypeRep "Char"# []
instance Typeable () where
typeOf _ = TypeRep "()"# []
instance Typeable Int where
typeOf _ = TypeRep "Int"# []
--instance (Typeable1 f,Typeable a) => Typeable (f a) where
-- typeOf x = typeOf1 x `mkAppTy` typeOf (argType x) where
-- argType :: a b -> b
-- argType = undefined
mkAppTy :: TypeRep -> TypeRep -> TypeRep
mkAppTy (TypeRep x xs) tr = TypeRep x (xs ++ [tr])
-------------------------------------------------------------
--
-- Type-safe cast
--
-------------------------------------------------------------
unsafeCoerce :: a -> b
unsafeCoerce = unsafeCoerce__
-- | The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b
cast x = r where
fromJust (Just x) = x
r = if typeOf x == typeOf (fromJust r)
then Just $ unsafeCoerce x
else Nothing
{-
-- | A flexible variation parameterised in a type constructor
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
gcast x = r
where
r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> *
gcast1 :: (Typeable1 t, Typeable1 t') c (t a) -> Maybe (c (t' a))
gcast1 x = r
where
r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> * -> *
gcast2 :: (Typeable2 t, Typeable2 t') c (t a b) -> Maybe (c (t' a b))
gcast2 x = r
where
r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-}
-- | For defining a 'Typeable' instance from any 'Typeable1' instance.
typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
where
argType :: t a -> a
argType = undefined
-- | For defining a 'Typeable1' instance from any 'Typeable2' instance.
typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
where
argType :: t a b -> a
argType = undefined
| m-alvarez/jhc | lib/haskell-extras/Data/Typeable.hs | mit | 4,497 | 2 | 12 | 1,076 | 929 | 483 | 446 | 62 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances,
UndecidableInstances, FlexibleContexts, EmptyDataDecls, ScopedTypeVariables,
TypeOperators, TypeSynonymInstances, TypeFamilies #-}
--module Main where
import Records
import References
import ReferenceMonad
import Methods
{-
key = firstLabel
name = nextLabel key
type TestType = Integer :* String :* EmptyRecord
test :: TestType
test = key .= 10
.* name .= "Pippo"
.* EmptyRecord
res :: Reference TestType Integer
res = do v <- this <-- key
return (v+1)
res1 :: Reference TestType ()
res1 = do v <- ((this <-- key)::Reference TestType Integer)
(((this <-- key)::Reference TestType Integer) =: (v+1))::Reference TestType ()
return ()
x = getter res test -- x = (11, test)
y = getter res1 test -- y = ((), {test with key = test.key+1})
-}
{-
dichiariamo le labels del nostro record
-}
val = firstLabel
incr = nextLabel val
val' :: (Z,((Counter RecCounter) -> Integer), (Counter RecCounter) -> Integer -> (Counter RecCounter))
val' = firstLabel'
incr' :: (S Z,((Counter RecCounter) -> Method RecCounter () ()), (Counter RecCounter) -> Method RecCounter () () -> (Counter RecCounter))
incr' = nextLabel' val'
{-
dichiariamo due tipi per il nostro record:
serve perché altrimenti con i metodi otteniamo
un tipo infinito
-}
type Counter k = (Integer :* Method k () () :* EmptyRecord)
data RecCounter = RecCounter (Counter RecCounter)
{-
mettiamo in relazione i due tipi che definiscono il
record, in modo che il sistema di oggetti possa
autonomamente convertire istanze ricorsive (di RecCounter)
in istanze "appiattite" (di Counter RecCounter)
-}
instance Recursive (Counter RecCounter) where
{-
le type functions sono una feature molto nuova
di Haskell (ce l'ha mostrate SPJ a Oxford) che
permette di far funzionare i metodi: senza
queste il type checker non é in grado di
risolvere alcuni predicati di tipo perché non
fa SDL-risoluzione (che sarebbe l'unico modo)
-}
type Rec (Counter RecCounter) = RecCounter
cons = RecCounter
elim (RecCounter r) = r
{-
costruiamo un metodo, che ha tipo () -> Reference RecCounter ();
prima costruiamo il metodo originale, che ha tipo
() -> Reference (Counter RecCounter) (), e poi lo convertiamo
con mk_method alla sua forma finale
-}
m :: Method RecCounter () ()
m = mk_method (\() ->
(do v <- ((this <-- val) :: Reference (Counter RecCounter) Integer)
(this <-- val) =: (v+1) :: Reference (Counter RecCounter) ()
return ()))
x |> f = f x
{-
costruiamo il nostro record iniziale
-}
test' :: Counter RecCounter
test' = RecCounter( val .= 0
.* incr .= m
.* EmptyRecord) |> elim
{-
invochiamo due volte il metodo incr e poi
leggiamo il contatore
-}
res2 :: Reference (Counter RecCounter) Integer
res2 = do (this <<- incr) () :: Reference (Counter RecCounter) ()
(this <<- incr) () :: Reference (Counter RecCounter) ()
v <- (this <-- val)
return v
res3 = do v <- (this <== val')
(this <== val') =: (v+1)
v <- (this <== val')
return v
--count é pari a 2: YAY!
count = fst (getter res2 test')
| vs-team/Papers | Before Giuseppe's PhD/Monads/ObjectiveMonad/MonadicObjects/trunk/Src/Main.hs | mit | 3,251 | 0 | 15 | 745 | 606 | 317 | 289 | 39 | 1 |
-- | PDF viewer demo
-- Author : Andy Stewart
-- Copyright : (c) 2010 Andy Stewart <[email protected]>
-- | The PDF viewer base on poppler library.
--
-- Usage:
-- pdfviewer file
--
module Main where
import Control.Applicative
import Control.Concurrent.STM
import Control.Monad
import Data.Maybe
import Graphics.Rendering.Cairo
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.EventM
import Graphics.UI.Gtk.Poppler.Document
import Graphics.UI.Gtk.Poppler.Page
import System.Environment
import System.Process
data Viewer =
Viewer {viewerArea :: DrawingArea
,viewerDocument :: Document
,viewerScrolledWindow:: ScrolledWindow
,viewerPage :: TVar Int}
-- | Main entry.
main :: IO ()
main = do
-- Get program arguments.
args <- getArgs
case args of
-- Display help
["--help"] ->
putStrLn $ "PDF viewer demo. \n\n" ++
"Usage: pdfviewer file\n\n"
-- Start program.
[arg] -> viewerMain arg
_ -> putStrLn "Usage: pdfviewer file"
-- | Internal browser fucntion.
viewerMain :: FilePath -> IO ()
viewerMain file = do
-- Init.
initGUI
-- Create window.
window <- windowNew
windowSetDefaultSize window 600 780
windowSetPosition window WinPosCenter
-- Create window box.
windowBox <- vBoxNew False 0
window `containerAdd` windowBox
-- Create viewer.
viewer <- viewerNew file
let area = viewerArea viewer
doc = viewerDocument viewer
sWin = viewerScrolledWindow viewer
-- Set title.
title <- get doc documentTitle
windowSetTitle window ("PdfViewer " ++ title)
-- Create spin button to select page.
pages <- documentGetNPages doc -- get maximum page
spinButton <- spinButtonNewWithRange 0 (integralToDouble pages) 1.0
-- Redraw viewer after change value of spin button.
afterValueSpinned spinButton $ do
page <- spinButtonGetValue spinButton
writeTVarIO (viewerPage viewer) (truncate page)
widgetQueueDraw area
-- Show.
boxPackStart windowBox sWin PackGrow 0
boxPackStart windowBox spinButton PackNatural 0
window `onDestroy` mainQuit
widgetShowAll window
mainGUI
viewerNew :: FilePath -> IO Viewer
viewerNew file = do
area <- drawingAreaNew
doc <- liftM (fromMaybe (error "Error when open pdf file.")) (documentNewFromFile ("file://" ++ file) Nothing)
sWin <- scrolledWindowNew Nothing Nothing
page <- newTVarIO 0
let viewer = Viewer area doc sWin page
scrolledWindowAddWithViewport sWin area
scrolledWindowSetPolicy sWin PolicyAutomatic PolicyAutomatic
area `on` exposeEvent $ tryEvent $ viewerDraw viewer
return viewer
viewerDraw :: Viewer -> EventM EExpose ()
viewerDraw viewer = do
let doc = viewerDocument viewer
area = viewerArea viewer
(winWidth, winHeight) <- eventWindowSize
liftIO $ do
pageNumber <- readTVarIO $ viewerPage viewer
page <- documentGetPage doc pageNumber
frameWin <- widgetGetDrawWindow area
(docWidth, docHeight) <- pageGetSize page
let scaleX = winWidth / docWidth
width = winWidth
height = scaleX * docHeight
widgetSetSizeRequest area (truncate width) (truncate height)
renderWithDrawable frameWin $ do
setSourceRGB 1.0 1.0 1.0
scale scaleX scaleX
pageRender page
eventWindowSize :: EventM EExpose (Double, Double)
eventWindowSize = do
dr <- eventWindow
(w,h) <- liftIO $ drawableGetSize dr
return $ if w * h > 1
then (fromIntegral w, fromIntegral h)
else (1,1)
-- | Transform Int to Doube
integralToDouble :: Integral a => a -> Double
integralToDouble v = fromIntegral v :: Double
-- | The IO version of `writeTVar`.
writeTVarIO :: TVar a -> a -> IO ()
writeTVarIO a b = atomically $ writeTVar a b
| wavewave/poppler | demo/PdfViewer.hs | lgpl-2.1 | 3,804 | 0 | 13 | 871 | 960 | 478 | 482 | 91 | 3 |
{-# LANGUAGE ScopedTypeVariables #-}
import StackTest
import System.Directory
import Control.Exception (catch, IOException)
main :: IO ()
main = do
removeFileIgnore "stack.yaml"
createDirectory "unreachabledir" `catch` \(e :: IOException) -> pure ()
setPermissions "unreachabledir" emptyPermissions
stack ["init"]
| juhp/stack | test/integration/tests/skip-unreachable-dirs/Main.hs | bsd-3-clause | 332 | 0 | 10 | 53 | 90 | 46 | 44 | 10 | 1 |
module E5 where
data BTree a
= Empty | T a (BTree a) (BTree a) deriving Show
buildtree :: Ord a => [a] -> BTree a
buildtree [] = Empty
buildtree ((x : xs)) = head (insert x (buildtree xs))
insert :: Ord a => a -> (BTree a) -> [BTree a]
insert val v2
= do case v2 of
T val Empty Empty
| val == val -> [Empty]
| otherwise -> [(T val Empty Empty), Empty]
T val (T val2 Empty Empty) Empty -> [Empty]
_ -> [v2]
main :: IO ()
main
= do let f = [(T a_1 Empty Empty) | n@(T a_1
Empty Empty) <- insert 42
(buildtree
[1,
2,
3])]
if True
then do putStrLn $ (show 42)
else do putStrLn $ (show 42)
| kmate/HaRe | old/testing/unfoldAsPatterns/E5AST.hs | bsd-3-clause | 1,090 | 0 | 16 | 635 | 353 | 181 | 172 | 25 | 3 |
module DuplicateModuleName (Window(..)) where
data Window = Window deriving (Show)
| ezyang/ghc | testsuite/tests/typecheck/T13168/package1/DuplicateModuleName.hs | bsd-3-clause | 84 | 0 | 6 | 11 | 27 | 17 | 10 | 2 | 0 |
{-# LANGUAGE TypeFamilies, ConstraintKinds, UndecidableInstances, UndecidableSuperClasses #-}
module Ctx where
import Data.Kind ( Constraint )
type family Indirect :: * -> Constraint
type instance Indirect = Show
class Indirect a => Cls a where
foo :: Cls a => a -> String
foo = show
| ezyang/ghc | testsuite/tests/typecheck/should_compile/tc256.hs | bsd-3-clause | 288 | 0 | 6 | 49 | 72 | 40 | 32 | -1 | -1 |
module T4114dSub (assertKeep, assertNoKeep) where
import Control.Monad (unless, when)
import System.Directory (doesFileExist)
assertNoKeep :: FilePath -> IO ()
assertNoKeep a =
whenM (doesFileExist a) $
error ("error: intermediate '" ++ a ++ "' exists")
assertKeep :: FilePath -> IO ()
assertKeep a =
unlessM (doesFileExist a) $
error ("error: intermediate '" ++ a ++ "' is missing")
whenM :: Monad m => m Bool -> m () -> m ()
whenM mp f = mp >>= \p -> when p f
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM mp f = mp >>= \p -> unless p f
| ezyang/ghc | testsuite/tests/driver/T4114dSub.hs | bsd-3-clause | 574 | 0 | 9 | 133 | 247 | 124 | 123 | 15 | 1 |
module Player where
import GameEngine
playerX :: Player
playerX = Player 'X'
playerO :: Player
playerO = Player 'O'
-- workaround since the Player data type is not an instance of eq
isPlayer :: Player -> Player -> Bool
isPlayer (Player a) (Player b) = a == b
isPlayerSymbol :: Player -> Symbol -> Bool
isPlayerSymbol (Player x) = (==) x
isPlayerXSymbol :: Symbol -> Bool
isPlayerXSymbol = isPlayerSymbol playerX
isPlayerOSymbol :: Symbol -> Bool
isPlayerOSymbol = isPlayerSymbol playerO
| TGOlson/haskell-tic-tac-toe | Src/Player.hs | mit | 500 | 0 | 7 | 92 | 139 | 75 | 64 | 14 | 1 |
-- Recursiveness
-- Gets the biggest value in a list
-- This version uses guards
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "no max for empty lists"
maximum' [x] = x
maximum' (x:y)
| x > maxTail = x
| otherwise = x
where maxTail = maximum' y
-- We can improve this by using `max`
shortMax :: (Ord a) => [a] -> a
shortMax [] = error "no max for empty lists"
shortMax [x] = x
shortMax (x:y) = max x (shortMax y)
-- Replicate
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x:replicate' (n - 1) x
-- This one fallsthrough when n is not <= 0
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _
| n <= 0 = []
take' _ [] = []
take' n (x:xs) = x : take' (n - 1) xs
-- Reverses a list
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
-- Repeat
-- Repeats an element infinitely
-- If we do something like: take 5 (repeat 3) we can finish evaluating
-- However, if we just do repeat 3 we keep going ad infinitum
repeat' :: a -> [a]
repeat' x = x : repeat' x
-- Zip
-- This one has two edge conditions
zip' :: [a] -> [b] -> [(a, b)]
zip' [] _ = []
zip' _ [] = []
zip' (x:xs) (y:ys) = [(x, y)] ++ (zip' xs ys)
-- Elem
-- Finds an element in the list
elem' :: (Eq a) => a -> [a] -> Bool
elem' _ [] = False
elem' a (x:xs)
| a == x = True
| otherwise = elem' a xs
-- Quicksort
-- OH MY GOD THIS IS SO ELEGANT
-- I WANNA THROW A PARTY FOR THIS ALGORITHM
-- OH GOD HASKELL WHY U SO GOOD
-- PLS TELL ME, I CAN'T TAKE IT
quickSort :: (Ord a) => [a] -> [a]
quickSort [] = []
quickSort (x:xs) =
let smallerSorted = quickSort [ a | a <- xs, a <= x ]
biggerSorted = quickSort [ a | a <- xs, a > x ]
in smallerSorted ++ [x] ++ biggerSorted
| lucasfcosta/haskell-experiences | Chapter 5/recursiveness.hs | mit | 1,737 | 0 | 12 | 434 | 742 | 395 | 347 | 40 | 1 |
module LC where
import Data.List (sort)
kthLargest :: Int -> [Int] -> Int
kthLargest k = last . take k . sort
| AriaFallah/leetcode | haskell/KthLargest.hs | mit | 112 | 0 | 7 | 24 | 49 | 27 | 22 | 4 | 1 |
{-|
Module : PostgREST.DbStructure
Description : PostgREST schema cache
This module contains queries that target PostgreSQL system catalogs, these are used to build the schema cache(DbStructure).
The schema cache is necessary for resource embedding, foreign keys are used for inferring the relationships between tables.
These queries are executed once at startup or when PostgREST is reloaded.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE NamedFieldPuns #-}
module PostgREST.DbStructure (
getDbStructure
, accessibleTables
, accessibleProcs
, schemaDescription
, getPgVersion
) where
import qualified Hasql.Decoders as HD
import qualified Hasql.Encoders as HE
import qualified Hasql.Statement as H
import Control.Applicative
import qualified Data.HashMap.Strict as M
import qualified Data.List as L
import Data.Set as S (fromList)
import Data.Text (split, strip,
breakOn, dropAround,
splitOn)
import qualified Data.Text as T
import qualified Hasql.Session as H
import qualified Hasql.Transaction as HT
import PostgREST.Types
import Text.InterpolatedString.Perl6 (q, qc)
import GHC.Exts (groupWith)
import Protolude
import Unsafe (unsafeHead)
getDbStructure :: Schema -> PgVersion -> HT.Transaction DbStructure
getDbStructure schema pgVer = do
HT.sql "set local schema ''" -- for getting the fully qualified name(schema.name) of every db object
tabs <- HT.statement () allTables
cols <- HT.statement schema $ allColumns tabs
syns <- HT.statement schema $ allSynonyms cols pgVer
childRels <- HT.statement () $ allChildRelations tabs cols
keys <- HT.statement () $ allPrimaryKeys tabs
procs <- HT.statement schema allProcs
let rels = addManyToManyRelations . addParentRelations $ addViewChildRelations syns childRels
cols' = addForeignKeys rels cols
keys' = addViewPrimaryKeys syns keys
return DbStructure {
dbTables = tabs
, dbColumns = cols'
, dbRelations = rels
, dbPrimaryKeys = keys'
, dbProcs = procs
, pgVersion = pgVer
}
decodeTables :: HD.Result [Table]
decodeTables =
HD.rowList tblRow
where
tblRow = Table <$> HD.column HD.text
<*> HD.column HD.text
<*> HD.nullableColumn HD.text
<*> HD.column HD.bool
decodeColumns :: [Table] -> HD.Result [Column]
decodeColumns tables =
mapMaybe (columnFromRow tables) <$> HD.rowList colRow
where
colRow =
(,,,,,,,,,,,)
<$> HD.column HD.text <*> HD.column HD.text
<*> HD.column HD.text <*> HD.nullableColumn HD.text
<*> HD.column HD.int4 <*> HD.column HD.bool
<*> HD.column HD.text <*> HD.column HD.bool
<*> HD.nullableColumn HD.int4
<*> HD.nullableColumn HD.int4
<*> HD.nullableColumn HD.text
<*> HD.nullableColumn HD.text
decodeRelations :: [Table] -> [Column] -> HD.Result [Relation]
decodeRelations tables cols =
mapMaybe (relationFromRow tables cols) <$> HD.rowList relRow
where
relRow = (,,,,,)
<$> HD.column HD.text
<*> HD.column HD.text
<*> HD.column (HD.array (HD.dimension replicateM (HD.element HD.text)))
<*> HD.column HD.text
<*> HD.column HD.text
<*> HD.column (HD.array (HD.dimension replicateM (HD.element HD.text)))
decodePks :: [Table] -> HD.Result [PrimaryKey]
decodePks tables =
mapMaybe (pkFromRow tables) <$> HD.rowList pkRow
where
pkRow = (,,) <$> HD.column HD.text <*> HD.column HD.text <*> HD.column HD.text
decodeSynonyms :: [Column] -> HD.Result [Synonym]
decodeSynonyms cols =
mapMaybe (synonymFromRow cols) <$> HD.rowList synRow
where
synRow = (,,,,,)
<$> HD.column HD.text <*> HD.column HD.text
<*> HD.column HD.text <*> HD.column HD.text
<*> HD.column HD.text <*> HD.column HD.text
decodeProcs :: HD.Result (M.HashMap Text [ProcDescription])
decodeProcs =
-- Duplicate rows for a function means they're overloaded, order these by least args according to ProcDescription Ord instance
map sort . M.fromListWith (++) . map ((\(x,y) -> (x, [y])) . addName) <$> HD.rowList tblRow
where
tblRow = ProcDescription
<$> HD.column HD.text
<*> HD.nullableColumn HD.text
<*> (parseArgs <$> HD.column HD.text)
<*> (parseRetType
<$> HD.column HD.text
<*> HD.column HD.text
<*> HD.column HD.bool
<*> HD.column HD.char)
<*> (parseVolatility <$> HD.column HD.char)
addName :: ProcDescription -> (Text, ProcDescription)
addName pd = (pdName pd, pd)
parseArgs :: Text -> [PgArg]
parseArgs = mapMaybe parseArg . filter (not . isPrefixOf "OUT" . toS) . map strip . split (==',')
parseArg :: Text -> Maybe PgArg
parseArg a =
let arg = lastDef "" $ splitOn "INOUT " a
(body, def) = breakOn " DEFAULT " arg
(name, typ) = breakOn " " body in
if T.null typ
then Nothing
else Just $
PgArg (dropAround (== '"') name) (strip typ) (T.null def)
parseRetType :: Text -> Text -> Bool -> Char -> RetType
parseRetType schema name isSetOf typ
| isSetOf = SetOf pgType
| otherwise = Single pgType
where
qi = QualifiedIdentifier schema name
pgType = case typ of
'c' -> Composite qi
'p' -> if name == "record" -- Only pg pseudo type that is a row type is 'record'
then Composite qi
else Scalar qi
_ -> Scalar qi -- 'b'ase, 'd'omain, 'e'num, 'r'ange
parseVolatility :: Char -> ProcVolatility
parseVolatility v | v == 'i' = Immutable
| v == 's' = Stable
| otherwise = Volatile -- only 'v' can happen here
allProcs :: H.Statement Schema (M.HashMap Text [ProcDescription])
allProcs = H.Statement (toS procsSqlQuery) (HE.param HE.text) decodeProcs True
accessibleProcs :: H.Statement Schema (M.HashMap Text [ProcDescription])
accessibleProcs = H.Statement (toS sql) (HE.param HE.text) decodeProcs True
where
sql = procsSqlQuery <> " AND has_function_privilege(p.oid, 'execute')"
procsSqlQuery :: SqlQuery
procsSqlQuery = [q|
SELECT p.proname as "proc_name",
d.description as "proc_description",
pg_get_function_arguments(p.oid) as "args",
tn.nspname as "rettype_schema",
coalesce(comp.relname, t.typname) as "rettype_name",
p.proretset as "rettype_is_setof",
t.typtype as "rettype_typ",
p.provolatile
FROM pg_proc p
JOIN pg_namespace pn ON pn.oid = p.pronamespace
JOIN pg_type t ON t.oid = p.prorettype
JOIN pg_namespace tn ON tn.oid = t.typnamespace
LEFT JOIN pg_class comp ON comp.oid = t.typrelid
LEFT JOIN pg_catalog.pg_description as d on d.objoid = p.oid
WHERE pn.nspname = $1
|]
schemaDescription :: H.Statement Schema (Maybe Text)
schemaDescription =
H.Statement sql (HE.param HE.text) (join <$> HD.rowMaybe (HD.nullableColumn HD.text)) True
where
sql = [q|
select
description
from
pg_catalog.pg_namespace n
left join pg_catalog.pg_description d on d.objoid = n.oid
where
n.nspname = $1 |]
accessibleTables :: H.Statement Schema [Table]
accessibleTables =
H.Statement sql (HE.param HE.text) decodeTables True
where
sql = [q|
select
n.nspname as table_schema,
relname as table_name,
d.description as table_description,
c.relkind = 'r' or (c.relkind IN ('v', 'f')) and (pg_relation_is_updatable(c.oid::regclass, false) & 8) = 8
or (exists (
select 1
from pg_trigger
where pg_trigger.tgrelid = c.oid and (pg_trigger.tgtype::integer & 69) = 69)
) as insertable
from
pg_class c
join pg_namespace n on n.oid = c.relnamespace
left join pg_catalog.pg_description as d on d.objoid = c.oid and d.objsubid = 0
where
c.relkind in ('v', 'r', 'm', 'f')
and n.nspname = $1
and (
pg_has_role(c.relowner, 'USAGE'::text)
or has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text)
or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'::text)
)
order by relname |]
addForeignKeys :: [Relation] -> [Column] -> [Column]
addForeignKeys rels = map addFk
where
addFk col = col { colFK = fk col }
fk col = join $ relToFk col <$> find (lookupFn col) rels
lookupFn :: Column -> Relation -> Bool
lookupFn c Relation{relColumns=cs, relType=rty} = c `elem` cs && rty==Child
relToFk col Relation{relColumns=cols, relFColumns=colsF} = do
pos <- L.elemIndex col cols
colF <- atMay colsF pos
return $ ForeignKey colF
{-
Adds Views Child Relations based on Synonyms found, the logic is as follows:
Having a Relation{relTable=t1, relColumns=[c1], relFTable=t2, relFColumns=[c2], relType=Child} represented by:
t1.c1------t2.c2
When only having a t1_view.c1 synonym, we need to add a View to Table Child Relation
t1.c1----t2.c2 t1.c1----------t2.c2
-> ________/
/
t1_view.c1 t1_view.c1
When only having a t2_view.c2 synonym, we need to add a Table to View Child Relation
t1.c1----t2.c2 t1.c1----------t2.c2
-> \________
\
t2_view.c2 t2_view.c1
When having t1_view.c1 and a t2_view.c2 synonyms, we need to add a View to View Child Relation in addition to the prior
t1.c1----t2.c2 t1.c1----------t2.c2
-> \________/
/ \
t1_view.c1 t2_view.c2 t1_view.c1-------t2_view.c1
The logic for composite pks is similar just need to make sure all the Relation columns have synonyms.
-}
addViewChildRelations :: [Synonym] -> [Relation] -> [Relation]
addViewChildRelations allSyns = concatMap (\rel ->
rel : case rel of
Relation{relType=Child, relTable, relColumns, relFTable, relFColumns} ->
let colSynsGroupedByView :: [Column] -> [[Synonym]]
colSynsGroupedByView relCols = L.groupBy (\(_, viewCol1) (_, viewCol2) -> colTable viewCol1 == colTable viewCol2) $
filter (\(c, _) -> c `elem` relCols) allSyns
colsSyns = colSynsGroupedByView relColumns
fColsSyns = colSynsGroupedByView relFColumns
getView :: [Synonym] -> Table
getView = colTable . snd . unsafeHead
syns `allSynsOf` cols = S.fromList (fst <$> syns) == S.fromList cols
-- Relation is dependent on the order of relColumns and relFColumns to get the join conditions right in the generated query.
-- So we need to change the order of the synonyms to match the relColumns
-- This could be avoided if the Relation type is improved with a structure that maintains the association of relColumns and relFColumns
syns `sortAccordingTo` columns = sortOn (\(k, _) -> L.lookup k $ zip columns [0::Int ..]) syns in
-- View Table Child Relations
[Relation (getView syns) (snd <$> syns `sortAccordingTo` relColumns) relFTable relFColumns Child Nothing Nothing Nothing
| syns <- colsSyns, syns `allSynsOf` relColumns] ++
-- Table View Child Relations
[Relation relTable relColumns (getView fSyns) (snd <$> fSyns `sortAccordingTo` relFColumns) Child Nothing Nothing Nothing
| fSyns <- fColsSyns, fSyns `allSynsOf` relFColumns] ++
-- View View Child Relations
[Relation (getView syns) (snd <$> syns `sortAccordingTo` relColumns) (getView fSyns) (snd <$> fSyns `sortAccordingTo` relFColumns) Child Nothing Nothing Nothing
| syns <- colsSyns, fSyns <- fColsSyns, syns `allSynsOf` relColumns, fSyns `allSynsOf` relFColumns]
_ -> [])
addParentRelations :: [Relation] -> [Relation]
addParentRelations = concatMap (\rel@(Relation t c ft fc _ _ _ _) -> [rel, Relation ft fc t c Parent Nothing Nothing Nothing])
addManyToManyRelations :: [Relation] -> [Relation]
addManyToManyRelations rels = rels ++ addMirrorRelation (mapMaybe link2Relation links)
where
links = join $ map (combinations 2) $ filter (not . null) $ groupWith groupFn $ filter ( (==Child). relType) rels
groupFn :: Relation -> Text
groupFn Relation{relTable=Table{tableSchema=s, tableName=t}} = s <> "_" <> t
-- Reference : https://wiki.haskell.org/99_questions/Solutions/26
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [ [] ]
combinations n xs = [ y:ys | y:xs' <- tails xs
, ys <- combinations (n-1) xs']
addMirrorRelation = concatMap (\rel@(Relation t c ft fc _ lt lc1 lc2) -> [rel, Relation ft fc t c Many lt lc2 lc1])
link2Relation [
Relation{relTable=lt, relColumns=lc1, relFTable=t, relFColumns=c},
Relation{ relColumns=lc2, relFTable=ft, relFColumns=fc}
]
| lc1 /= lc2 && length lc1 == 1 && length lc2 == 1 = Just $ Relation t c ft fc Many (Just lt) (Just lc1) (Just lc2)
| otherwise = Nothing
link2Relation _ = Nothing
addViewPrimaryKeys :: [Synonym] -> [PrimaryKey] -> [PrimaryKey]
addViewPrimaryKeys syns = concatMap (\pk ->
let viewPks = (\(_, viewCol) -> PrimaryKey{pkTable=colTable viewCol, pkName=colName viewCol}) <$>
filter (\(col, _) -> colTable col == pkTable pk && colName col == pkName pk) syns in
pk : viewPks)
allTables :: H.Statement () [Table]
allTables =
H.Statement sql HE.unit decodeTables True
where
sql = [q|
SELECT
n.nspname AS table_schema,
c.relname AS table_name,
NULL AS table_description,
c.relkind = 'r' OR (c.relkind IN ('v','f'))
AND (pg_relation_is_updatable(c.oid::regclass, FALSE) & 8) = 8
OR (EXISTS
( SELECT 1
FROM pg_trigger
WHERE pg_trigger.tgrelid = c.oid
AND (pg_trigger.tgtype::integer & 69) = 69) ) AS insertable
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('v','r','m','f')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
GROUP BY table_schema, table_name, insertable
ORDER BY table_schema, table_name |]
allColumns :: [Table] -> H.Statement Schema [Column]
allColumns tabs =
H.Statement sql (HE.param HE.text) (decodeColumns tabs) True
where
sql = [q|
SELECT DISTINCT
info.table_schema AS schema,
info.table_name AS table_name,
info.column_name AS name,
info.description AS description,
info.ordinal_position AS position,
info.is_nullable::boolean AS nullable,
info.data_type AS col_type,
info.is_updatable::boolean AS updatable,
info.character_maximum_length AS max_len,
info.numeric_precision AS precision,
info.column_default AS default_value,
array_to_string(enum_info.vals, ',') AS enum
FROM (
/*
-- CTE based on pg_catalog to get only Primary and Foreign key columns outside api schema
*/
WITH key_columns AS (
SELECT
r.oid AS r_oid,
c.oid AS c_oid,
n.nspname,
c.relname,
r.conname,
r.contype,
unnest(r.conkey) AS conkey
FROM
pg_catalog.pg_constraint r,
pg_catalog.pg_class c,
pg_catalog.pg_namespace n
WHERE
r.contype IN ('f', 'p')
AND c.relkind IN ('r', 'v', 'f', 'm')
AND r.conrelid = c.oid
AND c.relnamespace = n.oid
AND n.nspname NOT IN ('pg_catalog', 'information_schema', $1)
),
/*
-- CTE based on information_schema.columns
-- changed:
-- remove the owner filter
-- limit columns to the ones in the api schema or PK/FK columns
*/
columns AS (
SELECT current_database()::information_schema.sql_identifier AS table_catalog,
nc.nspname::information_schema.sql_identifier AS table_schema,
c.relname::information_schema.sql_identifier AS table_name,
a.attname::information_schema.sql_identifier AS column_name,
d.description::information_schema.sql_identifier AS description,
a.attnum::information_schema.cardinal_number AS ordinal_position,
pg_get_expr(ad.adbin, ad.adrelid)::information_schema.character_data AS column_default,
CASE
WHEN a.attnotnull OR t.typtype = 'd'::"char" AND t.typnotnull THEN 'NO'::text
ELSE 'YES'::text
END::information_schema.yes_or_no AS is_nullable,
CASE
WHEN t.typtype = 'd'::"char" THEN
CASE
WHEN bt.typelem <> 0::oid AND bt.typlen = (-1) THEN 'ARRAY'::text
WHEN nbt.nspname = 'pg_catalog'::name THEN format_type(t.typbasetype, NULL::integer)
ELSE format_type(a.atttypid, a.atttypmod)
END
ELSE
CASE
WHEN t.typelem <> 0::oid AND t.typlen = (-1) THEN 'ARRAY'::text
WHEN nt.nspname = 'pg_catalog'::name THEN format_type(a.atttypid, NULL::integer)
ELSE format_type(a.atttypid, a.atttypmod)
END
END::information_schema.character_data AS data_type,
information_schema._pg_char_max_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_maximum_length,
information_schema._pg_char_octet_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_octet_length,
information_schema._pg_numeric_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision,
information_schema._pg_numeric_precision_radix(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision_radix,
information_schema._pg_numeric_scale(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_scale,
information_schema._pg_datetime_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS datetime_precision,
information_schema._pg_interval_type(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.character_data AS interval_type,
NULL::integer::information_schema.cardinal_number AS interval_precision,
NULL::character varying::information_schema.sql_identifier AS character_set_catalog,
NULL::character varying::information_schema.sql_identifier AS character_set_schema,
NULL::character varying::information_schema.sql_identifier AS character_set_name,
CASE
WHEN nco.nspname IS NOT NULL THEN current_database()
ELSE NULL::name
END::information_schema.sql_identifier AS collation_catalog,
nco.nspname::information_schema.sql_identifier AS collation_schema,
co.collname::information_schema.sql_identifier AS collation_name,
CASE
WHEN t.typtype = 'd'::"char" THEN current_database()
ELSE NULL::name
END::information_schema.sql_identifier AS domain_catalog,
CASE
WHEN t.typtype = 'd'::"char" THEN nt.nspname
ELSE NULL::name
END::information_schema.sql_identifier AS domain_schema,
CASE
WHEN t.typtype = 'd'::"char" THEN t.typname
ELSE NULL::name
END::information_schema.sql_identifier AS domain_name,
current_database()::information_schema.sql_identifier AS udt_catalog,
COALESCE(nbt.nspname, nt.nspname)::information_schema.sql_identifier AS udt_schema,
COALESCE(bt.typname, t.typname)::information_schema.sql_identifier AS udt_name,
NULL::character varying::information_schema.sql_identifier AS scope_catalog,
NULL::character varying::information_schema.sql_identifier AS scope_schema,
NULL::character varying::information_schema.sql_identifier AS scope_name,
NULL::integer::information_schema.cardinal_number AS maximum_cardinality,
a.attnum::information_schema.sql_identifier AS dtd_identifier,
'NO'::character varying::information_schema.yes_or_no AS is_self_referencing,
'NO'::character varying::information_schema.yes_or_no AS is_identity,
NULL::character varying::information_schema.character_data AS identity_generation,
NULL::character varying::information_schema.character_data AS identity_start,
NULL::character varying::information_schema.character_data AS identity_increment,
NULL::character varying::information_schema.character_data AS identity_maximum,
NULL::character varying::information_schema.character_data AS identity_minimum,
NULL::character varying::information_schema.yes_or_no AS identity_cycle,
'NEVER'::character varying::information_schema.character_data AS is_generated,
NULL::character varying::information_schema.character_data AS generation_expression,
CASE
WHEN c.relkind = 'r'::"char" OR (c.relkind = ANY (ARRAY['v'::"char", 'f'::"char"])) AND pg_column_is_updatable(c.oid::regclass, a.attnum, false) THEN 'YES'::text
ELSE 'NO'::text
END::information_schema.yes_or_no AS is_updatable
FROM pg_attribute a
LEFT JOIN key_columns kc ON kc.conkey = a.attnum AND kc.c_oid = a.attrelid
LEFT JOIN pg_catalog.pg_description AS d ON d.objoid = a.attrelid and d.objsubid = a.attnum
LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
JOIN (pg_class c
JOIN pg_namespace nc ON c.relnamespace = nc.oid) ON a.attrelid = c.oid
JOIN (pg_type t
JOIN pg_namespace nt ON t.typnamespace = nt.oid) ON a.atttypid = t.oid
LEFT JOIN (pg_type bt
JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid) ON t.typtype = 'd'::"char" AND t.typbasetype = bt.oid
LEFT JOIN (pg_collation co
JOIN pg_namespace nco ON co.collnamespace = nco.oid) ON a.attcollation = co.oid AND (nco.nspname <> 'pg_catalog'::name OR co.collname <> 'default'::name)
WHERE
NOT pg_is_other_temp_schema(nc.oid)
AND a.attnum > 0
AND NOT a.attisdropped
AND (c.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char", 'm'::"char"]))
AND (nc.nspname = $1 OR kc.r_oid IS NOT NULL) /*--filter only columns that are FK/PK or in the api schema */
/*--AND (pg_has_role(c.relowner, 'USAGE'::text) OR has_column_privilege(c.oid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/
)
SELECT
table_schema,
table_name,
column_name,
description,
ordinal_position,
is_nullable,
data_type,
is_updatable,
character_maximum_length,
numeric_precision,
column_default,
udt_name
/*-- FROM information_schema.columns*/
FROM columns
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
) AS info
LEFT OUTER JOIN (
SELECT
n.nspname AS s,
t.typname AS n,
array_agg(e.enumlabel ORDER BY e.enumsortorder) AS vals
FROM pg_type t
JOIN pg_enum e ON t.oid = e.enumtypid
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
GROUP BY s,n
) AS enum_info ON (info.udt_name = enum_info.n)
ORDER BY schema, position |]
columnFromRow :: [Table] ->
(Text, Text, Text,
Maybe Text, Int32, Bool,
Text, Bool, Maybe Int32,
Maybe Int32, Maybe Text, Maybe Text)
-> Maybe Column
columnFromRow tabs (s, t, n, desc, pos, nul, typ, u, l, p, d, e) = buildColumn <$> table
where
buildColumn tbl = Column tbl n desc pos nul typ u l p d (parseEnum e) Nothing
table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs
parseEnum :: Maybe Text -> [Text]
parseEnum = maybe [] (split (==','))
allChildRelations :: [Table] -> [Column] -> H.Statement () [Relation]
allChildRelations tabs cols =
H.Statement sql HE.unit (decodeRelations tabs cols) True
where
sql = [q|
SELECT ns1.nspname AS table_schema,
tab.relname AS table_name,
column_info.cols AS columns,
ns2.nspname AS foreign_table_schema,
other.relname AS foreign_table_name,
column_info.refs AS foreign_columns
FROM pg_constraint,
LATERAL (SELECT array_agg(cols.attname) AS cols,
array_agg(cols.attnum) AS nums,
array_agg(refs.attname) AS refs
FROM ( SELECT unnest(conkey) AS col, unnest(confkey) AS ref) k,
LATERAL (SELECT * FROM pg_attribute
WHERE attrelid = conrelid AND attnum = col)
AS cols,
LATERAL (SELECT * FROM pg_attribute
WHERE attrelid = confrelid AND attnum = ref)
AS refs)
AS column_info,
LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = connamespace) AS ns1,
LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = conrelid) AS tab,
LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = confrelid) AS other,
LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = other.relnamespace) AS ns2
WHERE confrelid != 0
ORDER BY (conrelid, column_info.nums) |]
relationFromRow :: [Table] -> [Column] -> (Text, Text, [Text], Text, Text, [Text]) -> Maybe Relation
relationFromRow allTabs allCols (rs, rt, rcs, frs, frt, frcs) =
Relation <$> table <*> cols <*> tableF <*> colsF <*> pure Child <*> pure Nothing <*> pure Nothing <*> pure Nothing
where
findTable s t = find (\tbl -> tableSchema tbl == s && tableName tbl == t) allTabs
findCol s t c = find (\col -> tableSchema (colTable col) == s && tableName (colTable col) == t && colName col == c) allCols
table = findTable rs rt
tableF = findTable frs frt
cols = mapM (findCol rs rt) rcs
colsF = mapM (findCol frs frt) frcs
allPrimaryKeys :: [Table] -> H.Statement () [PrimaryKey]
allPrimaryKeys tabs =
H.Statement sql HE.unit (decodePks tabs) True
where
sql = [q|
/*
-- CTE to replace information_schema.table_constraints to remove owner limit
*/
WITH tc AS (
SELECT current_database()::information_schema.sql_identifier AS constraint_catalog,
nc.nspname::information_schema.sql_identifier AS constraint_schema,
c.conname::information_schema.sql_identifier AS constraint_name,
current_database()::information_schema.sql_identifier AS table_catalog,
nr.nspname::information_schema.sql_identifier AS table_schema,
r.relname::information_schema.sql_identifier AS table_name,
CASE c.contype
WHEN 'c'::"char" THEN 'CHECK'::text
WHEN 'f'::"char" THEN 'FOREIGN KEY'::text
WHEN 'p'::"char" THEN 'PRIMARY KEY'::text
WHEN 'u'::"char" THEN 'UNIQUE'::text
ELSE NULL::text
END::information_schema.character_data AS constraint_type,
CASE
WHEN c.condeferrable THEN 'YES'::text
ELSE 'NO'::text
END::information_schema.yes_or_no AS is_deferrable,
CASE
WHEN c.condeferred THEN 'YES'::text
ELSE 'NO'::text
END::information_schema.yes_or_no AS initially_deferred
FROM pg_namespace nc,
pg_namespace nr,
pg_constraint c,
pg_class r
WHERE nc.oid = c.connamespace AND nr.oid = r.relnamespace AND c.conrelid = r.oid AND (c.contype <> ALL (ARRAY['t'::"char", 'x'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)
/*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/
UNION ALL
SELECT current_database()::information_schema.sql_identifier AS constraint_catalog,
nr.nspname::information_schema.sql_identifier AS constraint_schema,
(((((nr.oid::text || '_'::text) || r.oid::text) || '_'::text) || a.attnum::text) || '_not_null'::text)::information_schema.sql_identifier AS constraint_name,
current_database()::information_schema.sql_identifier AS table_catalog,
nr.nspname::information_schema.sql_identifier AS table_schema,
r.relname::information_schema.sql_identifier AS table_name,
'CHECK'::character varying::information_schema.character_data AS constraint_type,
'NO'::character varying::information_schema.yes_or_no AS is_deferrable,
'NO'::character varying::information_schema.yes_or_no AS initially_deferred
FROM pg_namespace nr,
pg_class r,
pg_attribute a
WHERE nr.oid = r.relnamespace AND r.oid = a.attrelid AND a.attnotnull AND a.attnum > 0 AND NOT a.attisdropped AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)
/*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/
),
/*
-- CTE to replace information_schema.key_column_usage to remove owner limit
*/
kc AS (
SELECT current_database()::information_schema.sql_identifier AS constraint_catalog,
ss.nc_nspname::information_schema.sql_identifier AS constraint_schema,
ss.conname::information_schema.sql_identifier AS constraint_name,
current_database()::information_schema.sql_identifier AS table_catalog,
ss.nr_nspname::information_schema.sql_identifier AS table_schema,
ss.relname::information_schema.sql_identifier AS table_name,
a.attname::information_schema.sql_identifier AS column_name,
(ss.x).n::information_schema.cardinal_number AS ordinal_position,
CASE
WHEN ss.contype = 'f'::"char" THEN information_schema._pg_index_position(ss.conindid, ss.confkey[(ss.x).n])
ELSE NULL::integer
END::information_schema.cardinal_number AS position_in_unique_constraint
FROM pg_attribute a,
( SELECT r.oid AS roid,
r.relname,
r.relowner,
nc.nspname AS nc_nspname,
nr.nspname AS nr_nspname,
c.oid AS coid,
c.conname,
c.contype,
c.conindid,
c.confkey,
c.confrelid,
information_schema._pg_expandarray(c.conkey) AS x
FROM pg_namespace nr,
pg_class r,
pg_namespace nc,
pg_constraint c
WHERE nr.oid = r.relnamespace AND r.oid = c.conrelid AND nc.oid = c.connamespace AND (c.contype = ANY (ARRAY['p'::"char", 'u'::"char", 'f'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)) ss
WHERE ss.roid = a.attrelid AND a.attnum = (ss.x).x AND NOT a.attisdropped
/*--AND (pg_has_role(ss.relowner, 'USAGE'::text) OR has_column_privilege(ss.roid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/
)
SELECT
kc.table_schema,
kc.table_name,
kc.column_name
FROM
/*
--information_schema.table_constraints tc,
--information_schema.key_column_usage kc
*/
tc, kc
WHERE
tc.constraint_type = 'PRIMARY KEY' AND
kc.table_name = tc.table_name AND
kc.table_schema = tc.table_schema AND
kc.constraint_name = tc.constraint_name AND
kc.table_schema NOT IN ('pg_catalog', 'information_schema') |]
pkFromRow :: [Table] -> (Schema, Text, Text) -> Maybe PrimaryKey
pkFromRow tabs (s, t, n) = PrimaryKey <$> table <*> pure n
where table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs
allSynonyms :: [Column] -> PgVersion -> H.Statement Schema [Synonym]
allSynonyms cols pgVer =
H.Statement sql (HE.param HE.text) (decodeSynonyms cols) True
-- query explanation at https://gist.github.com/steve-chavez/7ee0e6590cddafb532e5f00c46275569
where
subselectRegex :: Text
-- "result" appears when the subselect is used inside "case when", see `authors_have_book_in_decade` fixture
-- "resno" appears in every other case
-- when copying the query into pg make sure you omit one backslash from \\d+, it should be like `\d+` for the regex
subselectRegex | pgVer < pgVersion100 = ":subselect {.*?:constraintDeps <>} :location \\d+} :res(no|ult)"
| otherwise = ":subselect {.*?:stmt_len 0} :location \\d+} :res(no|ult)"
sql = [qc|
with
views as (
select
n.nspname as view_schema,
c.relname as view_name,
r.ev_action as view_definition
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
join pg_rewrite r on r.ev_class = c.oid
where (c.relkind in ('v', 'm')) and n.nspname = $1
),
removed_subselects as(
select
view_schema, view_name,
regexp_replace(view_definition, '{subselectRegex}', '', 'g') as x
from views
),
target_lists as(
select
view_schema, view_name,
regexp_split_to_array(x, 'targetList') as x
from removed_subselects
),
last_target_list_wo_tail as(
select
view_schema, view_name,
(regexp_split_to_array(x[array_upper(x, 1)], ':onConflict'))[1] as x
from target_lists
),
target_entries as(
select
view_schema, view_name,
unnest(regexp_split_to_array(x, 'TARGETENTRY')) as entry
from last_target_list_wo_tail
),
results as(
select
view_schema, view_name,
substring(entry from ':resname (.*?) :') as view_colum_name,
substring(entry from ':resorigtbl (.*?) :') as resorigtbl,
substring(entry from ':resorigcol (.*?) :') as resorigcol
from target_entries
)
select
sch.nspname as table_schema,
tbl.relname as table_name,
col.attname as table_column_name,
res.view_schema,
res.view_name,
res.view_colum_name
from results res
join pg_class tbl on tbl.oid::text = res.resorigtbl
join pg_attribute col on col.attrelid = tbl.oid and col.attnum::text = res.resorigcol
join pg_namespace sch on sch.oid = tbl.relnamespace
where resorigtbl <> '0'
order by view_schema, view_name, view_colum_name; |]
synonymFromRow :: [Column] -> (Text,Text,Text,Text,Text,Text) -> Maybe Synonym
synonymFromRow allCols (s1,t1,c1,s2,t2,c2) = (,) <$> col1 <*> col2
where
col1 = findCol s1 t1 c1
col2 = findCol s2 t2 c2
findCol s t c = find (\col -> (tableSchema . colTable) col == s && (tableName . colTable) col == t && colName col == c) allCols
getPgVersion :: H.Session PgVersion
getPgVersion = H.statement () $ H.Statement sql HE.unit versionRow False
where
sql = "SELECT current_setting('server_version_num')::integer, current_setting('server_version')"
versionRow = HD.singleRow $ PgVersion <$> HD.column HD.int4 <*> HD.column HD.text
| begriffs/postgrest | src/PostgREST/DbStructure.hs | mit | 37,710 | 0 | 21 | 10,645 | 4,568 | 2,419 | 2,149 | 254 | 5 |
module LoggingSpec (spec, main) where
import Control.Monad.Except (runExceptT)
import Data.Either.Combinators (fromRight')
import Data.Monoid ((<>))
import Network.AWS.S3.Types (BucketName(..))
import Network.AWS.Types (Region(..))
import Test.Hspec ( describe
, context
, shouldBe
, shouldSatisfy
, it
, hspec
, Spec
)
import Configuration (Command(..))
import Logging ( logMain
, logGeneral
, logStackName
, logExecution
, logStackOutputs
, logFileUpload
, logZip
, filterBuilderBy
, LogParameters(..)
)
import StackParameters (getStackParameters, StackDescription(..))
import Types ( StackName(..)
, StackOutputName(..)
)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "LoggingSpec" $ do
context "generating log messages" $ do
it "can generate a main log message" $ do
stackParams <- runExceptT . getStackParameters $ "test/valid.yaml"
let descriptions = fromRight' stackParams
let accountID = "478156153062"
let logParams = LogParameters Create descriptions accountID Sydney
let logMessage = logMain logParams
logMessage `shouldBe`
"\nCommand being executed: "
<> "Create"
<> "\nAWS Account ID: "
<> "478156153062"
<> "\nRegion: ap-southeast-2"
<> "\nStack(s) being operated on:"
<> "\n Stack1"
<> "\n Stack2"
it "can generate a general log message" $ do
let accountID = "478156153062"
let logMessage = logGeneral Create accountID Sydney
logMessage `shouldBe`
"\nCommand being executed: "
<> "Create"
<> "\nAWS Account ID: "
<> "478156153062"
<> "\nRegion: ap-southeast-2"
it "can generate a stack name log message" $ do
stackParams <- runExceptT . getStackParameters $ "test/valid.yaml"
let desc = head . fromRight' $ stackParams
let logMessage = logStackName desc
logMessage `shouldBe` "\n Stack1"
it "can generate a command execution log message" $ do
stackParams <- runExceptT . getStackParameters $ "test/valid.yaml"
let desc = head . fromRight' $ stackParams
let logMessage = logExecution Create (_stackName desc) Sydney
logMessage `shouldBe`
"\nExecuting "
<> "Create"
<> " on "
<> "Stack1"
<> " in "
<> "ap-southeast-2"
<> "...\n"
it "can generate a stack outputs log message" $ do
let stackOutputs = Just ([
(StackOutputName (StackName "myStack") "myOutput1", "OutputValue1")
, (StackOutputName (StackName "myStack") "myOutput2", "OutputValue2")
])
let logMessage = logStackOutputs stackOutputs
logMessage `shouldBe`
"Stack outputs:\n"
<> "Stack name: myStack, Output name: myOutput1, Output value: OutputValue1\n"
<> "Stack name: myStack, Output name: myOutput2, Output value: OutputValue2\n"
it "can generate a file upload log message" $ do
let filePath = "myFolder/myFile.txt"
let myAltPath = "folder/myFile.txt"
let bucketName = BucketName "myBucket"
logFileUpload filePath myAltPath bucketName `shouldBe`
"Uploading myFolder/myFile.txt"
<> " as folder/myFile.txt"
<> " to myBucket"
it "can generate a zip log message" $ do
let nameOfZip = "test.zip"
let paths = ["folder/file1.txt", "folder/file2.txt"]
logZip nameOfZip paths `shouldBe`
"Creating archive test.zip"
<> "\n folder/file1.txt"
<> "\n folder/file2.txt"
it "logs properly when there are no stack outputs" $ do
let stackOutputs = Nothing
let logMessage = logStackOutputs stackOutputs
logMessage `shouldBe` "Stack outputs: None"
context "filtering log messages" $
it "can filter a message based on a given prefix" $ do
let prefix = "Log:"
let message = "Log: This is a logMessage."
prefix `shouldSatisfy` filterBuilderBy message
| SEEK-Org/evaporate | test/LoggingSpec.hs | mit | 4,260 | 0 | 23 | 1,310 | 866 | 443 | 423 | 105 | 1 |
module Data.Rational where
import Prelude hiding (Rational)
import Data.Maybe
import Data.List
import Data.Function
data Rational =
Rational { numerator :: Integer
, denominator :: Integer }
instance Show Rational where
show r = show (numerator r) ++ "/" ++ show (denominator r)
instance Read Rational where
readsPrec _ s = [(Rational (read p) (read $ tail q), "")]
where (p, q) = splitAt (fromJust $ elemIndex '/' s) s
add :: Rational -> Rational -> Rational
add p q = Rational ((r + s) `quot` gcdRS) (lcmPQ `quot` gcdRS)
where lcmPQ = (lcm `on` denominator) p q
r = (lcmPQ `quot` denominator p) * numerator p
s = (lcmPQ `quot` denominator q) * numerator q
rs = r + s
gcdRS = gcd (r + s) lcmPQ
| gallais/dailyprogrammer | easy/226/Data/Rational.hs | mit | 768 | 0 | 11 | 200 | 320 | 175 | 145 | 20 | 1 |
module Core.CorePrelude(preludeDefs) where
import Core.CoreExpr
preludeDefs :: CoreProgram
preludeDefs
= [ ("I", ["x"], EVar "x"),
("K", ["x","y"], EVar "x"),
("K1",["x","y"], EVar "y"),
("S", ["f","g","x"], EAp (EAp (EVar "f") (EVar "x"))
(EAp (EVar "g") (EVar "x"))),
("compose", ["f","g","x"], EAp (EVar "f")
(EAp (EVar "g") (EVar "x"))),
("twice", ["f"], EAp (EAp (EVar "compose") (EVar "f")) (EVar "f")) ]
| binesiyu/ifl | Core/CorePrelude.hs | mit | 524 | 0 | 11 | 169 | 250 | 143 | 107 | 12 | 1 |
ms = [getChar, getChar]
s1 :: Monad m => [m a] -> m [a]
s1 [] = return []
s1 (m:ms)
= m >>=
\ a ->
do as <- s1 ms
return (a:as)
-- can't >>= on return () <-- needs to be return []
{-s2 :: Monad m => [m a] -> m [a]-}
{-s2 ms = foldr func (return ()) ms-}
{-where-}
{-func :: (Monad m) => m a -> m [a] -> m [a]-}
{-func m acc-}
{-= do x <- m-}
{-xs <- acc-}
{-return (x : xs)-}
{-s3 :: Monad m => [m a] -> m [a]-}
{-s3 ms = foldr func (return []) ms-}
{-where-}
{-func :: (Monad m) => m a -> m [a] -> m [a]-}
{-func m acc = m : acc-}
-- invalid syntax
{-s4 :: Monad m => [m a] -> m [a]-}
{-s4 [] = return []-}
{-s4 (m : ms) = return (a : as)-}
{-where-}
{-a <- m-}
{-as <- s4 ms-}
s5 :: Monad m => [m a] -> m [a]
s5 ms = foldr func (return []) ms
where
func :: (Monad m) => m a -> m [a] -> m [a]
func m acc
= do x <- m
xs <- acc
return (x : xs)
-- Can't use '>>' with a lambda on the right!
{-s6 :: Monad m => [m a] -> m [a]-}
{-s6 [] = return []-}
{-s6 (m : ms)-}
{-= m >>-}
{-\ a ->-}
{-do as <- s6 ms-}
{-return (a : as)-}
-- Can't use <- without do syntax!
{-s7 :: Monad m => [m a] -> m [a]-}
{-s7 (m:ms) = m >>= \a ->-}
{-as <- s7 ms-}
{-return (a : as)-}
s8 :: Monad m => [m a] -> m [a]
s8 [] = return []
s8 (m : ms)
= do a <- m
as <- s8 ms
return (a:as)
| adz/real_world_haskell | edx-fp1/sequence.hs | mit | 1,428 | 0 | 11 | 489 | 351 | 189 | 162 | 21 | 1 |
{-# language ScopedTypeVariables #-}
module Control.Unification.IntVar.Extras (liftCatch) where
import Control.Unification.IntVar
import Control.Monad.Signatures (Catch)
import Control.Monad.Trans (lift)
import qualified Control.Monad.State.Class as St
runWithState :: St.MonadState s m => s -> m a -> m a
runWithState s m = St.put s >> m
-- | Lift a @catchE@ operation to the new monad.
liftCatch :: forall e tm m a . Monad m => Catch e m (a, IntBindingState tm) -> Catch e (IntBindingT tm m) a
liftCatch catch comp handler = do
initial <- St.get
(ans, final) <- lift $ guardedComp initial comp
St.put final
return ans
where
guardedComp :: IntBindingState tm -> IntBindingT tm m a -> m (a, IntBindingState tm)
guardedComp s m = runIntBindingT (runWithState s m) `catch` (runIntBindingT . runWithState s . handler)
| lambdageek/use-c | src/Control/Unification/IntVar/Extras.hs | mit | 844 | 0 | 11 | 156 | 292 | 154 | 138 | 16 | 1 |
import Data.Array
import Data.Maybe (catMaybes)
import qualified Data.Heap as H
import qualified Data.Set as S
import Debug.Trace
--trace _ b = b
main = do
input <- readFile "p083_matrix.txt"
print $ process input
process input = lookup (Point (1,1)) $ solve $ matrixArray $ toMatrix input
type Score = Int
toMatrix :: String -> [[Score]]
toMatrix input = map ((map read) . (split ',')) $ lines input
split :: (Eq a) => a -> [a] -> [[a]]
split _ [] = [[]]
split c s = case second of
[] -> [first]
(x:xs) -> first : split c xs
where (first, second) = break (==c) s
matrixSize matrix = let y = length matrix
x = length $ head matrix
in (x,y)
matrixArray matrix = listArray ((1,1),(x,y)) $ concat matrix
where (x,y) = matrixSize matrix
-- boilerplate ends here
newtype Point = Point (Int,Int) deriving (Show, Eq, Ord)
arr `at` (Point p) = arr ! p
solve arr = bfs (initialHeap arr) S.empty arr []
initialHeap :: (Ord a) => Array (Int,Int) a -> H.MinPrioHeap a Point
initialHeap arr = H.singleton (arr `at` p, p)
where p = Point (x1,y1)
((_,_),(x1,y1)) = bounds arr
data Direction = DUp | DDown | DRight | DLeft deriving (Show, Eq, Ord, Ix)
move :: Array (Int, Int) Int -> Point -> Direction -> Maybe Point
move arr (Point (i,j)) DUp | i>x0 = Just (Point (i-1, j))
| otherwise = Nothing
where ((x0,y0),(x1,y1)) = bounds arr
move arr (Point (i,j)) DDown | i<x1 = Just (Point (i+1, j))
| otherwise = Nothing
where ((x0,y0),(x1,y1)) = bounds arr
move arr (Point (i,j)) DLeft | j>y0 = Just (Point (i, j-1))
| otherwise = Nothing
where ((x0,y0),(x1,y1)) = bounds arr
move arr (Point (i,j)) DRight | j<y1 = Just (Point (i, j+1))
| otherwise = Nothing
where ((x0,y0),(x1,y1)) = bounds arr
reachable :: Point -> Array (Int, Int) Int -> S.Set Point -> [Point]
reachable point arr visited = filter (\p -> not $ S.member p visited) (catMaybes points)
where points = map (move arr point) [DUp, DDown, DRight, DLeft]
bfs :: H.MinPrioHeap Int Point -> S.Set Point -> Array (Int, Int) Int -> [(Point,Int)] -> [(Point, Int)]
bfs heap _ _ values | H.null heap = values
--bfs heap visited arr values | trace ("---------------\n" ++ show values ++ "\n" ++ show visited) False = undefined
bfs heap visited arr values = bfs heap' visited'' arr values'
where ((top:_), restHeap) = H.splitAt 1 heap
(value, point) = top
points = reachable point arr visited
visited' = S.insert point visited
visited'' = foldr S.insert visited' points
pvals = map (\p -> (arr `at` p + value, p)) points
heap' = foldr H.insert restHeap pvals
newValue = (point, value)
values' = newValue : values
| arekfu/project_euler | p0083/p0083.hs | mit | 2,889 | 0 | 12 | 798 | 1,351 | 723 | 628 | 59 | 2 |
-- statemonads.hs
import Control.Monad.State
| gitrookie/functionalcode | code/Haskell/snippets/statemonads.hs | mit | 48 | 0 | 4 | 7 | 8 | 5 | 3 | 1 | 0 |
import Data.Matrix
import Hungarian
import System.Random
import Criterion.Main
import Control.DeepSeq (($!!))
data NamedMatrix a = NMatrix String (Matrix a)
instance (Show a) => Show (NamedMatrix a) where
show (NMatrix string matr) = "\n\n" ++ string ++ "\n\n" ++ show matr
main = do
putStrLn "Enter a number to seed random generator with mkStdGen, or type 'new' to use newStdGen."
response <- getLine
globalStdGen <- newStdGen
let stdGen = if response == "new"
then globalStdGen
else mkStdGen (read response :: Int)
putStrLn "Run benchmarks up to what nxn size matrix?"
size <- getLine
let matrixSize = (read size :: Int)
putStrLn $ show $ generateSolvedRandomMatrices matrixSize stdGen
defaultMain [
bgroup "hungarianMin" $ generateBenchmarks matrixSize stdGen
]
randSquareMatrix :: Int -> Int -> StdGen -> Int -> Matrix Int
randSquareMatrix lowerLimit upperLimit g x = matrix x x $ \(i,j) -> randomNumbers !! (j + i*x)
where randomNumbers = randomRs (lowerLimit, upperLimit) g
randTestMatrix = randSquareMatrix 0 1000
generateBenchmarks :: Int -> StdGen -> [Benchmark]
generateBenchmarks 0 _ = []
generateBenchmarks x g = generateBenchmarks (x-1) (snd (next g)) ++ [bench (show x ++ "x" ++ show x) $ (whnf hungarianMin) $!! randTestMatrix g x]
generateSolvedRandomMatrices :: Int -> StdGen -> [NamedMatrix Int]
generateSolvedRandomMatrices 0 _ = []
generateSolvedRandomMatrices x g =
let randName = "Random " ++ sizeStr x ++ " Matrix"
randMatrix = randTestMatrix g x
solvedName = "Solved Random " ++ sizeStr x ++ " Matrix"
solvedMatrix = hungarianMin randMatrix
in generateSolvedRandomMatrices (x-1) (snd (next g)) ++ NMatrix randName randMatrix : [NMatrix solvedName solvedMatrix]
sizeStr :: Int -> String
sizeStr x = show x ++ "x" ++ show x | jjeffrey/hungarian | CriterionTests.hs | mit | 1,929 | 12 | 16 | 453 | 592 | 304 | 288 | 38 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NamedFieldPuns #-}
module Server.Web where
import Data.String (fromString)
import Web.Scotty
import Network.HTTP.Types (status404)
import Network.Wai.Middleware.RequestLogger (logStdoutDev)
import Server.Types
import Server.ProgramOptions (ProgramOptions(..))
import Server.Stream (getStream)
import Server.HLSProxy (getProxy)
import Control.Monad.IO.Class (liftIO)
import Control.Concurrent.MVar (MVar(..))
runServer :: MVar ServerState -> ProgramOptions -> IO ()
runServer state options = scotty webPort $ do
middleware logStdoutDev
get "/:channel" $ do
channel <- param "channel"
maybeStream <- liftIO $ getStream options channel state
withJustOr404 json maybeStream
get playlistRoutePattern $ do
channel <- param "channel"
quality <- param "quality"
mbProxy <- liftIO $ getProxy options channel quality state
withJustOr404 serveProxy mbProxy
where
ProgramOptions{indexFileName, webPort} = options
playlistRoutePattern = fromString $
"/:channel/:quality/" ++ indexFileName
withJustOr404 :: (a -> ActionM ()) -> Maybe a -> ActionM ()
withJustOr404 = maybe $ status status404
serveProxy :: HLSProxy -> ActionM ()
serveProxy proxy = do
addHeader "Content-Type" "application/vnd.apple.mpegurl"
file $ indexPath proxy
| best-coloc-ever/twitch-cast | streamer/app/Server/Web.hs | mit | 1,425 | 0 | 13 | 280 | 376 | 192 | 184 | 35 | 1 |
{-|
Module : Sivi.Operation.Types
Description : Type declarations
Copyright : (c) Maxime ANDRE, 2015
License : GPL-2
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
-}
module Sivi.Operation.Types
(
Transformation
, Operation
, OpEnvironment(..)
, OpState(..)
, Tool(..)
, ArcDirection(..)
, CuttingParameters(..)
, buildEnvironment
, buildState
) where
import Linear
import Control.Monad.RWS
type Transformation = V3 Double -> V3 Double
-- | The Operation type.
type Operation m w a = RWS (OpEnvironment m) w OpState a
-- | Contains the Reader part of the 'Operation' monad.
-- Before, a tuple was used. But a custom datatype is more readable, and it is easier to add new parameters.
-- Each parameter name is prepended with an "e" to avoid name collisions with functions like 'Sivi.Operation.Base.getTransformation', 'Sivi.Operation.Base.getFeedRate', ... Moreover, these names are used only internally, and won't be used by the user. They are a bit ugly, but it's not really a problem.
data OpEnvironment m = OpEnvironment {
eTransformation :: Transformation
, eFeedRate :: Double
, ePlungeRate :: Double
, eProbeRate :: Double
, eDepthOfCut :: Double
, eMachine :: m
}
-- | Contains the State part of the 'Operation' monad.
-- Each parameter is prepended with an "s" tto avoid name collisions. For the same reason as 'OpEnvironment'.
data OpState = OpState {
sCurrentPosition :: (V3 Double)
, sTool :: Tool
}
-- | Tool data type.
-- Used for tool changes, radius compensation.
data Tool =
EndMill { diameter :: Double, len :: Double }
| BallEndMill { diameter :: Double, shankDiameter :: Double, len :: Double } -- ^ The coordinates of the tool are the center of the ball (and not the bottom of the tool)
| ProbeTool { diameter :: Double, len :: Double }
deriving (Eq, Show)
data ArcDirection = CW -- ^ Clockwise
| CCW -- ^ Counterclockwise
deriving (Eq, Show)
-- | Cutting parameters : contains the feed rate, plunge rate, etc. They are needed when we want to run an operation with 'Sivi.Operation.Run.runOperation'.
data CuttingParameters m = CuttingParameters {
transformation :: Transformation -- ^ the initial transformation should always be 'Prelude.id' (identity function, i.e. no transformation). Use something else if you know what you are doing.
, feedRate :: Double
, plungeRate :: Double
, probeRate :: Double
, depthOfCut :: Double -- ^ Must be a negative number
, machine :: m
, initialPosition :: V3 Double
, initialTool :: Tool
}
-- | Gets the environment part of the cutting parameters.
buildEnvironment :: CuttingParameters m -> OpEnvironment m
buildEnvironment (CuttingParameters tr fr pr pbr dc m _ _) = OpEnvironment tr fr pr pbr dc m
-- | Gets the state part of the cutting parameters.
buildState :: CuttingParameters m -> OpState
buildState (CuttingParameters _ _ _ _ _ _ ipos itool) = OpState ipos itool
| iemxblog/sivi-haskell | src/Sivi/Operation/Types.hs | gpl-2.0 | 3,199 | 0 | 10 | 808 | 450 | 275 | 175 | 46 | 1 |
import Data.Char
import System.IO
n :: Integer
n = 134896036104102133446208954973118530800743044711419303630456535295204304771800100892609593430702833309387082353959992161865438523195671760946142657809228938824313865760630832980160727407084204864544706387890655083179518455155520501821681606874346463698215916627632418223019328444607858743434475109717014763667
k :: Int
k = 131
primes :: [Integer]
primes = take k $ sieve (2 : [3, 5..])
where
sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
stringToInteger :: String -> Integer
stringToInteger str = foldl (\x y -> (toInteger $ ord y) + x*256) 0 str
integerToString :: Integer -> String
integerToString num = f num ""
where
f 0 str = str
f num str = f (div num 256) $ (:) (chr $ fromIntegral $ num `mod` 256) str
numToBits :: Integer -> [Int]
numToBits num = f num []
where
f 0 arr = arr
f x arr = f (div x 2) ((fromInteger $ x `mod` 2) : arr)
extendBits :: Int -> [Int] -> [Int]
extendBits blockLen arr
| len == 0 = arr
| len > 0 = (replicate (blockLen-len) 0) ++ arr
where len = (length arr) `mod` blockLen
calc :: Integer -> [Int] -> Integer
calc num [] = num
calc num arr = calc result restArr
where
num2 = num*num `mod` n
(block, restArr) = splitAt k arr
zipped = zipWith (\x y -> ((fromIntegral x)*y) `mod` n) block primes
mul = product $ filter (/=0) zipped
result = num2*mul `mod` n
magic :: String -> String
magic input = result
where
num = stringToInteger input
bits = numToBits num
extended = reverse $ extendBits 8 bits
oriLen = length extended
extendedBits = extendBits k extended
oriLenBits = numToBits $ fromIntegral oriLen
extendedOriLenBits = extendBits k oriLenBits
finalBits = extendedOriLenBits ++ extendedBits
result = show $ calc 1 (reverse finalBits)
main = do
flag <- readFile "flag"
putStrLn.show $ length flag
putStrLn $ magic ("the flag is hitcon{" ++ flag ++ "}")
| Qwaz/solved-hacking-problem | HITCON/2019 Quals/very_simple_haskell/prob.hs | gpl-2.0 | 2,051 | 6 | 12 | 504 | 788 | 394 | 394 | 47 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module TestHttpConduit
(runGoogle)
where
import Network.HTTP.Conduit
import Data.Conduit
import Data.Conduit.Binary(sinkFile)
import qualified Data.ByteString.Lazy as L
import Control.Monad.IO.Class (liftIO)
-- Process the result byte string by saving the transaction in
-- the database.
parse aResponse = responseBody aResponse
runGoogle :: IO ()
runGoogle = do
-- We are in the IO monad
runResourceT $ do
-- Now we are in the resource transformer monad.
-- the idea being that the exception path
-- is handled inside the ResourceTransformer monad
manager <- liftIO $ newManager def
-- the newManager call returns an IO Manager so liftIO
-- is a generic operation that lifts the manager from IO
-- and puts it in the resource transformer.
--
req <- liftIO $ parseUrl "http://www.google.com"
res <- httpLbs req manager
-- Process this response
-- save it in the database, break out the components and do something like that.
let resultByteString = parse res in
liftIO $ L.putStr $ resultByteString
| dservgun/haskell_test_code | src/TestHttpConduit.hs | gpl-2.0 | 1,227 | 0 | 14 | 353 | 165 | 93 | 72 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Lib.Parallelism
( ParId
, Parallelism, new
, Cell
, Priority(..)
, startAlloc
, withReleased
) where
import Control.Concurrent.MVar
import Control.Monad
import Data.IORef
import Lib.Exception (bracket, bracket_, finally)
import Lib.IORef (atomicModifyIORef_)
import Lib.PoolAlloc (PoolAlloc, Priority(..))
import qualified Control.Exception as E
import qualified Lib.PoolAlloc as PoolAlloc
-- NOTE: withReleased may be called multiple times on the same Cell,
-- concurrently. This is allowed, but the parallelism will only be
-- released and regained once. The regain will occur after all
-- withReleased sections completed. This means that not every
-- "withReleased" completion actually incurs a re-allocation -- so
-- withReleased can complete without parallelism being allocated. This
-- happens anywhere whenever there is hidden concurrency in a build
-- step, so it's not a big deal.
type ParId = Int
data CellState
= CellReleased Int (MVar ()) -- ^ Release overdraft and mvar to publish alloc result when allocation succeeds
| CellAlloced ParId
| CellAllocating (MVar ())
type Cell = IORef CellState
type Parallelism = PoolAlloc ParId
new :: ParId -> IO Parallelism
new n = PoolAlloc.new [1..n]
-- MUST be called under proper masking to avoid losing result bracket
-- which MUST be invoked to avoid a leak!
startAlloc :: Priority -> Parallelism -> IO ((Cell -> IO r) -> IO r)
startAlloc priority parallelism = do
alloc <- PoolAlloc.startAlloc priority parallelism
return $ bracket (newIORef . CellAlloced =<< alloc) (release parallelism)
release :: Parallelism -> Cell -> IO ()
release parallelism cell = go
where
go = do
mvar <- newEmptyMVar
E.mask_ $ do
join $ atomicModifyIORef cell $ \cellState ->
case cellState of
CellReleased n oldMVar -> (CellReleased (n + 1) oldMVar, return ())
CellAlloced parId -> (CellReleased 0 mvar, PoolAlloc.release parallelism parId)
CellAllocating oldMVar -> (cellState, readMVar oldMVar >> go)
-- | Release the currently held item, run given action, then regain
-- new item instead
withReleased :: Priority -> Cell -> Parallelism -> IO a -> IO a
withReleased priority cell parallelism =
bracket_ (release parallelism cell) realloc
where
setAlloced parId = atomicModifyIORef_ cell $ \cellState ->
case cellState of
CellAllocating _ -> CellAlloced parId
_ -> error "Somebody touched the cell when it was in CellAllocating?!"
actualAlloc mvar =
(PoolAlloc.alloc priority parallelism >>= setAlloced)
`finally` putMVar mvar ()
realloc =
join $ atomicModifyIORef cell $ \cellState ->
case cellState of
CellReleased 0 mvar -> (CellAllocating mvar, actualAlloc mvar)
CellReleased n mvar -> (CellReleased (n-1) mvar, return ())
CellAllocating mvar -> (CellAllocating mvar, readMVar mvar >> realloc)
CellAlloced _ -> error "More allocs than releases?!"
| nadavshemer/buildsome | src/Lib/Parallelism.hs | gpl-2.0 | 3,029 | 0 | 20 | 624 | 712 | 377 | 335 | 56 | 5 |
module Codegen(
cGen,
runtimeCode,
runtimeMain
) where
import Bytecode
import Data.List
type CCode = String
type Prototype = String
runtimeCode :: IO String
runtimeCode = readFile "lib/runtime.c"
runtimeMain :: IO String
runtimeMain = readFile "lib/runtime_main.c"
cGen :: CompiledFun -> ([Prototype], CCode)
cGen (n, ic, na, code) = (protos, glob_val ++ fun')
where fun = "uint8_t __fun_" ++ n' ++ "(uint8_t n)\n{\n\t" ++ varCheck ++ ccode ++ "\n}\n"
glob_val = "struct __val " ++ n' ++ "()\n{\n\t" ++ str ++ "\n}\n"
struct = "struct __val v = {};\n\t"
++ "v.data = __fun_" ++ n' ++ ";\n\t"
++ "return v;"
struct' = ccode ++ "\n\t"
++ "struct __val v = __read_val(0);\n\t"
++ "__pop();\n\t"
++ "return v;"
protos = protoVal : if not ic then [protoFun] else []
protoVal = "struct __val " ++ n' ++ "();"
protoFun = "uint8_t __fun_" ++ n' ++ "(uint8_t n);"
varCheck = "if (n != " ++ show na ++ ") {\n\t\treturn 0;\n\t}\n\t"
str = if ic then struct' else struct
fun' = if ic then "" else fun
n' = mangle n
ccode = intercalate "\n\t" instrs
instrs = map genInstr code
genInstr :: Instruction -> String
genInstr i = case i of
PushNum i -> "__push_num(" ++ show i ++ ");"
PushStr s -> "__push_str(" ++ show s ++ ");"
PushVar i -> "__push_val(__read_val(" ++ show i ++ "));"
PushGlobal g -> "__push_val(" ++ mangle g ++ "());"
Call n -> "__call(" ++ show n ++ ");"
Unwind n -> "__unwind(" ++ show n ++ ");"
Pop -> "__pop();"
Return -> "return 1;"
Cond t e -> "if (__pop_num(0)) {" ++ tc ++ "} else {" ++ ec ++ "}"
where tc = unwords (map genInstr t)
ec = unwords (map genInstr e)
mangle :: String -> String
mangle s | head s == '$' = "builtin" ++ tail (init s) ++ "builtin"
mangle s = "b_" ++ concatMap mangleChar s ++ "_b"
mangleChar :: Char -> String
mangleChar c = case c of
'$' -> "builtin"
':' -> "_lambda_"
'\'' -> "_prime_"
x -> [x]
| dosenfrucht/beagle | src/Codegen.hs | gpl-2.0 | 2,174 | 0 | 12 | 682 | 656 | 339 | 317 | 54 | 9 |
module Functions.Algebra
(incSum
) where
incSum :: (Float -> Float) -> Float -> Float -> Float
incSum f sumMinBound sumMaxBound = sum [f i | i <- [sumMinBound .. sumMaxBound]]
| LeoMingo/RPNMathParser | Functions/Algebra.hs | gpl-3.0 | 180 | 0 | 9 | 34 | 70 | 38 | 32 | 4 | 1 |
module Infsabot.Strategy.Random.Interface(
complexity, cRandom,
randomChecks
) where
import Infsabot.Strategy.Random.Tests
import Infsabot.Strategy.Random.Logic | kavigupta/Infsabot | Infsabot/Strategy/Random/Interface.hs | gpl-3.0 | 189 | 0 | 4 | 39 | 33 | 23 | 10 | 5 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.ExternalVPNGateways.TestIAMPermissions
-- 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)
--
-- Returns permissions that a caller has on the specified resource.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.externalVpnGateways.testIamPermissions@.
module Network.Google.Resource.Compute.ExternalVPNGateways.TestIAMPermissions
(
-- * REST Resource
ExternalVPNGatewaysTestIAMPermissionsResource
-- * Creating a Request
, externalVPNGatewaysTestIAMPermissions
, ExternalVPNGatewaysTestIAMPermissions
-- * Request Lenses
, evgtipProject
, evgtipPayload
, evgtipResource
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.externalVpnGateways.testIamPermissions@ method which the
-- 'ExternalVPNGatewaysTestIAMPermissions' request conforms to.
type ExternalVPNGatewaysTestIAMPermissionsResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"externalVpnGateways" :>
Capture "resource" Text :>
"testIamPermissions" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TestPermissionsRequest :>
Post '[JSON] TestPermissionsResponse
-- | Returns permissions that a caller has on the specified resource.
--
-- /See:/ 'externalVPNGatewaysTestIAMPermissions' smart constructor.
data ExternalVPNGatewaysTestIAMPermissions =
ExternalVPNGatewaysTestIAMPermissions'
{ _evgtipProject :: !Text
, _evgtipPayload :: !TestPermissionsRequest
, _evgtipResource :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ExternalVPNGatewaysTestIAMPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'evgtipProject'
--
-- * 'evgtipPayload'
--
-- * 'evgtipResource'
externalVPNGatewaysTestIAMPermissions
:: Text -- ^ 'evgtipProject'
-> TestPermissionsRequest -- ^ 'evgtipPayload'
-> Text -- ^ 'evgtipResource'
-> ExternalVPNGatewaysTestIAMPermissions
externalVPNGatewaysTestIAMPermissions pEvgtipProject_ pEvgtipPayload_ pEvgtipResource_ =
ExternalVPNGatewaysTestIAMPermissions'
{ _evgtipProject = pEvgtipProject_
, _evgtipPayload = pEvgtipPayload_
, _evgtipResource = pEvgtipResource_
}
-- | Project ID for this request.
evgtipProject :: Lens' ExternalVPNGatewaysTestIAMPermissions Text
evgtipProject
= lens _evgtipProject
(\ s a -> s{_evgtipProject = a})
-- | Multipart request metadata.
evgtipPayload :: Lens' ExternalVPNGatewaysTestIAMPermissions TestPermissionsRequest
evgtipPayload
= lens _evgtipPayload
(\ s a -> s{_evgtipPayload = a})
-- | Name or id of the resource for this request.
evgtipResource :: Lens' ExternalVPNGatewaysTestIAMPermissions Text
evgtipResource
= lens _evgtipResource
(\ s a -> s{_evgtipResource = a})
instance GoogleRequest
ExternalVPNGatewaysTestIAMPermissions
where
type Rs ExternalVPNGatewaysTestIAMPermissions =
TestPermissionsResponse
type Scopes ExternalVPNGatewaysTestIAMPermissions =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient
ExternalVPNGatewaysTestIAMPermissions'{..}
= go _evgtipProject _evgtipResource (Just AltJSON)
_evgtipPayload
computeService
where go
= buildClient
(Proxy ::
Proxy ExternalVPNGatewaysTestIAMPermissionsResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/ExternalVPNGateways/TestIAMPermissions.hs | mpl-2.0 | 4,589 | 0 | 17 | 1,016 | 475 | 283 | 192 | 86 | 1 |
module Grouch.Simulation.PaperTrade where
import Grouch.Data
import Grouch.Games.Common
import Grouch.Bots.Blackjack
import Grouch.Games.Blackjack
import Grouch.Logging.Logger
import Data.Maybe
import Control.Arrow ((&&&))
import Control.Concurrent (threadDelay)
import Control.Monad.Trans.State
import Control.Monad.Trans.Class (lift)
import Control.Monad
-- TODO Extract the core functionality of the paper trader and make it so that you can plug in behaviours
type Odds = Double
type Value = Double
type PlayerId = Int
data Bet = Bet {
betSide :: Side
, betPlayer :: PlayerId
, betOdds :: Odds -- as in 6 for 5 to 1, or 2 for even
, betVal :: Value
} deriving (Show, Read)
data Side = Lay | Back deriving (Show, Read)
type Return = Double
evalWin :: Bet -> Return
evalWin (Bet Lay _ _ _) = 0
evalWin (Bet Back _ odds front) = odds * front
evalLoss :: Bet -> Return
evalLoss (Bet Lay _ odds front) = (front / odds) + front
evalLoss (Bet Back _ _ _) = 0
-- | Given a game snapshot, tells if the player won or lost
evaluateBet :: GameSnapshot -> Bet -> Return
evaluateBet snapshot bet =
if playerHand `beatsDealers` dealerHand then evalWin bet else evalLoss bet
where
hs = assembleGame snapshot
pname = "Player " ++ show (betPlayer bet)
dealerHand = handValue $ fromMaybe
(error "No dealer in hand, need dealer to evaluate bet!") $
lookup "Dealer" hs
playerHand = handValue $ fromMaybe
(error $ "Could not find for " ++ pname ++ ", cannot eval bet") $
lookup pname hs
data PlayerState = PlayerState {
playerPot :: Double
, playerBets :: [Bet]
} deriving (Show, Read)
defaultState :: PlayerState
defaultState = PlayerState 1000.0 []
-- Will need to iterate over the game, keeping tracks of what bets I have made and making new bets as opportunities come up.
-- Once the game ends, I will need to evaluate all the bets into a return, and work out my new pot. Actions should be written
-- to a log that I can put on disk somewhere.
type Simulation = StateT PlayerState IO ()
simulate :: PlayerState -> IO PlayerState
simulate initialState = do
grouchInfo "Grouch.Simulation.PaperTrade" "Starting simulation..."
end <- execStateT simulateStep initialState
grouchInfo "Grouch.Simulation.PaperTrade" $ "Simulation finished with state " ++ show end
return end
evaluateBets :: GameSnapshot -> Simulation
evaluateBets snapshot = do
pstate <- get
let returns = map (evaluateBet snapshot) $ playerBets pstate
lift $ grouchInfo "Grouch.Simulation.PaperTrade" $ "Final hands: " ++ show (asHandValues $ assembleGame snapshot)
lift $ grouchInfo "Grouch.Simulation.PaperTrade" $ "Winning bets: " ++ show (map snd $ filter (( > 0) . fst) $ zip returns $ playerBets pstate)
put $ pstate { playerBets = [], playerPot = playerPot pstate + sum returns }
placeBet :: Bet -> Simulation
placeBet bet = do
pstate <- get
unless
(betAlreadyPlaced (betPlayer bet) (playerBets pstate))
(put $ pstate { playerBets = bet : playerBets pstate, playerPot = playerPot pstate - betVal bet })
betAlreadyPlaced :: PlayerId -> [Bet] -> Bool
betAlreadyPlaced i bs = i `elem` map betPlayer bs
getBestBack :: PlayerId -> GameSnapshot -> Maybe Price
getBestBack player snapshot = listToMaybe =<< lookup playerName playerBacks
where
playerName = "Player " ++ show player
selections = marketSelections $ gameMarket snapshot
playerBacks = map (selectionName &&& selectionBestBackPrices) selections
getBestLay :: PlayerId -> GameSnapshot -> Maybe Price
getBestLay player snapshot = listToMaybe =<< lookup playerName playerLays
where
playerName = "Player " ++ show player
selections = marketSelections $ gameMarket snapshot
playerLays = map (selectionName &&& selectionBestLayPrices) selections
getGoodBacks :: GameSnapshot -> [(PlayerId, Price, Double)]
getGoodBacks snapshot =
map (\((name, actual), price) -> (playerId name, fromJust price, actual))
$ filter (uncurry oddsAreBetter) $ zip bettingOdds bestBacks
where
bettingOdds = map (\x -> (fst x, probToOdds $ snd x)) $ fromMaybe [] probs
probs = playerProbs $ assembleGame snapshot
bestBacks = map (`getBestBack` snapshot) [1.. 4]
playerId name = read [last name]
getGoodLays :: GameSnapshot -> [(PlayerId, Price, Double)]
getGoodLays snapshot =
map (\((name, actual), price) -> (playerId name, fromJust price, actual))
$ filter (uncurry oddsAreWorse) $ zip bettingOdds bestLays
where
bettingOdds = map (\x -> (fst x, probToOdds $ snd x)) $ fromMaybe [] probs
probs = playerProbs $ assembleGame snapshot
bestLays = map (`getBestLay` snapshot) [1.. 4]
playerId name = read [last name]
probThreshold :: Double
probThreshold = 0.2
oddsAreBetter :: (String, Double) -> Maybe Price -> Bool
oddsAreBetter (_, odds) (Just price)
| odds <= 2 = odds < (priceValue price - probThreshold)
| otherwise = False
oddsAreBetter _ _ = False
oddsAreWorse :: (String, Double) -> Maybe Price -> Bool
oddsAreWorse (_, odds) (Just price)
| odds >= 3 = odds > (priceValue price + probThreshold)
| otherwise = False
oddsAreWorse _ _ = False
{-
oddsAreBetter :: (String, Double) -> Maybe Price -> Bool
oddsAreBetter (_, odds) (Just price) = odds < priceValue price
oddsAreBetter _ _ = False
oddsAreWorse :: (String, Double) -> Maybe Price -> Bool
oddsAreWorse (_, odds) (Just price) = odds > priceValue price
oddsAreWorse _ _ = False
-}
constructDefaultBet :: Side -> (PlayerId, Price, Double) -> Bet
constructDefaultBet side (player, price, _) =
Bet side player (priceValue price) (min (priceAmountUnmatched price) 10)
constructKellyBet :: Side -> Double -> (PlayerId, Price, Double) -> Bet
constructKellyBet side pot (player, price, actual) = let kellyBet = pot * abs (kellyFrac (oddsToProb actual) (priceValue price)) in
Bet side player (priceValue price) (min (priceAmountUnmatched price) kellyBet)
simulateStep :: Simulation
simulateStep = do
snapshot <- lift getSnapshotTurbo
let hands = map (\(p, h) -> ([head p, last p], handValue h)) $ assembleGame snapshot
lift $ grouchDebug "Grouch.Simulation.PaperTrade" $ "Received new snapshot: " ++ show hands
lift $ threadDelay 4000000
pstate <- get
let lays = map (constructDefaultBet Lay) $ getGoodLays snapshot
let backs = map (constructDefaultBet Back) $ getGoodBacks snapshot
--let lays = map (constructKellyBet Lay $ playerPot pstate) $ getGoodLays snapshot
--let backs = map (constructKellyBet Back $ playerPot pstate) $ getGoodBacks snapshot
lift $ grouchInfo "Grouch.Simulation.PaperTrade" $ "Current state: " ++ show pstate
unless (playerPot pstate <= 0.0) $
--unless (gameOver snapshot) $
--unless (null lays) (placeBet $ head lays) >>
--unless (null backs) (placeBet $ head backs) >>
mapM_ placeBet lays >>
mapM_ placeBet backs >>
when (gameOver snapshot) (evaluateBets snapshot) >>
simulateStep
kellyFrac :: Double -> Double -> Double
kellyFrac p b = (p * b - 1) / (b - 1)
| tetigi/hlol | src/HLol/Simulation/PaperTrade.hs | agpl-3.0 | 7,220 | 0 | 16 | 1,545 | 2,043 | 1,065 | 978 | 129 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module CountdownGame.State.Snapshots
( Snapshot
, takeSnapshot
)where
import GHC.Generics (Generic)
import Data.Aeson (ToJSON)
import Data.Function (on)
import Data.Text (Text)
import Data.Time.Clock (UTCTime, getCurrentTime, diffUTCTime)
import Data.Maybe (isJust, fromMaybe, listToMaybe)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.List (sortBy)
import Countdown.Game (Attempt, AttemptsMap, Challange, Player, PlayersMap, PlayerId)
import qualified Countdown.Game as G
import CountdownGame.References
import CountdownGame.Database (getPlayersMap)
import CountdownGame.State.Definitions (State (..), Ergebnisse)
import qualified CountdownGame.State.Definitions as Def
data Snapshot =
Snapshot
{ goal :: Maybe Int
, availableNrs :: [Int]
, isWaiting :: Bool
, isRunning :: Bool
, secondsLeft :: Int
, scoreBoard :: Ergebnisse
} deriving (Generic, Show)
instance ToJSON Snapshot
takeSnapshot :: Bool -> State -> IO Snapshot
takeSnapshot isAdmin state = do
zielZ <- Def.zielZahl state
verfNrs <- Def.verfuegbareZahlen state
wartet <- Def.istWartend state
laueft <- Def.istInRunde state
seks <- Def.nochZuWartendeSekunden state
ergs <- Def.ergebnisListe state
return $ Snapshot zielZ verfNrs wartet laueft seks ergs
| CarstenKoenig/DOS2015 | CountdownGame/src/web/CountdownGame/State/Snapshots.hs | unlicense | 1,390 | 0 | 9 | 234 | 382 | 220 | 162 | 39 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.Probe where
import GHC.Generics
import Kubernetes.V1.ExecAction
import Kubernetes.V1.HTTPGetAction
import Kubernetes.V1.TCPSocketAction
import qualified Data.Aeson
-- | Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive traffic.
data Probe = Probe
{ exec :: Maybe ExecAction -- ^ One and only one of the following should be specified. Exec specifies the action to take.
, httpGet :: Maybe HTTPGetAction -- ^ HTTPGet specifies the http request to perform.
, tcpSocket :: Maybe TCPSocketAction -- ^ TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported
, initialDelaySeconds :: Maybe Integer -- ^ Number of seconds after the container has started before liveness probes are initiated. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes
, timeoutSeconds :: Maybe Integer -- ^ Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes
, periodSeconds :: Maybe Integer -- ^ How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.
, successThreshold :: Maybe Integer -- ^ Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness. Minimum value is 1.
, failureThreshold :: Maybe Integer -- ^ Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON Probe
instance Data.Aeson.ToJSON Probe
| minhdoboi/deprecated-openshift-haskell-api | kubernetes/lib/Kubernetes/V1/Probe.hs | apache-2.0 | 1,904 | 0 | 9 | 310 | 166 | 101 | 65 | 23 | 0 |
--
-- Copyright 2017 Andrew Dawson
--
-- 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.
--
module Test.Truncate.Arbitrary
( Bitstring32(..)
, Bitstring64(..)
, Hexstring32(..)
, Hexstring64(..)
, TiedWord32(..)
, TiedWord64(..)
) where
------------------------------------------------------------------------
import Test.QuickCheck
------------------------------------------------------------------------
import Data.Bits
import Data.Word
------------------------------------------------------------------------
-- 'Arbitrary' instances for bit-strings representing floating-point
-- numbers
newtype Bitstring32 = Bitstring32 String
deriving (Show)
instance Arbitrary Bitstring32 where
arbitrary = Bitstring32 <$> genBitstring 32
newtype Bitstring64 = Bitstring64 String
deriving (Show)
instance Arbitrary Bitstring64 where
arbitrary = Bitstring64 <$> genBitstring 64
genBitstring :: Int -> Gen String
genBitstring n = (listOf . choose) ('0', '1')
`suchThat` \ s -> length s == n
------------------------------------------------------------------------
-- 'Arbitrary' instances for hexadecimal-strings representing floating-point
-- numbers
newtype Hexstring32 = Hexstring32 String
deriving (Show)
instance Arbitrary Hexstring32 where
arbitrary = Hexstring32 <$> genHexstring 8
newtype Hexstring64 = Hexstring64 String
deriving (Show)
instance Arbitrary Hexstring64 where
arbitrary = Hexstring64 <$> genHexstring 16
genHexstring :: Int -> Gen String
genHexstring n = (listOf . elements) "0123456789abcdef"
`suchThat` \ s -> length s == n
------------------------------------------------------------------------
-- 'Arbitrary' instances for 'Word32' and 'Word64' types that produce
-- a number with a '1' in a particular bit and '0's in the bits to then
-- right of this
newtype TiedWord32 = TiedWord32 (Word32, Int)
deriving (Show)
instance Arbitrary TiedWord32 where
arbitrary = TiedWord32 <$> genTiedBits32
genTiedBits32 :: Gen (Word32, Int)
genTiedBits32 = do
n <- choose (1, 22)
w <- arbitrary :: Gen Word32
return (tieBits w (22 - n), n)
newtype TiedWord64 = TiedWord64 (Word64, Int)
deriving (Show)
instance Arbitrary TiedWord64 where
arbitrary = TiedWord64 <$> genTiedBits64
genTiedBits64 :: Gen (Word64, Int)
genTiedBits64 = do
n <- choose (1, 51)
w <- arbitrary :: Gen Word64
return (tieBits w (51 - n), n)
tieBits :: Bits a => a -> Int -> a
tieBits bits n = setBit (dropBits n bits) n
where
dropBits m = (`shiftL` m) . (`shiftR` m)
| aopp-pred/fp-truncate | test/Test/Truncate/Arbitrary.hs | apache-2.0 | 3,208 | 0 | 11 | 663 | 624 | 358 | 266 | 53 | 1 |
{-
Copyright 2020 The CodeWorld Authors. 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.
-}
main = drawingOf(codeWorldLogo)
| google/codeworld | codeworld-compiler/test/testcases/programCalledMain/source.hs | apache-2.0 | 643 | 0 | 6 | 119 | 13 | 7 | 6 | 1 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
-- | Constructors for K3 Expressions. This module should almost certainly be imported qualified.
module Language.K3.Core.Constructor.Expression (
immut,
mut,
constant,
variable,
some,
indirect,
tuple,
unit,
record,
empty,
lambda,
unop,
binop,
applyMany,
block,
send,
project,
letIn,
assign,
caseOf,
bindAs,
ifThenElse,
address,
self,
Binder(..),
Constant(..),
Operator(..)
) where
import Data.Tree
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Expression
import Language.K3.Core.Type
-- | Add mutability qualifier
mutable :: Bool -> K3 Expression -> K3 Expression
mutable b n =
n @+ (if b then EMutable else EImmutable)
-- | Shortcuts to the above
mut :: K3 Expression -> K3 Expression
mut = mutable True
immut :: K3 Expression -> K3 Expression
immut = mutable False
-- | Create a constant expression.
constant :: Constant -> K3 Expression
constant c = Node (EConstant c :@: []) []
-- | Create a variable expression.
variable :: Identifier -> K3 Expression
variable v = Node (EVariable v :@: []) []
-- | Create an option value from a constituent expression.
some :: K3 Expression -> K3 Expression
some e = Node (ESome :@: []) [e]
-- | Create an indirection to a the result of an expression.
indirect :: K3 Expression -> K3 Expression
indirect e = Node (EIndirect :@: []) [e]
-- | Create a tuple from a list of members.
tuple :: [K3 Expression] -> K3 Expression
tuple = Node (ETuple :@: [])
-- | Unit value.
unit :: K3 Expression
unit = Node (ETuple :@: []) []
-- | Create a record from a list of field names and initializers.
record :: [(Identifier, K3 Expression)] -> K3 Expression
record vs = Node (ERecord ids :@: []) es where (ids, es) = unzip vs
-- | Create an empty collection.
empty :: K3 Type -> K3 Expression
empty t = Node (EConstant (CEmpty t) :@: []) []
-- | Create an anonymous function..
lambda :: Identifier -> K3 Expression -> K3 Expression
lambda x b = Node (ELambda x :@: []) [b]
-- | Create an application of a unary operator.
unop :: Operator -> K3 Expression -> K3 Expression
unop op a = Node (EOperate op :@: []) [a]
-- | Create an application of a binary operator.
binop :: Operator -> K3 Expression -> K3 Expression -> K3 Expression
binop op a b = Node (EOperate op :@: []) [a, b]
-- | Create a multi-argument function application.
applyMany :: K3 Expression -> [K3 Expression] -> K3 Expression
applyMany f args = foldl (\curried_f arg -> binop OApp curried_f arg) f args
-- | Create a chain of sequential computation.
block :: [K3 Expression] -> K3 Expression
block [] = unit
block [x] = x
block exprs = foldl (\sq e -> binop OSeq sq e) (head exprs) (tail exprs)
send :: K3 Expression -> K3 Expression -> K3 Expression -> K3 Expression
send target addr arg = binop OSnd (tuple [qualifyE target, qualifyE addr]) arg
where qualifyE e = if null $ filter isEQualified $ annotations e then e @+ EImmutable else e
-- | Project a field from a record.
project :: Identifier -> K3 Expression -> K3 Expression
project i r = Node (EProject i :@: []) [r]
-- | Create a let binding.
letIn :: Identifier -> K3 Expression -> K3 Expression -> K3 Expression
letIn i e b = Node (ELetIn i :@: []) [e, b]
-- | Create an assignment.
assign :: Identifier -> K3 Expression -> K3 Expression
assign i v = Node (EAssign i :@: []) [v]
-- | Create a case destruction.
caseOf :: K3 Expression -> Identifier -> K3 Expression -> K3 Expression -> K3 Expression
caseOf e x s n = Node (ECaseOf x :@: []) [e, s, n]
-- | Create a binding destruction.
bindAs :: K3 Expression -> Binder -> K3 Expression -> K3 Expression
bindAs e x b = Node (EBindAs x :@: []) [e, b]
-- | Create an if/then/else conditional expression.
ifThenElse :: K3 Expression -> K3 Expression -> K3 Expression -> K3 Expression
ifThenElse p t e = Node (EIfThenElse :@: []) [p, t, e]
-- | Create an address expression
address :: K3 Expression -> K3 Expression -> K3 Expression
address ip port = Node (EAddress :@: []) [ip, port]
-- | A self expression.
self :: K3 Expression
self = Node (ESelf :@: []) []
| yliu120/K3 | src/Language/K3/Core/Constructor/Expression.hs | apache-2.0 | 4,212 | 0 | 10 | 871 | 1,430 | 748 | 682 | 89 | 2 |
module Handler.Gallery where
import Import
import qualified Data.Map as M
import Andon.Theme
import Andon.Gallery
getGalleryR :: Handler RepHtml
getGalleryR = defaultLayout $ do
setTitle "Gallery"
$(widgetFile "gallery")
| amutake/andon-yesod | Handler/Gallery.hs | bsd-2-clause | 234 | 0 | 10 | 40 | 60 | 33 | 27 | 9 | 1 |
{-| PyValueInstances contains instances for the 'PyValue' typeclass.
The typeclass 'PyValue' converts Haskell values to Python values.
This module contains instances of this typeclass for several generic
types. These instances are used in the Haskell to Python generation
of opcodes and constants, for example.
-}
{-
Copyright (C) 2013 Google Inc.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.
-}
{-# LANGUAGE FlexibleInstances, OverlappingInstances,
TypeSynonymInstances, IncoherentInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Ganeti.PyValueInstances where
import Data.List (intercalate)
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Set as Set (toList)
import Ganeti.BasicTypes
import Ganeti.THH
instance PyValue Bool where
showValue = show
instance PyValue Int where
showValue = show
instance PyValue Integer where
showValue = show
instance PyValue Double where
showValue = show
instance PyValue Char where
showValue = show
instance (PyValue a, PyValue b) => PyValue (a, b) where
showValue (x, y) = "(" ++ showValue x ++ "," ++ showValue y ++ ")"
instance (PyValue a, PyValue b, PyValue c) => PyValue (a, b, c) where
showValue (x, y, z) =
"(" ++
showValue x ++ "," ++
showValue y ++ "," ++
showValue z ++
")"
instance PyValue String where
showValue = show
instance PyValue a => PyValue [a] where
showValue xs = "[" ++ intercalate "," (map showValue xs) ++ "]"
instance (PyValue k, PyValue a) => PyValue (Map k a) where
showValue mp =
"{" ++ intercalate ", " (map showPair (Map.assocs mp)) ++ "}"
where showPair (k, x) = showValue k ++ ":" ++ showValue x
instance PyValue a => PyValue (ListSet a) where
showValue = showValue . Set.toList . unListSet
| apyrgio/snf-ganeti | src/Ganeti/PyValueInstances.hs | bsd-2-clause | 2,991 | 0 | 13 | 533 | 473 | 253 | 220 | 39 | 0 |
module Exercises.BalancedParenthesesSpec (main, spec) where
import Test.Hspec
import Exercises.BalancedParentheses
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "isValid" $ do
context "when input string is empty" $
it "valid" $
isValid "" `shouldBe` True
context "when input string contains balanced parentheses" $
it "valid" $ do
isValid "()" `shouldBe` True
isValid "((()))" `shouldBe` True
isValid "()()()" `shouldBe` True
isValid "()(())((()))" `shouldBe` True
context "when input string contains not balanced parentehses" $
it "not valid" $ do
isValid "(" `shouldBe` False
isValid ")" `shouldBe` False
isValid "(()" `shouldBe` False
isValid ")))" `shouldBe` False
isValid "((()))()(" `shouldBe` False
| WarKnife/exercises | test/Exercises/BalancedParenthesesSpec.hs | bsd-3-clause | 837 | 0 | 12 | 218 | 227 | 113 | 114 | 24 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Duration.DA.Rules
( rules ) where
import Control.Monad (join)
import qualified Data.Text as Text
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Duration.Helpers
import Duckling.Numeral.Helpers (parseInteger)
import Duckling.Numeral.Types (NumeralData (..))
import qualified Duckling.Numeral.Types as TNumeral
import Duckling.Regex.Types
import qualified Duckling.TimeGrain.Types as TG
import Duckling.Types
ruleExactlyDuration :: Rule
ruleExactlyDuration = Rule
{ name = "exactly <duration>"
, pattern =
[ regex "pr(æ)cis"
, dimension Duration
]
, prod = \tokens -> case tokens of
-- TODO(jodent) +precision exact
(_:token:_) -> Just token
_ -> Nothing
}
ruleIntegerAndAnHalfHours :: Rule
ruleIntegerAndAnHalfHours = Rule
{ name = "<integer> and an half hours"
, pattern =
[ Predicate isNatural
, regex "og (en )?halv timer?"
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = v}:_) ->
Just . Token Duration . duration TG.Minute $ 30 + 60 * floor v
_ -> Nothing
}
ruleAUnitofduration :: Rule
ruleAUnitofduration = Rule
{ name = "a <unit-of-duration>"
, pattern =
[ regex "en|et?"
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_) -> Just . Token Duration $ duration grain 1
_ -> Nothing
}
ruleIntegerMoreUnitofduration :: Rule
ruleIntegerMoreUnitofduration = Rule
{ name = "<integer> more <unit-of-duration>"
, pattern =
[ Predicate isNatural
, dimension TimeGrain
, regex "mere|mindre"
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = v}:
Token TimeGrain grain:
_) -> Just . Token Duration . duration grain $ floor v
_ -> Nothing
}
ruleFortnight :: Rule
ruleFortnight = Rule
{ name = "fortnight"
, pattern =
[ regex "(a|one)? fortnight"
]
, prod = \_ -> Just . Token Duration $ duration TG.Day 14
}
ruleAboutDuration :: Rule
ruleAboutDuration = Rule
{ name = "about <duration>"
, pattern =
[ regex "(omkring|cirka|ca.)"
, dimension Duration
]
, prod = \tokens -> case tokens of
-- TODO(jodent) +precision approximate
(_:token:_) -> Just token
_ -> Nothing
}
ruleNumeralnumberHours :: Rule
ruleNumeralnumberHours = Rule
{ name = "number.number hours"
, pattern =
[ regex "(\\d+)\\,(\\d+)"
, regex "timer?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (h:m:_)):_) -> do
hh <- parseInteger h
mnum <- parseInteger m
let mden = 10 ^ Text.length m
Just . Token Duration $ minutesFromHourMixedFraction hh mnum mden
_ -> Nothing
}
ruleHalfAnHour :: Rule
ruleHalfAnHour = Rule
{ name = "half an hour"
, pattern =
[ regex "(1/2|en halv) time"
]
, prod = \_ -> Just . Token Duration $ duration TG.Minute 30
}
rules :: [Rule]
rules =
[ ruleAUnitofduration
, ruleAboutDuration
, ruleExactlyDuration
, ruleFortnight
, ruleHalfAnHour
, ruleIntegerAndAnHalfHours
, ruleIntegerMoreUnitofduration
, ruleNumeralnumberHours
]
| facebookincubator/duckling | Duckling/Duration/DA/Rules.hs | bsd-3-clause | 3,472 | 0 | 18 | 809 | 909 | 510 | 399 | 100 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ConstraintKinds #-}
module Math.Coordinate.LogPolar where
import Data.Typeable (Typeable)
import Control.Applicative
import Data.Array.Accelerate
import Data.Array.Accelerate.Smart
import Data.Array.Accelerate.Product
import Data.Array.Accelerate.Array.Sugar
import Data.Complex
import qualified Data.Foldable as F
import qualified Math.Coordinate.Cartesian as Cartesian
import Math.Coordinate.Cartesian (Cartesian)
import Math.Coordinate.Coordinate (CoordConversion(..), ManualConversion(..), convertCoord)
import Math.Space.Space (Space2)
import qualified Math.Constants as Const
data LogPolar = LogPolar deriving (Show)
data Point2 a = Point2 { rho :: !a
, phi :: !a
} deriving (Eq, Ord, Show, Read, Typeable)
toLogPolar = convertCoord LogPolar
--------------------------------------------------------------------------------
-- Instances
--------------------------------------------------------------------------------
instance RealFloat a => CoordConversion ManualConversion Cartesian space (Point2 a) (Cartesian.Point2 a) where
convertCoordBase _ _ _ pt@(Point2 rho phi) = Cartesian.Point2 (base * cos phi) (base * sin phi)
where base = Const.e**rho
instance RealFloat a => CoordConversion ManualConversion LogPolar space (Cartesian.Point2 a) (Point2 a) where
convertCoordBase _ _ _ (Cartesian.Point2 x y) = Point2 rho phi
where rho = log . sqrt $ (x*x) + (y*y)
phi = atan2 y x
--------------------------------------------------------------------------------
-- Point2
--------------------------------------------------------------------------------
instance Functor Point2 where
fmap f (Point2 a b) = Point2 (f a) (f b)
instance Applicative Point2 where
pure a = Point2 a a
{-# INLINE pure #-}
Point2 a b <*> Point2 d e = Point2 (a d) (b e)
{-# INLINE (<*>) #-}
instance Num a => Num (Point2 a) where
(+) = liftA2 (+)
{-# INLINE (+) #-}
(-) = liftA2 (-)
{-# INLINE (-) #-}
(*) = liftA2 (*)
{-# INLINE (*) #-}
negate = fmap negate
{-# INLINE negate #-}
abs = fmap abs
{-# INLINE abs #-}
signum = fmap signum
{-# INLINE signum #-}
fromInteger = pure . fromInteger
{-# INLINE fromInteger #-}
instance Fractional a => Fractional (Point2 a) where
recip = fmap recip
{-# INLINE recip #-}
(/) = liftA2 (/)
{-# INLINE (/) #-}
fromRational = pure . fromRational
{-# INLINE fromRational #-}
type instance EltRepr (Point2 a) = EltRepr (a, a)
instance Elt a => Elt (Point2 a) where
eltType _ = eltType (undefined :: (a,a))
toElt p = case toElt p of
(x, y) -> Point2 x y
fromElt (Point2 x y) = fromElt (x, y)
instance cst a => IsProduct cst (Point2 a) where
type ProdRepr (Point2 a) = ProdRepr (a,a)
fromProd cst (Point2 x y) = fromProd cst (x,y)
toProd cst t = case toProd cst t of
(x, y) -> Point2 x y
prod cst _ = prod cst (undefined :: (a,a))
instance (Lift Exp a, Elt (Plain a)) => Lift Exp (Point2 a) where
type Plain (Point2 a) = Point2 (Plain a)
lift (Point2 x y) = Exp $ Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y
instance (Elt a, e ~ Exp a) => Unlift Exp (Point2 e) where
unlift t = Point2 (Exp $ SuccTupIdx ZeroTupIdx `Prj` t)
(Exp $ ZeroTupIdx `Prj` t)
| wdanilo/algebraic | src/Math/Coordinate/LogPolar.hs | bsd-3-clause | 3,802 | 0 | 11 | 892 | 1,125 | 618 | 507 | 87 | 1 |
-- ------------------------------------------------------------
{- |
Module : Yuuko.Text.XML.HXT.Arrow.DocumentInput
Copyright : Copyright (C) 2005 Uwe Schmidt
License : MIT
Maintainer : Uwe Schmidt ([email protected])
Stability : experimental
Portability: portable
Version : $Id$
State arrows for document input
-}
-- ------------------------------------------------------------
module Yuuko.Text.XML.HXT.Arrow.DocumentInput
( getURIContents
, getXmlContents
, getXmlEntityContents
, getEncoding
, getTextEncoding
, decodeDocument
)
where
import Control.Arrow -- arrow classes
import Yuuko.Control.Arrow.ArrowList
import Yuuko.Control.Arrow.ArrowIf
import Yuuko.Control.Arrow.ArrowTree
import Yuuko.Control.Arrow.ArrowIO
import Yuuko.Control.Arrow.ListArrow
import Data.List ( isPrefixOf )
import System.FilePath ( takeExtension )
import Yuuko.Text.XML.HXT.DOM.Unicode ( getDecodingFct
, guessEncoding
, normalizeNL
)
import qualified Yuuko.Text.XML.HXT.IO.GetFILE as FILE
import qualified Yuuko.Text.XML.HXT.IO.GetHTTPLibCurl as LibCURL
import Yuuko.Text.XML.HXT.DOM.Interface
import Yuuko.Text.XML.HXT.Arrow.ParserInterface ( parseXmlDocEncodingSpec
, parseXmlEntityEncodingSpec
, removeEncodingSpec
)
import Yuuko.Text.XML.HXT.Arrow.XmlArrow
import Yuuko.Text.XML.HXT.Arrow.XmlIOStateArrow
-- ----------------------------------------------------------
protocolHandlers :: AssocList String (IOStateArrow s XmlTree XmlTree)
protocolHandlers
= [ ("file", getFileContents)
, ("http", getHttpContents)
, ("stdin", getStdinContents)
]
getProtocolHandler :: IOStateArrow s String (IOStateArrow s XmlTree XmlTree)
getProtocolHandler
= arr (\ s -> lookupDef getUnsupported s protocolHandlers)
getUnsupported :: IOStateArrow s XmlTree XmlTree
getUnsupported
= perform ( getAttrValue a_source
>>>
arr (("unsupported protocol in URI " ++) . show)
>>>
applyA (arr issueFatal)
)
>>>
setDocumentStatusFromSystemState "accessing documents"
getStringContents :: IOStateArrow s XmlTree XmlTree
getStringContents
= setCont $< getAttrValue a_source
>>>
addAttr transferMessage "OK"
>>>
addAttr transferStatus "200"
where
setCont contents
= replaceChildren (txt contents')
>>>
addAttr transferURI (take 7 contents) -- the "string:" prefix is stored, this is required by setBaseURIFromDoc
>>>
addAttr a_source (show . prefix 48 $ contents') -- a quoted prefix of the content, max 48 chars is taken as source name
where
contents' = drop (length stringProtocol) contents
prefix l s
| length s' > l = take (l - 3) s' ++ "..."
| otherwise = s'
where
s' = take (l + 1) s
getFileContents :: IOStateArrow s XmlTree XmlTree
getFileContents
= applyA ( ( ( getAttrValue a_strict_input
>>>
arr isTrueValue
)
&&&
( getAttrValue transferURI
>>>
getPathFromURI
)
)
>>>
traceValue 2 (\ (b, f) -> "read file " ++ show f ++ " (strict input = " ++ show b ++ ")")
>>>
arrIO (uncurry FILE.getCont)
>>>
( arr (uncurry addError) -- io error occured
|||
arr addTxtContent -- content read
)
)
>>>
addMimeType
getStdinContents :: IOStateArrow s XmlTree XmlTree
getStdinContents
= applyA ( getAttrValue a_strict_input
>>>
arr isTrueValue
>>>
arrIO FILE.getStdinCont
>>>
( arr (uncurry addError) -- io error occured
|||
arr addTxtContent -- content read
)
)
addError :: [(String, String)] -> String -> IOStateArrow s XmlTree XmlTree
addError al e
= issueFatal e
>>>
seqA (map (uncurry addAttr) al)
>>>
setDocumentStatusFromSystemState "accessing documents"
addMimeType :: IOStateArrow s XmlTree XmlTree
addMimeType
= addMime $< ( getAttrValue transferURI
>>>
( uriToMime $< getSysParam xio_mimeTypes )
)
where
addMime mt
= addAttr transferMimeType mt
uriToMime mtt
= arr $ ( \ uri -> extensionToMimeType (drop 1 . takeExtension $ uri) mtt )
addTxtContent :: String -> IOStateArrow s XmlTree XmlTree
addTxtContent c
= replaceChildren (txt c)
>>>
addAttr transferMessage "OK"
>>>
addAttr transferStatus "200"
getHttpContents :: IOStateArrow s XmlTree XmlTree
getHttpContents
= getCont $<< ( getAttrValue transferURI
&&&
( ( getAttrlAsAssoc -- get all attributes of root node
&&&
getAllParamsString -- get all system params
)
>>^ uncurry addEntries -- merge them, attributes overwrite system params
)
)
where
getAttrlAsAssoc -- get the attributes as assoc list
= listA ( getAttrl
>>> ( getName
&&&
xshow getChildren
)
)
getCont uri options
= applyA ( ( traceMsg 2 ( "get HTTP via libcurl, uri=" ++ show uri ++ " options=" ++ show options )
>>>
arrIO0 ( LibCURL.getCont options uri )
)
>>>
( arr (uncurry addError)
|||
arr addContent
)
)
addContent :: (AssocList String String, String) -> IOStateArrow s XmlTree XmlTree
addContent (al, c)
= replaceChildren (txt c)
>>>
seqA (map (uncurry addAttr) al)
getURIContents :: IOStateArrow s XmlTree XmlTree
getURIContents
= getContentsFromString
`orElse`
getContentsFromDoc
where
getContentsFromString
= ( getAttrValue a_source
>>>
isA (isPrefixOf stringProtocol)
)
`guards`
getStringContents
getContentsFromDoc
= ( ( addTransferURI $< getBaseURI
>>>
getCont
)
`when`
( setAbsURI $< ( getAttrValue a_source
>>^
( \ src-> (if null src then "stdin:" else src) ) -- empty document name -> read from stdin
)
)
)
>>>
setDocumentStatusFromSystemState "getURIContents"
setAbsURI src
= ifA ( constA src >>> changeBaseURI )
this
( issueFatal ("illegal URI : " ++ show src) )
addTransferURI uri
= addAttr transferURI uri
getCont
= applyA ( getBaseURI -- compute the handler and call it
>>>
traceValue 2 (("getURIContents: reading " ++) . show)
>>>
getSchemeFromURI
>>>
getProtocolHandler
)
`orElse`
this -- don't change tree, when no handler can be found
setBaseURIFromDoc :: IOStateArrow s XmlTree XmlTree
setBaseURIFromDoc
= perform ( getAttrValue transferURI
>>>
isA (isPrefixOf stringProtocol) -- do not change base URI when reading from a string
>>>
setBaseURI
)
{- |
Read the content of a document.
This routine is usually called from 'Yuuko.Text.XML.HXT.Arrow.ProcessDocument.getDocumentContents'.
The input must be a root node (constructed with 'Yuuko.Text.XML.HXT.Arrow.XmlArrow.root'), usually without children.
The attribute list contains all input parameters, e.g. URI or source file name, encoding preferences, ...
If the source name is empty, the input is read from standard input.
The source is transformed into an absolute URI. If the source is a relative URI, or a file name,
it is expanded into an absolut URI with respect to the current base URI.
The default base URI is of protocol \"file\" and points to the current working directory.
The currently supported protocols are \"http\", \"file\", \"stdin\" and \"string\".
The latter two are internal protocols. An uri of the form \"stdin:\" stands for the content of
the standard input stream.
\"string:some text\" means, that \"some text\" is taken as input.
This internal protocol is used for reading from normal 'String' values.
-}
getXmlContents :: IOStateArrow s XmlTree XmlTree
getXmlContents
= getXmlContents' parseXmlDocEncodingSpec
>>>
setBaseURIFromDoc
getXmlEntityContents :: IOStateArrow s XmlTree XmlTree
getXmlEntityContents
= getXmlContents' parseXmlEntityEncodingSpec
>>>
processChildren removeEncodingSpec
>>>
setBaseURIFromDoc
getXmlContents' :: IOStateArrow s XmlTree XmlTree -> IOStateArrow s XmlTree XmlTree
getXmlContents' parseEncodingSpec
= ( getURIContents
>>>
choiceA
[ isXmlHtmlDoc :-> ( parseEncodingSpec
>>>
filterErrorMsg
>>>
decodeDocument
)
, isTextDoc :-> decodeDocument
, this :-> this
]
>>>
perform ( getAttrValue transferURI
>>>
traceValue 1 (("getXmlContents: content read and decoded for " ++) . show)
)
>>>
traceTree
>>>
traceSource
)
`when`
isRoot
isMimeDoc :: (String -> Bool) -> IOStateArrow s XmlTree XmlTree
isMimeDoc isMT = fromLA $
( ( getAttrValue transferMimeType >>^ stringToLower )
>>>
isA (\ t -> null t || isMT t)
)
`guards` this
isTextDoc, isXmlHtmlDoc :: IOStateArrow s XmlTree XmlTree
isTextDoc = isMimeDoc isTextMimeType
isXmlHtmlDoc = isMimeDoc (\ mt -> isHtmlMimeType mt || isXmlMimeType mt)
-- ------------------------------------------------------------
getEncoding :: IOStateArrow s XmlTree String
getEncoding
= catA [ xshow getChildren -- 1. guess: guess encoding by looking at the first few bytes
>>>
arr guessEncoding
, getAttrValue transferEncoding -- 2. guess: take the transfer encoding
, getAttrValue a_encoding -- 3. guess: take encoding parameter in root node
, getParamString a_encoding -- 4. guess: take encoding parameter in global state
, constA utf8 -- default : utf8
]
>. (head . filter (not . null)) -- make the filter deterministic: take 1. entry from list of guesses
getTextEncoding :: IOStateArrow s XmlTree String
getTextEncoding
= catA [ getAttrValue transferEncoding -- 1. guess: take the transfer encoding
, getAttrValue a_encoding -- 2. guess: take encoding parameter in root node
, getParamString a_encoding -- 3. guess: take encoding parameter in global state
, constA isoLatin1 -- default : no encoding
]
>. (head . filter (not . null)) -- make the filter deterministic: take 1. entry from list of guesses
decodeDocument :: IOStateArrow s XmlTree XmlTree
decodeDocument
= choiceA
[ ( isRoot >>> isXmlHtmlDoc ) :-> ( decodeArr normalizeNL $< getEncoding )
, ( isRoot >>> isTextDoc ) :-> ( decodeArr id $< getTextEncoding )
, this :-> this
]
where
decodeArr :: (String -> String) -> String -> IOStateArrow s XmlTree XmlTree
decodeArr normalizeNewline enc
= maybe notFound found . getDecodingFct $ enc
where
found df
= traceMsg 2 ("decodeDocument: encoding is " ++ show enc)
>>>
( decodeText df $< getAttrValue a_ignore_encoding_errors )
>>>
addAttr transferEncoding enc
notFound
= issueFatal ("encoding scheme not supported: " ++ show enc)
>>>
setDocumentStatusFromSystemState "decoding document"
decodeText df ignoreErrs
= processChildren
( getText -- get the document content
>>> arr df -- decode the text, result is (string, [errMsg])
>>> ( ( (fst >>> normalizeNewline) -- take decoded string, normalize newline and build text node
^>> mkText
)
<+>
( if isTrueValue ignoreErrs
then none -- encoding errors are ignored
else
( arrL snd -- take the error messages
>>>
arr ((enc ++) . (" encoding error" ++)) -- prefix with enc error
>>>
applyA (arr issueErr) -- build issueErr arrow and apply
>>>
none -- neccessary for type match with <+>
)
)
)
)
-- ------------------------------------------------------------
| nfjinjing/yuuko | src/Yuuko/Text/XML/HXT/Arrow/DocumentInput.hs | bsd-3-clause | 11,803 | 312 | 19 | 3,012 | 2,491 | 1,344 | 1,147 | 279 | 2 |
{-# LANGUAGE OverloadedStrings, RecordWildCards, ScopedTypeVariables #-}
-- Reindents the type signature of Haskell functions.
{-# LANGUAGE OverloadedStrings, RecordWildCards, ScopedTypeVariables #-}
-- For use within a text editor like Vim.
module Main where
import Text.Parsec
import qualified Text.Parsec.Token as T (GenTokenParser(..))
import Text.Parsec.Language
import qualified Data.Text.IO as T
import Data.Monoid
import Data.List (intersperse)
-- parse :: Stream s Identity t => Parsec s () a -> SourceName -> s -> Either ParseError a
-- main = case (parse numbers "" "11, 2, 43") of
-- Left err -> print err
-- Right xs -> print (sum xs)
--
-- numbers = commaSep integer
-- type signature parsing
{-
type Identifier = String
data DoubleColon = DoubleColon Int -- ^ position
data TypeParam = TypeParam Identifier (Maybe Comment)
| FuncTypeParam [TypeParam]
data Function = Function Identifier DoubleColon [TypeParam]
-}
T.TokenParser{..} = haskell
data FunctionType = FunctionType String Int [TypeParam]
deriving (Show)
type Comment = Maybe String
data TypeParam =
TypeParam String Comment Int
| FuncTypeParam [TypeParam] Comment Int
deriving (Show)
testparser :: Parsec String () (String, Int, Int, Maybe String)
testparser = do
whiteSpace
f <- identifier
n <- sourceColumn <$> getPosition
symbol "::"
x <- identifier'
n2 <- sourceColumn <$> getPosition
c <- comment
return (x, n,n2, c)
identStart = letter
identLetter = alphaNum <|> oneOf "_'"
-- parses identifiers but does not consume following comment whitespace
identifier' :: Parsec String () String
identifier' = do
x <- identStart
xs <- many identLetter
spaces
return (x:xs)
parser :: Parsec String () FunctionType
parser = do
whiteSpace
f <- identifier
n <- getPosition
symbol "::"
xs <- typeParams
return $ FunctionType f (sourceColumn n) xs
typeParams :: Parsec String () [TypeParam]
typeParams = sepBy (typeParam <|> functionParam) (symbol "->" )
typeParam :: Parsec String () TypeParam
typeParam = do
-- t <- (concat . intersperse " ") <$> (many1 identifier')
t <- manyTill anyChar (try $ string "--") -- TODO CHANGEME
string "--"
n <- getCol
spaces
c <- (comment <* spaces)
return $ TypeParam t c n
comment :: Parsec String () (Maybe String)
comment = do
option Nothing
$ fmap Just (try comment')
comment' = string "--" >> manyTill anyChar (string "\n")
getCol = sourceColumn <$> getPosition
functionParam :: Parsec String () TypeParam
functionParam = do
xs <- between (string "(") (string ")") typeParams
n <- getCol
spaces
c <- comment
return $ FuncTypeParam xs c n
main :: IO ()
main = do
s <- getContents
case (parse parser "" s) of
Left err -> print err
Right (xs ) -> print xs
numbers :: Parsec String () [Integer]
-- numbers = (commaSep haskell) (integer haskell)
numbers = commaSep integer
| danchoi/ftindent | Main.hs | bsd-3-clause | 3,060 | 0 | 11 | 729 | 763 | 390 | 373 | 74 | 2 |
module Language.BCoPL.DataLevel.CompareNat (
-- * Types
Nat (..)
, Judge (..)
-- * Deducer
, deduce1
, deduce2
, deduce3
-- * Session for deriving judgement on comparing 'Nat'
, session1
, session2
, session3
, session1'
, session2'
, session3'
) where
import Language.BCoPL.DataLevel.Peano (Nat(..))
import Language.BCoPL.DataLevel.Derivation (Tree(..),Deducer,sessionGen,sessionGen')
data Judge = LessThan Nat Nat
deriving (Eq)
instance Show Judge where
show (LessThan m n) = unwords [show m,"is less than",show n]
instance Read Judge where
readsPrec _ s = case words s of
n1:"is":"less":"than":n2:_ -> [(LessThan (read n1) (read n2),"")]
_ -> error ("Invalid syntax for 'CompareNat judgement': "++s)
deduce1 :: Deducer Judge
deduce1 j = case j of
LessThan n (S n')
| n == n' -> [ Node ("L-Succ",j) [] ]
LessThan n1 n3 -> [ Node ("L-Trans",j) [j1,j2 ]
| n2 <- [S n1 .. n3]
, j1 <- deduce1 (LessThan n1 n2)
, j2 <- deduce1 (LessThan n2 n3)
]
deduce2 :: Deducer Judge
deduce2 j = case j of
LessThan Z (S _) -> [ Node ("L-Zero",j) [] ]
LessThan (S n1) (S n2) -> [ Node ("L-SuccSucc",j) [j']
| j' <- deduce2 (LessThan n1 n2)
]
_ -> []
deduce3 :: Deducer Judge
deduce3 j = case j of
LessThan n (S n')
| n == n' -> [ Node ("L-Succ",j) [] ]
LessThan n1 (S n2) -> [ Node ("L-SuccR",j) [j']
| j' <- deduce3 (LessThan n1 n2)
]
_ -> []
session1,session2,session3 :: IO ()
session1 = sessionGen ("CompareNat1> ",deduce1)
session2 = sessionGen ("CompareNat2> ",deduce2)
session3 = sessionGen ("CompareNat3> ",deduce3)
session1',session2',session3' :: IO ()
session1' = sessionGen' ("CompareNat1> ",deduce1)
session2' = sessionGen' ("CompareNat2> ",deduce2)
session3' = sessionGen' ("CompareNat3> ",deduce3)
| nobsun/hs-bcopl | src/Language/BCoPL/DataLevel/CompareNat.hs | bsd-3-clause | 2,053 | 0 | 13 | 635 | 753 | 408 | 345 | 51 | 3 |
import Data.Numbers.Primes
decompose :: Int -> [Int]
decompose n = factor primes n
where factor (p:ps) n
| (p*p) > n = [n]
| mod n p == 0 = p : (factor (p:ps) (div n p))
| otherwise = factor ps n
main :: IO ()
main = print (last (decompose 600851475143))
| JacksonGariety/euler.hs | 003.hs | bsd-3-clause | 289 | 0 | 10 | 87 | 160 | 80 | 80 | 9 | 1 |
module Network.Hawk.Internal.Server.Header
( header
, headerSuccess
, headerFail
, timestampMessage
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.Time.Clock.POSIX
import Data.Maybe (catMaybes)
import Network.HTTP.Types.Status (Status, ok200, badRequest400, unauthorized401)
import Network.HTTP.Types.Header (Header, hWWWAuthenticate)
import Network.Hawk.Internal.Types
import Network.Hawk.Internal.Server
import Network.Hawk.Internal.Server.Types
import Network.Hawk.Internal
-- | Generates a suitable @Server-Authorization@ header to send back
-- to the client. Credentials and artifacts would be provided by a
-- previous call to 'authenticateRequest' (or 'authenticate').
--
-- If a payload is supplied, its hash will be included in the header.
header :: AuthResult t -> Maybe PayloadInfo -> (Status, Header)
header (Right a) p = (ok200, (hServerAuthorization, headerSuccess a p))
header (Left e) _ = (status e, (hWWWAuthenticate, headerFail e))
where
status (AuthFailBadRequest _ _) = badRequest400
status (AuthFailUnauthorized _ _ _) = unauthorized401
status (AuthFailStaleTimeStamp _ _ _ _) = unauthorized401
headerSuccess :: AuthSuccess t -> Maybe PayloadInfo -> ByteString
headerSuccess (AuthSuccess creds arts _) payload = hawkHeaderString (catMaybes parts)
where
parts :: [Maybe (ByteString, ByteString)]
parts = [ Just ("mac", mac)
, fmap ((,) "hash") hash
, fmap ((,) "ext") ext]
hash = calculatePayloadHash (scAlgorithm creds) <$> payload
ext = escapeHeaderAttribute <$> haExt arts
mac = serverMac creds HawkResponse (arts { haHash = hash })
headerFail :: AuthFail -> ByteString
headerFail (AuthFailBadRequest e _) = hawkHeaderError e []
headerFail (AuthFailUnauthorized e _ _) = hawkHeaderError e []
headerFail (AuthFailStaleTimeStamp e now creds artifacts) = timestampMessage e now creds
hawkHeaderError :: String -> [(ByteString, ByteString)] -> ByteString
hawkHeaderError e ps = hawkHeaderString (("error", S8.pack e):ps)
timestampMessage :: String -> POSIXTime -> Credentials -> ByteString
timestampMessage e now creds = hawkHeaderError e parts
where
parts = [ ("ts", (S8.pack . show . floor) now)
, ("tsm", calculateTsMac (scAlgorithm creds) now)
]
| rvl/hsoz | src/Network/Hawk/Internal/Server/Header.hs | bsd-3-clause | 2,398 | 0 | 13 | 463 | 670 | 372 | 298 | 40 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
module Plots.Types.Others
( -- * Vertical line range
createlinerangev
, linerangevPlot
, linerangevPlot'
, linerangevPlotL
, linerangevPlotwithPoint
-- * Horizontal line range
, createlinerangeh
, linerangehPlot
, linerangehPlot'
, linerangehPlotL
, linerangehPlotwithPoint
-- * Vertical errorbar
, errorbarvPlot
, errorbarvPlotwithPoint
-- * Horizontal errorbar
, errorbarhPlot
, errorbarhPlotwithPoint
-- * Vertical crossbar
, crossbarvPlot
, crossbarvPlotwithPoint
-- * Horizontal crossbar
, crossbarhPlot
, crossbarhPlotwithPoint
-- * Boxplot
, boxplotvPlot
, boxplothPlot
) where
import Control.Lens hiding (lmap, none, transform,
( # ))
import Control.Monad.State.Lazy
-- import qualified Data.Foldable as F
import Data.Typeable
-- import Data.List
-- import Data.Function
import Diagrams.Prelude
-- import Diagrams.Coordinates.Isomorphic
import Plots.Themes
import Plots.Types
import Plots.API
-- import Plots.Axis
import Plots.Types.Line
import Plots.Types.Scatter
------------------------------------------------------------------------
-- Linerange Vertical
------------------------------------------------------------------------
createlinerangev :: (Double, Double) -> Double -> [(Double, Double)]
createlinerangev (a, b) s = [(a+(s/2), b), (a-(s/2), b)]
linerangevPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> m ()
linerangevPlot a s = linePlot (createlinerangev a s)
linerangevPlot' :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> m ()
linerangevPlot' a s = linePlot (createlinerangev a s)
linerangevPlotL :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
String -> (Double, Double) -> Double -> m ()
linerangevPlotL l a s = linePlotL l (createlinerangev a s)
linerangevPlotwithPoint :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> m ()
linerangevPlotwithPoint a s = do
linePlot' (createlinerangev a s) $ do
plotColor .= purple
addLegendEntry "data 1"
scatterPlot' [a] $ do
plotColor .= purple
plotMarker %= scale 2
------------------------------------------------------------------------
-- Linerange Horizontal
------------------------------------------------------------------------
createlinerangeh :: (Double, Double) -> Double -> [(Double, Double)]
createlinerangeh (a, b) s = [(a, b+(s/2)), (a, b-(s/2))]
linerangehPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> m ()
linerangehPlot a s = linePlot (createlinerangeh a s)
linerangehPlot' :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> m ()
linerangehPlot' a s = linePlot (createlinerangeh a s)
linerangehPlotL :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
String -> (Double, Double) -> Double -> m ()
linerangehPlotL l a s = linePlotL l (createlinerangeh a s)
linerangehPlotwithPoint :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> m ()
linerangehPlotwithPoint a s = do
linePlot' (createlinerangeh a s) $ do
plotColor .= purple
addLegendEntry "data 1"
scatterPlot' [a] $ do
plotColor .= purple
plotMarker %= scale 2
------------------------------------------------------------------------
-- Errorbar Vertical
------------------------------------------------------------------------
errorbarvPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
errorbarvPlot (a,b) s h = do
linePlot' (createlinerangev (a, b) s) $ do
plotColor .= red
addLegendEntry "data 1"
linePlot' (createlinerangeh (a+(s/2), b) h) $ do
plotColor .= red
linePlot' (createlinerangeh (a-(s/2), b) h) $ do
plotColor .= red
errorbarvPlotwithPoint :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
errorbarvPlotwithPoint (a,b) s h = do
linePlot' (createlinerangev (a, b) s) $ do
plotColor .= blue
addLegendEntry "data 1"
linePlot' (createlinerangeh (a+(s/2), b) h) $ do
plotColor .= blue
linePlot' (createlinerangeh (a-(s/2), b) h) $ do
plotColor .= blue
scatterPlot' [(a,b)] $ do
plotColor .= blue
------------------------------------------------------------------------
-- Errorbar Horizontal
------------------------------------------------------------------------
errorbarhPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
errorbarhPlot (a,b) s h = do
linePlot' (createlinerangeh (a, b) s) $ do
plotColor .= red
addLegendEntry "data n"
linePlot' (createlinerangev (a, b+(s/2)) h) $ do
plotColor .= red
linePlot' (createlinerangev (a, b-(s/2)) h) $ do
plotColor .= red
errorbarhPlotwithPoint :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
errorbarhPlotwithPoint (a,b) s h = do
linePlot' (createlinerangeh (a, b) s) $ do
plotColor .= blue
addLegendEntry "data n"
linePlot' (createlinerangev (a, b+(s/2)) h) $ do
plotColor .= blue
linePlot' (createlinerangev (a, b-(s/2)) h) $ do
plotColor .= blue
scatterPlot' [(a,b)] $ do
plotColor .= blue
------------------------------------------------------------------------
-- Crossbar Vertical
------------------------------------------------------------------------
crossbarvPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
crossbarvPlot (a,b) s h = do
linePlot' (createlinerangeh (a, b) h) $ do
plotColor .= red
addLegendEntry "data n"
linePlot' (createlinerangev (a, b+(h/2)) s) $ do
plotColor .= red
linePlot' (createlinerangev (a, b-(h/2)) s) $ do
plotColor .= red
linePlot' (createlinerangeh (a+(s/2), b) h) $ do
plotColor .= red
linePlot' (createlinerangeh (a-(s/2), b) h) $ do
plotColor .= red
crossbarvPlotwithPoint :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
crossbarvPlotwithPoint (a,b) s h = do
linePlot' (createlinerangeh (a, b) h) $ do
plotColor .= blue
addLegendEntry "data n"
linePlot' (createlinerangev (a, b+(h/2)) s) $ do
plotColor .= blue
linePlot' (createlinerangev (a, b-(h/2)) s) $ do
plotColor .= blue
linePlot' (createlinerangeh (a+(s/2), b) h) $ do
plotColor .= blue
linePlot' (createlinerangeh (a-(s/2), b) h) $ do
plotColor .= blue
scatterPlot' [(a,b)] $ do
plotColor .= blue
------------------------------------------------------------------------
-- Crossbar Horizontal --options for colour and legends seperate
------------------------------------------------------------------------
crossbarhPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
crossbarhPlot (a,b) s h = do
linePlot' (createlinerangev (a, b) s) $ do
plotColor .= red
addLegendEntry "data n"
linePlot' (createlinerangev (a, b+(h/2)) s) $ do
plotColor .= red
linePlot' (createlinerangev (a, b-(h/2)) s) $ do
plotColor .= red
linePlot' (createlinerangeh (a+(s/2), b) h) $ do
plotColor .= red
linePlot' (createlinerangeh (a-(s/2), b) h) $ do
plotColor .= red
crossbarhPlotwithPoint :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> m ()
crossbarhPlotwithPoint (a,b) s h = do
linePlot' (createlinerangev (a, b) s) $ do
plotColor .= blue
addLegendEntry "data n"
linePlot' (createlinerangev (a, b+(h/2)) s) $ do
plotColor .= blue
linePlot' (createlinerangev (a, b-(h/2)) s) $ do
plotColor .= blue
linePlot' (createlinerangeh (a+(s/2), b) h) $ do
plotColor .= blue
linePlot' (createlinerangeh (a-(s/2), b) h) $ do
plotColor .= blue
scatterPlot' [(a,b)] $ do
plotColor .= blue
------------------------------------------------------------------------
-- Boxplot Vertical
------------------------------------------------------------------------
boxplotvPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> Double -> m ()
boxplotvPlot (a,b) s1 s2 h = do
crossbarhPlot (a,b) s1 h
linePlot' (createlinerangeh (a-(s1/2), b) (s2-s1)) $ do
plotColor .= red
linePlot' (createlinerangeh (a+(s1/2), b) (s2-s1)) $ do
plotColor .= red
------------------------------------------------------------------------
-- Boxplot Horizontal
------------------------------------------------------------------------
boxplothPlot :: (Typeable b, Renderable (Path V2 Double) b,
MonadState (Axis b c Double) m, BaseSpace c ~ V2) =>
(Double, Double) -> Double -> Double -> Double -> m ()
boxplothPlot (a,b) s h1 h2= do
crossbarhPlot (a,b) s h1
linePlot' (createlinerangeh (a, b1) hmean) $ do
plotColor .= red
linePlot' (createlinerangeh (a, b2) hmean) $ do
plotColor .= red
where b1 = b + (h1/2) + (h2/2)
b2 = b - (h1/2) - (h2/2)
hmean = h2-h1
------------------------------------------------------------------------
-- Bar Plot
------------------------------------------------------------------------
-- $bar
-- Bar plots are different in that you often want to specify the axis
-- name along with the data.
-- barPlot :: (R2Backend, Plotable (Path v n) b, F.Foldable f)
-- => f (String, n) -> AxisState b v n
-- barPlot d = addPlotable $ P.mkBarPlot' d
-- barPlot' :: (R2Backend, Plotable (Path v n) b, F.Foldable f)
-- => f (String, n) -> AxisState b v n
-- barPlot' d s = addPlotable (P.mkBarPlot d) s
-- barPlotL :: (R2Backend, Plotable (Path v n) b, F.Foldable f)
-- => String -> f (String, n) -> AxisState b v n
-- barPlotL s d = addPlotableL s (P.mkBarPlot d)
| bergey/plots | src/Plots/Types/Others.hs | bsd-3-clause | 13,554 | 0 | 14 | 4,464 | 3,953 | 2,054 | 1,899 | 227 | 1 |
import XMonad
import XMonad.Config.Gnome
import XMonad.Actions.CycleWS
import XMonad.Hooks.SetWMName
import XMonad.Layout.NoBorders (smartBorders)
import XMonad.Layout.Spacing (smartSpacing)
import qualified Data.Map as M
myManageHook = composeAll (
[ manageHook gnomeConfig
, className =? "Unity-2d-panel" --> doIgnore
, className =? "Unity-2d-shell" --> doFloat
])
myLayoutHook = smartSpacing 2 $ smartBorders (layoutHook gnomeConfig)
main = do
xmonad $ gnomeConfig {
-- use windows as mod instead of meta
modMask = mod4Mask
, keys = myKeys <+> keys defaultConfig
, terminal = "gnome-terminal"
, manageHook = myManageHook
, startupHook = setWMName "LG3D"
, layoutHook = myLayoutHook
, focusedBorderColor = "#393"
}
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
[ ((modm, xK_p), spawn "dmenu_run -b" )
, ((modm, xK_o), nextScreen)
, ((modm .|. shiftMask, xK_o), shiftNextScreen)
, ((modm, xK_semicolon), toggleWS)
, ((modm, xK_quoteright), moveTo Next HiddenNonEmptyWS)
]
| dgtized/dotfiles | dot/xmonad/xmonad.hs | bsd-3-clause | 1,162 | 0 | 11 | 305 | 296 | 176 | 120 | 27 | 1 |
module Main where
import ABS
(x:i:ni:num_div:obj:i_divides:f:n:primeb:reminder:res:nprimes:fv:the_end) = [1..]
main_ :: Method
main_ [] this wb k =
Assign n (Val (I 1500)) $
Assign x (Sync check_primes [n]) $
k
check_primes :: Method
check_primes [pn] this wb k =
Assign nprimes (Val (I 0)) $
Assign i (Val (I 2)) $
While (ILTE (Attr i) (I pn)) (\k' ->
Assign obj New $
Assign f (Async obj is_prime [i]) $
Await f $
Assign fv (Get f) $
Assign nprimes (Val (Add (Attr nprimes) (Attr fv))) $
Assign i (Val (Add (Attr i) (I 1))) $
k'
) $
Return nprimes wb k
is_prime :: Method
is_prime [pn] this wb k =
Assign i (Val (I 1)) $
Assign ni (Val (I pn)) $
Assign num_div (Val (I 0)) $
While (ILTE (Attr i) (Attr ni)) (\k' ->
Assign obj New $
Assign f (Async obj divides [i,ni]) $
Await f $
Assign i_divides (Get f) $
Assign num_div (Val (Add (Attr num_div) (Attr i_divides))) $
Assign i (Val (Add (Attr i) (I 1))) $
k'
) $
If (IEq (Attr num_div) (I 2))
(\k' -> Assign primeb (Val (I 1)) k')
(\k' -> Assign primeb (Val (I 0)) k') $
Return primeb wb k
divides :: Method
divides [pd, pn] this wb k =
Assign reminder (Val (Mod (I pn) (I pd)) ) $
If (IEq (Attr reminder) (I 0))
(\k' -> Assign res (Val (I 1)) k')
(\k' -> Assign res (Val (I 0)) k' ) $
Return res wb k
main' :: IO ()
main' = run' 9999999999999999 main_ (head the_end)
main :: IO ()
main = printHeap =<< run 9999999999999999 main_ (head the_end)
| abstools/abs-haskell-formal | benchmarks/5_primes_range/progs/1500.hs | bsd-3-clause | 1,528 | 0 | 20 | 408 | 916 | 457 | 459 | 51 | 1 |
module Database.Seakale.Request
( query
, query_
, queryWith
, execute
, execute_
, executeMany
, executeMany_
, returning
, returningWith
, returning_
, returningWith_
, MonadRequest
, throwSeakaleError
, getBackend
) where
import Database.Seakale.Request.Internal (MonadRequest)
import Database.Seakale.FromRow
import Database.Seakale.ToRow
import Database.Seakale.Types
import qualified Database.Seakale.Request.Internal as I
-- | Replace holes in the query with the provided values and send it to the
-- database. This is to be used for @SELECT@ queries.
query :: (MonadRequest b m, ToRow b n r, FromRow b n' s) => Query n -> r
-> m [s]
query = queryWith fromRow
-- | Like 'query' but the query should not have any hole.
query_ :: (MonadRequest b m, FromRow b n r) => Query Zero -> m [r]
query_ req = query req ()
-- | Provide a way to specify a custom parser for 'query'.
queryWith :: (MonadRequest b m, ToRow b n r) => RowParser b n' s -> Query n -> r
-> m [s]
queryWith parser req dat = do
backend <- getBackend
(cols, rows) <- I.query $ formatQuery req $ toRow backend dat
case parseRows parser backend cols rows of
Left err -> throwSeakaleError $ RowParseError err
Right xs -> return xs
-- | Replace holes in the query with the provided values, send it to the
-- database and return the number of rows affected. This is to be used with
-- @DELETE@, @UPDATE@ and @INSERT@ queries (without any @RETURNING@ clause).
execute :: (MonadRequest b m, ToRow b n r) => Query n -> r -> m Integer
execute req dat = do
backend <- getBackend
I.execute $ formatQuery req $ toRow backend dat
-- | Like 'execute' but the query should not have any hole.
execute_ :: MonadRequest b m => Query Zero -> m Integer
execute_ req = I.execute $ formatQuery req Nil
-- | Like 'execute' but for a 'RepeatQuery' where a piece of the query is
-- repeated as many times as the number of values of type 'r2'.
executeMany :: (MonadRequest b m, ToRow b n1 r1, ToRow b n2 r2, ToRow b n3 r3)
=> RepeatQuery n1 n2 n3 -> r1 -> r3 -> [r2] -> m Integer
executeMany req bdat adat dat = do
backend <- getBackend
I.execute $ formatMany req
(toRow backend bdat) (toRow backend adat) (map (toRow backend) dat)
-- | Like 'executeMany' but the query should not have any hole before and after
-- the repeating piece.
executeMany_ :: (MonadRequest b m, ToRow b n r)
=> RepeatQuery Zero n Zero -> [r] -> m Integer
executeMany_ req dat = executeMany req () () dat
-- | Replace holes in a 'RepeatQuery' and send it to the database. This is to be
-- used for @INSERT@ queries with a @RETURNING@ clause.
returning :: ( MonadRequest b m, ToRow b n1 r1, ToRow b n2 r2, ToRow b n3 r3
, FromRow b n s )
=> RepeatQuery n1 n2 n3 -> r1 -> r3 -> [r2] -> m [s]
returning = returningWith fromRow
-- | Provide a way to a custom parser for 'returning'.
returningWith :: ( MonadRequest b m, ToRow b n1 r1, ToRow b n2 r2, ToRow b n3 r3
, FromRow b n s )
=> RowParser b n s -> RepeatQuery n1 n2 n3 -> r1 -> r3 -> [r2]
-> m [s]
returningWith parser req bdat adat dat = do
backend <- getBackend
(cols, rows) <- I.query $ formatMany req
(toRow backend bdat) (toRow backend adat) (map (toRow backend) dat)
case parseRows parser backend cols rows of
Left err -> throwSeakaleError $ RowParseError err
Right xs -> return xs
-- | Like 'returning' but the query should not have any hole before and after
-- the repeating piece.
returning_ :: (MonadRequest b m, ToRow b n r, FromRow b n' s)
=> RepeatQuery Zero n Zero -> [r] -> m [s]
returning_ req dat = returningWith fromRow req () () dat
-- | Like 'returningWith' but the query should not have any hole before and
-- after the repeating piece.
returningWith_ :: (MonadRequest b m, ToRow b n r, FromRow b n' s)
=> RowParser b n' s -> RepeatQuery Zero n Zero -> [r] -> m [s]
returningWith_ parser req dat = returningWith parser req () () dat
| thoferon/seakale | src/Database/Seakale/Request.hs | bsd-3-clause | 4,084 | 0 | 13 | 977 | 1,211 | 622 | 589 | 69 | 2 |
module General.GetOpt(
OptDescr(..), ArgDescr(..),
getOpt,
fmapFmapOptDescr,
showOptDescr,
mergeOptDescr,
removeOverlap,
optionsEnum,
optionsEnumDesc
) where
import qualified System.Console.GetOpt as O
import System.Console.GetOpt hiding (getOpt)
import qualified Data.HashSet as Set
import Data.Maybe
import Data.Either
import Data.List.Extra
getOpt :: [OptDescr (Either String a)] -> [String] -> ([a], [String], [String])
getOpt opts args = (flagGood, files, flagBad ++ errs)
where (flags, files, errs) = O.getOpt O.Permute opts args
(flagBad, flagGood) = partitionEithers flags
fmapFmapOptDescr :: (a -> b) -> OptDescr (Either String a) -> OptDescr (Either String b)
fmapFmapOptDescr f = fmap (fmap f)
showOptDescr :: [OptDescr a] -> [String]
showOptDescr xs = concat
[ if nargs <= 26 then [" " ++ args ++ replicate (28 - nargs) ' ' ++ desc]
else [" " ++ args, replicate 30 ' ' ++ desc]
| Option s l arg desc <- xs
, let args = intercalate ", " $ map (short arg) s ++ map (long arg) l
, let nargs = length args]
where short NoArg{} x = "-" ++ [x]
short (ReqArg _ b) x = "-" ++ [x] ++ " " ++ b
short (OptArg _ b) x = "-" ++ [x] ++ "[" ++ b ++ "]"
long NoArg{} x = "--" ++ x
long (ReqArg _ b) x = "--" ++ x ++ "=" ++ b
long (OptArg _ b) x = "--" ++ x ++ "[=" ++ b ++ "]"
-- | Remove flags from the first field that are present in the second
removeOverlap :: [OptDescr b] -> [OptDescr a] -> [OptDescr a]
removeOverlap bad = mapMaybe f
where
short = Set.fromList $ concat [x | Option x _ _ _ <- bad]
long = Set.fromList $ concat [x | Option _ x _ _ <- bad]
f (Option a b c d) | null a2 && null b2 = Nothing
| otherwise = Just $ Option a2 b2 c d
where a2 = filter (not . flip Set.member short) a
b2 = filter (not . flip Set.member long) b
mergeOptDescr :: [OptDescr (Either String a)] -> [OptDescr (Either String b)] -> [OptDescr (Either String (Either a b))]
mergeOptDescr xs ys = map (fmapFmapOptDescr Left) xs ++ map (fmapFmapOptDescr Right) ys
optionsEnum :: (Enum a, Bounded a, Show a) => [OptDescr (Either String a)]
optionsEnum = optionsEnumDesc [(x, "Flag " ++ lower (show x) ++ ".") | x <- enumerate]
optionsEnumDesc :: Show a => [(a, String)] -> [OptDescr (Either String a)]
optionsEnumDesc xs = [Option "" [lower $ show x] (NoArg $ Right x) d | (x,d) <- xs]
| ndmitchell/shake | src/General/GetOpt.hs | bsd-3-clause | 2,509 | 0 | 15 | 665 | 1,094 | 573 | 521 | 48 | 6 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module KMC.SymbolicSST.ActionSST(ActionSST, ConstOrAnyLab(..), actionToSST) where
import Data.Functor.Identity
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set as S
import KMC.Kleenex.Actions (RegAction(..))
import KMC.Kleenex.Syntax (RegIdent(..))
import KMC.RangeSet (RangeSet)
import KMC.SymbolicFST (FST(..))
import qualified KMC.SymbolicFST as FST
import KMC.SymbolicFST.ActionMachine (ActionMachine, CodeInputLab(..), DecodeFunc(..))
import KMC.SymbolicSST
import KMC.Theories
{-
Action machines are deterministic by construction, and thus may be seen as a
deterministic SST with only one register. Register effects adjoined to the
output alphabet can also be interpreted as SST actions.
-}
type ActionSST st digit sigma var
= SST st (ConstOrAnyLab digit) (DecodeFunc (RangeSet sigma) digit (Identity sigma)) var
-------------
-- Predicates
-------------
-- | Single-symbol data type representing labels for action SSTs
data ConstOrAnyLab b = ConstLab b -- ^ Read exactly this symbol
| AnyLab -- ^ Read any symbol
deriving (Eq, Ord)
instance (Eq b) => SetLike (ConstOrAnyLab b) b where
member _ AnyLab = True
member x (ConstLab y) = x == y
-----------------
-- SST generation
-----------------
actionToSST :: forall st sigma digit.
(Ord st, Ord sigma, Enum sigma, Bounded sigma, Enum digit, Bounded digit)
=> ActionMachine st sigma RegAction digit -> ActionSST (st, Int) digit sigma Int
actionToSST actM = construct' (fstI actM, 0) edges outs
where
regs = M.fromList [ (r, maxBound - i) | r <- S.toList (registers actM) | i <- [0..] ]
:: M.Map RegIdent Int
(edges, outs) = go (S.singleton (fstI actM, 0)) S.empty [] []
go ws states es os
| S.null ws = (es, os)
| (s, ws') <- S.deleteFindMin ws, S.member s states = go ws' states es os
| (s@(q,h),ws') <- S.deleteFindMin ws =
let (y, q') = followEps actM q
(h', kappa) = interp regs h y
:: (Int, RegisterUpdate Int (DecodeFunc (RangeSet sigma) digit (Identity sigma)))
os' = if S.member q' (fstF actM) then
[(s, evalUpdateStringFunc [error "input function emitted along epsilon path"]
$ fromMaybe [VarA 0] (M.lookup 0 kappa))]
else []
es' = [ (s, ps, composeRegisterUpdate kappa ru, s') | (ps, ru, s') <- next actM regs (q',h') ]
ws'' = S.fromList [ s' | (_, _, _, s') <- es' ]
states' = S.insert s states
in go (S.union ws'' ws') states' (es' ++ es) (os' ++ os)
-- | Extract all occurrences of register identifiers in an action machine
registers :: ActionMachine st sigma RegAction digit -> S.Set RegIdent
registers actM = S.unions [ ext l | (_, l, _) <- FST.edgesToList $ fstE actM ]
where
ext (Left (_, DecodeArg _)) = S.empty
ext (Left (_, DecodeConst xs)) = S.fromList $ concatMap extAct [ act | Right act <- xs ]
ext (Right xs) = S.fromList $ concatMap extAct [ act | Right act <- xs ]
extAct Push = []
extAct (Pop r) = [r]
extAct (Write r) = [r]
-- | Interpret a sequence of action symbols as a register update
interp :: M.Map RegIdent Int -> Int -> [Either sigma RegAction]
-> (Int, RegisterUpdate Int (DecodeFunc (RangeSet sigma) digit (Identity sigma)))
interp regs = go
where
go h [] = (h, M.empty)
go h (Left a:xs) =
let (h', kappa) = go h xs
kappa' = M.singleton h [VarA h, ConstA [a]]
in (h', composeRegisterUpdate kappa' kappa)
go h (Right Push:xs) =
let (h', kappa) = go (h+1) xs
in (h', kappa)
go h (Right (Pop r):xs) =
let (h', kappa) = go (h-1) xs
kappa' = M.fromList [(h, []), (regs M.! r, [VarA h])]
in (h', composeRegisterUpdate kappa' kappa)
go h (Right (Write r):xs) =
let (h', kappa) = go h xs
kappa' = M.fromList [(regs M.! r, []), (h, [VarA h, VarA $ regs M.! r])]
in (h', composeRegisterUpdate kappa' kappa)
followEps :: (Ord st) => ActionMachine st sigma act digit -> st -> ([Either sigma act], st)
followEps actM q =
case FST.fstEvalEpsilonEdges actM q of
[] -> ([], q)
[(out, q')] -> let (out', q'') = followEps actM q' in (out ++ out', q'')
_ -> error "non-deterministic action machine"
next :: (Ord st)
=> ActionMachine st sigma RegAction digit
-> M.Map RegIdent Int
-> (st, Int)
-> [([ConstOrAnyLab digit]
,RegisterUpdate Int (DecodeFunc (RangeSet sigma) digit (Identity sigma))
,(st, Int))]
next actM regs (q, h) = do
(p, f, q'') <- fromMaybe [] (M.lookup q (FST.eForward . fstE $ actM))
let ps = case p of InputAny k -> replicate k AnyLab
InputConst bs -> map ConstLab bs
let (us, q') = followEps actM q''
let (h'', kappa) = case f of
DecodeConst c -> interp regs h c
DecodeArg es -> (h, M.singleton h [VarA h, FuncA (DecodeArg es)])
let (h', kappa') = interp regs h'' us
return (ps, composeRegisterUpdate kappa kappa', (q', h'))
| diku-kmc/repg | src/KMC/SymbolicSST/ActionSST.hs | mit | 5,408 | 1 | 19 | 1,479 | 2,062 | 1,101 | 961 | 98 | 5 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Spec.Serializations where
import Data.Aeson
import Lib
import qualified Maia.Aeson.Default as Default
import qualified Maia.Example.Api as Ex
import Maia.Lookup
import Maia.Request
import Maia.Response
import qualified Spec.Serializations.NullCollapse as NullCollapse
import Test.HUnit
import Test.Tasty
import qualified Test.Tasty.HUnit as Hu
tests :: TestTree
tests =
testGroup "Serializations"
[ requestSerializations
, NullCollapse.tests
]
-- Exercises anticipated serialization and printer/parser loop
szTest ::
forall t e r .
(Ex.TestHandler t, Default.DefaultSerializer t) =>
String ->
Lookup t e r -> Value -> Value -> TestTree
szTest nm lk expectedReq expectedResp =
let
req :: Request t
req = request lk
resp :: Response t
resp = Ex.runTestHandler req
in testGroup nm
[ Hu.testCase "request sz" (assert (ReqJsonIs req expectedReq))
, Hu.testCase "response sz" (assert (RespJsonIs resp expectedResp))
, Hu.testCase "request parses" (assert (RoundTripReqEquality req))
, Hu.testCase "response parses" (assert (RoundTripRespEquality resp))
]
requestSerializations :: TestTree
requestSerializations =
testGroup "Lookup requests"
[ testGroup "Of NonType"
[ let
lk :: Lookup' Ex.NonType ()
lk = pure ()
exReq = object []
exResp = object []
in szTest "unit" lk exReq exResp
]
, testGroup "Of Location"
[ let
lk = Ex.latitude
exReq = object ["latitude" .= True]
exResp = object ["latitude" .= Number 0.0]
in szTest "latitude" lk exReq exResp
, let
lk = Ex.longitude
exReq = object ["longitude" .= True]
exResp = object ["longitude" .= Number 0.0]
in szTest "longitude" lk exReq exResp
, let
lk = (,) <$> Ex.latitude <*> Ex.longitude
exReq = object ["longitude" .= True, "latitude" .= True]
exResp = object ["longitude" .= Number 0.0, "latitude" .= Number 0.0]
in szTest "both" lk exReq exResp
]
, testGroup "Of City"
[ let
lk = Ex.name
exReq = object ["name" .= True]
exResp = object ["name" .= String "Atlanta"]
in szTest "name" lk exReq exResp
, let
lk = Ex.coordinates (pure ())
exReq = object ["coordinates" .= object []]
exResp = object ["coordinates" .= object []]
in szTest "coordinates, empty" lk exReq exResp
, let
lk = Ex.coordinates Ex.latitude
exReq = object ["coordinates" .= object ["latitude" .= True]]
exResp = object ["coordinates" .= object ["latitude" .= Number 33.749]]
in szTest "coordinates, latitude" lk exReq exResp
, let
lk = Ex.coordinates ((,) <$> Ex.latitude <*> Ex.longitude)
exReq = object [ "coordinates" .=
object [ "latitude" .= True
, "longitude" .= True
]]
exResp = object [ "coordinates" .=
object [ "latitude" .= Number 33.749
, "longitude" .= Number 84.388
]
]
in szTest "coordinates, both" lk exReq exResp
]
, testGroup "Of Person"
[ let
lk = Ex.firstName
exReq = object ["firstName" .= True]
exResp = object ["firstName" .= String "Joseph"]
in szTest "firstName" lk exReq exResp
, let
lk = Ex.lastName
exReq = object ["lastName" .= True]
exResp = object ["lastName" .= String "Abrahamson"]
in szTest "lastName" lk exReq exResp
, let
lk = Ex.hometown $ do
nm <- Ex.name
crd <- Ex.coordinates $ do
lat <- Ex.latitude
lon <- Ex.longitude
return (lat, lon)
return (nm, crd)
exReq =
object [ "hometown" .=
object [ "name" .= True
, "coordinates" .= object [ "latitude" .= True
, "longitude" .= True
]
]
]
exResp =
object [ "hometown" .=
object [ "the" .=
object [ "name" .= String "Atlanta"
, "coordinates" .= object [ "latitude" .= Number 33.7490
, "longitude" .= Number 84.3880
]
]
]
]
in szTest "hometown name and coordinates" lk exReq exResp
, let
lk =
Ex.hometown $ Ex.mayor $
Ex.hometown $ Ex.mayor $
Ex.hometown $ Ex.mayor $ pure ()
htmy x = object ["hometown" .= object [ "mayor" .= x]]
htmyResp x = object ["hometown" .= object ["the" .= object [ "mayor" .= object ["the" .= x]]]]
exReq = htmy (htmy (htmy (object [])))
exResp = htmyResp (htmyResp (htmyResp (object [])))
in szTest "mayor loop" lk exReq exResp
]
, testGroup "Of Api"
[ let
lk1 = subLookup (Ex.getCity "Atlanta") (pure ())
lk2 = subLookup (Ex.getCity "Atlanta") Ex.name
lk3 = subLookup (Ex.getCity "Fakeville") (pure ())
lk4 = subLookup (Ex.getCity "DoesNotExist") (pure ())
lk = (,,,) <$> lk1 <*> lk2 <*> lk3 <*> lk4
exReq =
object ["getCity" .=
-- NOTE: These have to be in Ord-order on args to get Value-equality
[ toJSON (String "Atlanta", object ["name" .= True])
, toJSON (String "DoesNotExist", object [])
, toJSON (String "Fakeville", object [])
]
]
exResp =
object ["getCity" .=
-- NOTE: These have to be in Ord-order on args to get Value-equality
[ toJSON ( String "Atlanta"
, object ["the" .= object ["name" .= String "Atlanta"]]
)
, toJSON ( String "DoesNotExist"
, Null
)
, toJSON ( String "Fakeville"
, object ["the" .= object []]
)
]
]
in szTest "getCity" lk exReq exResp
, let
lk = Ex.getAllCities (withErr Ex.name)
exReq =
object ["getAllCities" .= object ["name" .= True]]
exResp =
object ["getAllCities" .=
object [ "ok" .= [ object ["name" .= String "Atlanta"]
, object ["name" .= String "Fakeville"]
]
]
]
in szTest "getAllCities (error ok)" lk exReq exResp
, let
lk = Ex.getCurrentUser (withErr Ex.firstName)
exReq =
object ["getCurrentUser" .= object ["firstName" .= True]]
exResp =
object ["getCurrentUser" .= object ["err" .= String "NotAuthorized"]]
in szTest "getAllCities (error ok)" lk exReq exResp
]
]
| tel/haskell-maia | maia-aeson/test/Spec/Serializations.hs | mpl-2.0 | 7,751 | 0 | 25 | 3,093 | 2,015 | 1,029 | 986 | 165 | 1 |
module Main where
import Graphics.UI.WXCore
import Graphics.UI.WX
main :: IO ()
main
= start gui
gui :: IO ()
gui
= do f <- frame [text := "Process test"]
p <- panel f [] -- panel for tab-management etc.
input <- comboBox p [processEnter := True, text := "cmd"]
output <- textCtrlRich p [bgcolor := black, textColor := red, font := fontFixed{ _fontSize = 12 }]
stop_ <- button p [text := "kill", enabled := False]
focusOn input
textCtrlSetEditable output False
set f [layout := container p $
margin 10 $ column 5 [fill (widget output)
,row 5 [hfill (widget input), widget stop_]]
,clientSize := sz 600 400
]
let message txt = appendText output txt
set input [on command := startProcess f input stop_ message]
return ()
where
startProcess f input stop_ message
= do txt <- get input text
appendText input txt
(send,_process,pid) <- processExecAsyncTimed f txt True {- process all input on termination -}
(onEndProcess f input stop_ message) (onReceive message) (onReceive message)
let sendLn txt_ = send (txt_ ++ "\n")
if (pid /= 0)
then do message ("-- start process: '" ++ txt ++ "' --\n")
set input [on command := sendCommand input sendLn]
set stop_ [enabled := True, on command := unitIO (kill pid wxSIGKILL)]
else return ()
sendCommand input send
= do txt_ <- get input text
count <- comboBoxGetCount input
appendText input txt_
set input [selection := count]
_ <- send txt_
return ()
onEndProcess f input stop_ message exitcode
= do message ("\n-- process ended with exitcode " ++ show exitcode ++ " --\n")
set input [on command := startProcess f input stop_ message]
set stop_ [enabled := False, on command := return ()]
onReceive message txt_ _streamStatus
= message txt_
| jacekszymanski/wxHaskell | samples/wx/Process.hs | lgpl-2.1 | 2,164 | 0 | 17 | 774 | 716 | 340 | 376 | 46 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2013-15 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Succinct.Dictionary.Partitioned
( Partitioned(..)
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
import Data.Foldable
import Data.Monoid
import Data.Traversable
#endif
import Succinct.Dictionary.Builder
import Succinct.Dictionary.Class
-- | A partitioned succinct dictionary only supports 'select0' and 'select1' operations
--
-- This is sufficient to implement LOUDS with double-indexing
data Partitioned t = PE | P0 t t | P1 t t
deriving (Eq,Ord,Show)
instance Functor Partitioned where
fmap _ PE = PE
fmap f (P0 r0 r1) = P0 (f r0) (f r1)
fmap f (P1 r0 r1) = P1 (f r0) (f r1)
instance Foldable Partitioned where
foldMap _ PE = mempty
foldMap f (P0 r0 r1) = f r0 `mappend` f r1
foldMap f (P1 r0 r1) = f r0 `mappend` f r1
instance Traversable Partitioned where
traverse _ PE = pure PE
traverse f (P0 r0 r1) = P0 <$> f r0 <*> f r1
traverse f (P1 r0 r1) = P1 <$> f r0 <*> f r1
instance Ranked t => Select0 (Partitioned t) where
select0 PE _ = error "Partitioned.select0: empty"
select0 (P0 r0 r1) i = select1 r1 (rank_ r0 i) + i
select0 (P1 r0 r1) i = select1 r1 (rank_ r0 i + 1) + i
instance Ranked t => Select1 (Partitioned t) where
select1 PE _ = error "Partitioned.select1: empty"
select1 (P0 r0 r1) i = select1 r0 (rank_ r1 i + 1) + i
select1 (P1 r0 r1) i = select1 r0 (rank_ r1 i) + i
data BP a b
= BE !(Maybe Bool) a b
| BT !Bool a b !Bool
p :: Bool -> a -> a -> Partitioned a
p False = P0
p True = P1
instance Buildable Bool a => Buildable Bool (Partitioned a) where
builder = Builder $ case builder of
Builder (Building k h z) -> Building stop step start where
start = BE Nothing <$> z <*> z
step (BE Nothing x y) b = return $ BE (Just b) x y
step (BE (Just b) x y) c = return $ BT b x y c
step (BT b x y True) c = do
y' <- h y (not c)
return $ BT b x y' c
step (BT b x y False) c = do
x' <- h x c
return $ BT b x' y c
stop (BE Nothing _ _) = return PE
stop (BE (Just b) x y) = p b <$> k x <*> k y
stop (BT b x y False) = do
x' <- h x True
p b <$> k x' <*> k y
stop (BT b x y True) = do
y' <- h y True
p b <$> k x <*> k y'
| Gabriel439/succinct | src/Succinct/Dictionary/Partitioned.hs | bsd-2-clause | 2,697 | 0 | 17 | 689 | 1,070 | 532 | 538 | 65 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Arrow.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:47
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module DiagramScene.Arrow (
Qarrow(..)
,arrow_delete
,setArrowColor
,updatePosition
,arrowPaint, arrowBoundingRect, arrowShape
) where
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core
import Qtc.Classes.Gui
import Qtc.Classes.Gui_h
import Qth.Core
import Qtc.ClassTypes.Core
import Qtc.ClassTypes.Gui
import Qtc.Core.Base
import Qtc.Gui.Base
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
import Qtc.Enums.Core.Qt
import Qtc.Core.QRectF
import Qtc.Core.QPolygonF
import Qtc.Core.QLineF
import Qtc.Enums.Core.QLineF
import Qtc.Core.QMatrix
import Qtc.Gui.QPainterPath
import Qtc.Gui.QColor
import Qtc.Gui.QPen
import Qtc.Gui.QBrush
import Qtc.Gui.QPainter
import Qtc.Gui.QGraphicsItem
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Gui.QGraphicsLineItem
import Qtc.Gui.QGraphicsLineItem_h
import Qtc.Gui.QGraphicsPolygonItem
import Qtc.Gui.QGraphicsScene
import Data.IORef
import DiagramScene.ArrowType
class Qarrow x1 where
arrow :: Int -> Int -> x1 -> IO Arrow
instance Qarrow (QGraphicsPolygonItem (), QGraphicsPolygonItem ()) where
arrow xs xe (x1, x2)
= do
dlio <- qGraphicsLineItem_nf ()
arrow_s dlio xs xe x1 x2
instance Qarrow (QGraphicsPolygonItem (), QGraphicsPolygonItem (), QGraphicsItem a) where
arrow xs xe (x1, x2, x3)
= do
dlio <- qGraphicsLineItem_nf (x3)
arrow_s dlio xs xe x1 x2
instance Qarrow (QGraphicsPolygonItem (), QGraphicsPolygonItem (), QGraphicsItem a, QGraphicsScene b) where
arrow xs xe (x1, x2, x3, x4)
= do
tso <- qCast_QGraphicsScene x4
dlio <- qGraphicsLineItem_nf (x3, tso)
arrow_s dlio xs xe x1 x2
arrow_s :: QGraphicsLineItem () -> Int -> Int -> QGraphicsPolygonItem () -> QGraphicsPolygonItem () -> IO Arrow
arrow_s dlio nava nave sdi edi
= do
setFlag dlio ((eItemIsSelectable::GraphicsItemFlag), True)
tb <- qBrush eblack
setPen dlio =<< qPen (tb, 2::Double, eSolidLine, eRoundCap, eRoundJoin)
ar_cl_io <- newIORef =<< qColor eblack
ar_ah <- newIORef =<< qPolygonF ()
setHandler dlio "(int)type()" arrowtype
return $ Arrow dlio nava nave sdi edi ar_cl_io ar_ah
arrow_delete :: Arrow -> IO ()
arrow_delete a
= do
qGraphicsLineItem_delete (ar_o a)
setArrowColor :: QGraphicsLineItem () -> QColor () -> IO ()
setArrowColor li c
= do
cp <- pen li ()
setColor cp c
setPen li cp
updatePosition :: Arrow -> IO ()
updatePosition a
= do
let ao = ar_o a
smp <- mapFromItem ao ((ar_startItem a), 0::Double, 0::Double)
emp <- mapFromItem ao ((ar_endItem a), 0::Double, 0::Double)
setLine ao $ lineP (smp, emp)
arrowPaint :: Arrow -> QGraphicsLineItem () -> QPainter () -> QStyleOptionGraphicsItem () -> QWidget () -> IO ()
arrowPaint a ai ptr sgi w
= do
let si = ar_startItem a
ei = ar_endItem a
ao = ar_o a
cw <- collidesWithItem si ei
if (cw)
then
return ()
else
do
cp <- pen (ar_o a) ()
cc <- color cp ()
cb <- qBrush cc
setPen ptr cp
setBrush ptr cb
sp <- pos si ()
ep <- pos ei ()
eg <- polygon ei ()
eps <- qpoints eg ()
cl <- qLineF (sp, ep)
(it, ip) <- gip cl ep (ep + (head eps)) (tail eps)
if (it == eBoundedIntersection)
then
do
let nl = lineP (ip, sp)
ta = acos (dx nl / len nl)
angle = if (dy nl >= 0) then (pi * 2) - ta else ta
as = 20.0 :: Double
pd3 = pi / (3 :: Double)
ap1 = ip + pointF ((sin (angle + pd3)) * as) ((cos (angle + pd3)) * as)
ap2 = ip + pointF ((sin (angle + pi - pd3)) * as) ((cos (angle + pi - pd3)) * as)
setLine ao nl
arrowHead <- qPolygonFL [ip, ap1, ap2]
modifyIORef (ar_head a) (\_ -> arrowHead)
drawLine ptr nl
drawPolygon ptr arrowHead
iss <- isSelected ai ()
if (iss)
then
do
setPen ptr =<< qPen (cb, (1::Double), eDashLine)
nsl <- qqline ai ()
qtranslate nsl ((0::Double), (4::Double))
qdrawLine ptr nsl
qtranslate nsl ((0::Double), ((-8)::Double))
qdrawLine ptr nsl
else
return ()
else
return ()
where
gip _ _ _ [] = return (eNoIntersection, pointF 0.0 0.0)
gip cl ep p1 teps
= do
let p2 = ep + (head teps)
pl = lineP (p1, p2)
(it, ip) <- qintersect cl pl
if (it == eBoundedIntersection)
then return (it, ip)
else gip cl ep p2 (tail teps)
arrowBoundingRect :: Arrow -> QGraphicsLineItem () -> IO (QRectF ())
arrowBoundingRect a li
= do
tw <- pen li () >>= \p ->
widthF p ()
tl <- qline li ()
let extra = (tw + (20 :: Double)) / (2 :: Double)
tsize = sizeF ((x $ p2 tl) - (x $ p1 tl)) ((y $ p2 tl) - (y $ p1 tl))
ar <- qRectF (p1 tl, tsize) >>= \r ->
qqnormalized r () >>= \nr ->
qqadjusted nr ((-extra), (-extra), extra, extra)
mdxl <- qleft ar ()
mdxt <- qtop ar ()
mdxw <- qwidth ar ()
mdxh <- qheight ar ()
return ar
arrowShape :: Arrow -> QGraphicsLineItem () -> IO (QPainterPath ())
arrowShape a li
= do
pth <- shape_h li ()
addPolygon pth =<< readIORef (ar_head a)
return pth
| uduki/hsQt | examples/DiagramScene/Arrow.hs | bsd-2-clause | 5,701 | 0 | 24 | 1,523 | 2,183 | 1,114 | 1,069 | 161 | 7 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
module Data.HashTable.Weak.Internal.Linear.Bucket
( Bucket,
newBucketArray,
newBucketSize,
emptyWithSize,
growBucketTo,
snoc,
size,
lookup,
delete,
toList,
fromList,
mapM_,
foldM,
expandBucketArray,
expandArray,
nelemsAndOverheadInWords,
bucketSplitSize
) where
------------------------------------------------------------------------------
import Control.Monad hiding (foldM, mapM_)
import qualified Control.Monad
import Control.Monad.ST (ST)
#ifdef DEBUG
import Data.HashTable.Weak.Internal.Utils (unsafeIOToST)
#endif
import Data.HashTable.Weak.Internal.Array
import Data.Maybe (fromMaybe)
import Data.STRef
import Prelude hiding (lookup, mapM_)
------------------------------------------------------------------------------
import Data.HashTable.Weak.Internal.UnsafeTricks
#ifdef DEBUG
import System.IO
#endif
type Bucket s k v = Key (Bucket_ s k v)
------------------------------------------------------------------------------
data Bucket_ s k v = Bucket { _bucketSize :: {-# UNPACK #-} !Int
, _highwater :: {-# UNPACK #-} !(STRef s Int)
, _keys :: {-# UNPACK #-} !(MutableArray s k)
, _values :: {-# UNPACK #-} !(MutableArray s v)
}
------------------------------------------------------------------------------
bucketSplitSize :: Int
bucketSplitSize = 16
------------------------------------------------------------------------------
newBucketArray :: Int -> ST s (MutableArray s (Bucket s k v))
newBucketArray k = newArray k emptyRecord
------------------------------------------------------------------------------
nelemsAndOverheadInWords :: Bucket s k v -> ST s (Int,Int)
nelemsAndOverheadInWords bKey = do
if (not $ keyIsEmpty bKey)
then do
!hw <- readSTRef hwRef
let !w = sz - hw
return (hw, constOverhead + 2*w)
else
return (0, 0)
where
constOverhead = 8
b = fromKey bKey
sz = _bucketSize b
hwRef = _highwater b
------------------------------------------------------------------------------
emptyWithSize :: Int -> ST s (Bucket s k v)
emptyWithSize !sz = do
!keys <- newArray sz undefined
!values <- newArray sz undefined
!ref <- newSTRef 0
return $ toKey $ Bucket sz ref keys values
------------------------------------------------------------------------------
newBucketSize :: Int
newBucketSize = 4
------------------------------------------------------------------------------
expandArray :: a -- ^ default value
-> Int -- ^ new size
-> Int -- ^ number of elements to copy
-> MutableArray s a -- ^ old array
-> ST s (MutableArray s a)
expandArray def !sz !hw !arr = do
newArr <- newArray sz def
cp newArr
where
cp !newArr = go 0
where
go !i
| i >= hw = return newArr
| otherwise = do
readArray arr i >>= writeArray newArr i
go (i+1)
------------------------------------------------------------------------------
expandBucketArray :: Int
-> Int
-> MutableArray s (Bucket s k v)
-> ST s (MutableArray s (Bucket s k v))
expandBucketArray = expandArray emptyRecord
------------------------------------------------------------------------------
growBucketTo :: Int -> Bucket s k v -> ST s (Bucket s k v)
growBucketTo !sz bk | keyIsEmpty bk = emptyWithSize sz
| otherwise = do
if osz >= sz
then return bk
else do
hw <- readSTRef hwRef
k' <- expandArray undefined sz hw keys
v' <- expandArray undefined sz hw values
return $ toKey $ Bucket sz hwRef k' v'
where
bucket = fromKey bk
osz = _bucketSize bucket
hwRef = _highwater bucket
keys = _keys bucket
values = _values bucket
------------------------------------------------------------------------------
{-# INLINE snoc #-}
-- Just return == new bucket object
snoc :: Bucket s k v -> k -> v -> ST s (Int, Maybe (Bucket s k v))
snoc bucket | keyIsEmpty bucket = mkNew
| otherwise = snoc' (fromKey bucket)
where
mkNew !k !v = do
debug "Bucket.snoc: mkNew"
keys <- newArray newBucketSize undefined
values <- newArray newBucketSize undefined
writeArray keys 0 k
writeArray values 0 v
ref <- newSTRef 1
return (1, Just $ toKey $ Bucket newBucketSize ref keys values)
snoc' (Bucket bsz hwRef keys values) !k !v =
readSTRef hwRef >>= check
where
check !hw
| hw < bsz = bump hw
| otherwise = spill hw
bump hw = do
debug $ "Bucket.snoc: bumping hw, bsz=" ++ show bsz ++ ", hw="
++ show hw
writeArray keys hw k
writeArray values hw v
let !hw' = hw + 1
writeSTRef hwRef hw'
debug "Bucket.snoc: finished"
return (hw', Nothing)
doublingThreshold = bucketSplitSize `div` 2
growFactor = 1.5 :: Double
newSize z | z == 0 = newBucketSize
| z < doublingThreshold = z * 2
| otherwise = ceiling $ growFactor * fromIntegral z
spill !hw = do
let sz = newSize bsz
debug $ "Bucket.snoc: spilling, old size=" ++ show bsz ++ ", new size="
++ show sz
bk <- growBucketTo sz bucket
debug "Bucket.snoc: spill finished, snoccing element"
let (Bucket _ hwRef' keys' values') = fromKey bk
let !hw' = hw+1
writeArray keys' hw k
writeArray values' hw v
writeSTRef hwRef' hw'
return (hw', Just bk)
------------------------------------------------------------------------------
{-# INLINE size #-}
size :: Bucket s k v -> ST s Int
size b | keyIsEmpty b = return 0
| otherwise = readSTRef $ _highwater $ fromKey b
------------------------------------------------------------------------------
-- note: search in reverse order! We prefer recently snoc'd keys.
lookup :: (Eq k) => Bucket s k v -> k -> ST s (Maybe v)
lookup bucketKey !k | keyIsEmpty bucketKey = return Nothing
| otherwise = lookup' $ fromKey bucketKey
where
lookup' (Bucket _ hwRef keys values) = do
hw <- readSTRef hwRef
go (hw-1)
where
go !i
| i < 0 = return Nothing
| otherwise = do
k' <- readArray keys i
if k == k'
then do
!v <- readArray values i
return $! Just v
else go (i-1)
------------------------------------------------------------------------------
{-# INLINE toList #-}
toList :: Bucket s k v -> ST s [(k,v)]
toList bucketKey | keyIsEmpty bucketKey = return []
| otherwise = toList' $ fromKey bucketKey
where
toList' (Bucket _ hwRef keys values) = do
hw <- readSTRef hwRef
go [] hw 0
where
go !l !hw !i | i >= hw = return l
| otherwise = do
k <- readArray keys i
v <- readArray values i
go ((k,v):l) hw $ i+1
------------------------------------------------------------------------------
-- fromList needs to reverse the input in order to make fromList . toList == id
{-# INLINE fromList #-}
fromList :: [(k,v)] -> ST s (Bucket s k v)
fromList l = Control.Monad.foldM f emptyRecord (reverse l)
where
f bucket (k,v) = do
(_,m) <- snoc bucket k v
return $ fromMaybe bucket m
------------------------------------------------------------------------------
delete :: (Eq k) => Bucket s k v -> k -> ST s Bool
delete bucketKey !k | keyIsEmpty bucketKey = do
debug $ "Bucket.delete: empty bucket"
return False
| otherwise = do
debug "Bucket.delete: start"
del $ fromKey bucketKey
where
del (Bucket sz hwRef keys values) = do
hw <- readSTRef hwRef
debug $ "Bucket.delete: hw=" ++ show hw ++ ", sz=" ++ show sz
go hw $ hw - 1
where
go !hw !i | i < 0 = return False
| otherwise = do
k' <- readArray keys i
if k == k'
then do
debug $ "found entry to delete at " ++ show i
move (hw-1) i keys
move (hw-1) i values
let !hw' = hw-1
writeSTRef hwRef hw'
return True
else go hw (i-1)
------------------------------------------------------------------------------
{-# INLINE mapM_ #-}
mapM_ :: ((k,v) -> ST s a) -> Bucket s k v -> ST s ()
mapM_ f bucketKey
| keyIsEmpty bucketKey = do
debug $ "Bucket.mapM_: bucket was empty"
return ()
| otherwise = doMap $ fromKey bucketKey
where
doMap (Bucket sz hwRef keys values) = do
hw <- readSTRef hwRef
debug $ "Bucket.mapM_: hw was " ++ show hw ++ ", sz was " ++ show sz
go hw 0
where
go !hw !i | i >= hw = return ()
| otherwise = do
k <- readArray keys i
v <- readArray values i
_ <- f (k,v)
go hw $ i+1
------------------------------------------------------------------------------
{-# INLINE foldM #-}
foldM :: (a -> (k,v) -> ST s a) -> a -> Bucket s k v -> ST s a
foldM f !seed0 bucketKey
| keyIsEmpty bucketKey = return seed0
| otherwise = doMap $ fromKey bucketKey
where
doMap (Bucket _ hwRef keys values) = do
hw <- readSTRef hwRef
go hw seed0 0
where
go !hw !seed !i | i >= hw = return seed
| otherwise = do
k <- readArray keys i
v <- readArray values i
seed' <- f seed (k,v)
go hw seed' (i+1)
------------------------------------------------------------------------------
-- move i into j
move :: Int -> Int -> MutableArray s a -> ST s ()
move i j arr | i == j = do
debug $ "move " ++ show i ++ " into " ++ show j
return ()
| otherwise = do
debug $ "move " ++ show i ++ " into " ++ show j
readArray arr i >>= writeArray arr j
{-# INLINE debug #-}
debug :: String -> ST s ()
#ifdef DEBUG
debug s = unsafeIOToST $ do
putStrLn s
hFlush stdout
#else
#ifdef TESTSUITE
debug !s = do
let !_ = length s
return $! ()
#else
debug _ = return ()
#endif
#endif
| cornell-pl/HsAdapton | weak-hashtables/src/Data/HashTable/Weak/Internal/Linear/Bucket.hs | bsd-3-clause | 10,951 | 0 | 18 | 3,625 | 3,123 | 1,489 | 1,634 | 235 | 2 |
-- Copyright : Isaac Jones 2003-2004
{- All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
OWNER 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. -}
-- | ComponentLocalBuildInfo for Cabal >= 1.21
module Language.Haskell.GhcMod.Cabal21 (
ComponentLocalBuildInfo
, PackageIdentifier(..)
, PackageName(..)
, componentPackageDeps
, componentLibraries
) where
import Distribution.Package (InstalledPackageId)
import Data.Version (Version)
data LibraryName = LibraryName String
deriving (Read, Show)
newtype PackageName = PackageName { unPackageName :: String }
deriving (Read, Show)
data PackageIdentifier
= PackageIdentifier {
pkgName :: PackageName,
pkgVersion :: Version
}
deriving (Read, Show)
type PackageId = PackageIdentifier
data ComponentLocalBuildInfo
= LibComponentLocalBuildInfo {
componentPackageDeps :: [(InstalledPackageId, PackageId)],
componentLibraries :: [LibraryName]
}
| ExeComponentLocalBuildInfo {
componentPackageDeps :: [(InstalledPackageId, PackageId)]
}
| TestComponentLocalBuildInfo {
componentPackageDeps :: [(InstalledPackageId, PackageId)]
}
| BenchComponentLocalBuildInfo {
componentPackageDeps :: [(InstalledPackageId, PackageId)]
}
deriving (Read, Show)
| cabrera/ghc-mod | Language/Haskell/GhcMod/Cabal21.hs | bsd-3-clause | 2,646 | 0 | 10 | 467 | 242 | 153 | 89 | 29 | 0 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
-- | Security specific migration
module Distribution.Server.Features.Security.Migration (
migratePkgTarball_v1_to_v2
, migrateCandidatePkgTarball_v1_to_v2
) where
-- stdlib
import Control.DeepSeq
import Control.Exception
import Data.Map (Map)
import System.IO
import System.IO.Error
import qualified Data.Map as Map
import qualified Data.Vector as Vec
-- Cabal
import Distribution.Package (PackageId)
-- hackage
import Distribution.Server.Features.Core.State
import Distribution.Server.Features.PackageCandidates.State
import Distribution.Server.Features.PackageCandidates.Types
import Distribution.Server.Features.Security.Layout
import Distribution.Server.Framework hiding (Length)
import Distribution.Server.Framework.BlobStorage
import Distribution.Server.Packages.Types
import Distribution.Server.Util.ReadDigest
import qualified Distribution.Server.Packages.PackageIndex as PackageIndex
{-------------------------------------------------------------------------------
Migration of core data structures
-------------------------------------------------------------------------------}
-- | Migrate from BlobId to BlobInfo in PkgTarball
--
-- This is part of the security feature because this computes the additional
-- information (SHA hashes) that we need for the TUF target files.
migratePkgTarball_v1_to_v2 :: ServerEnv
-> StateComponent AcidState PackagesState
-> IO ()
migratePkgTarball_v1_to_v2 env@ServerEnv{ serverVerbosity = verbosity }
packagesState
= do
precomputedHashes <- readPrecomputedHashes env
PackagesState{packageIndex} <- queryState packagesState GetPackagesState
let allPackages = PackageIndex.allPackages packageIndex
partitionSz = PackageIndex.numPackageVersions packageIndex `div` 10
partitioned = partition partitionSz allPackages
stats <- forM (zip [1..] partitioned) $ \(i, pkgs) ->
logTiming verbosity (partitionLogMsg i (length partitioned)) $
migratePkgs env updatePackage precomputedHashes pkgs
loginfo verbosity $ prettyMigrationStats (mconcat stats)
where
updatePackage :: PackageId -> PkgInfo -> IO ()
updatePackage pkgId pkgInfo = updateState packagesState
$ UpdatePackageInfo pkgId pkgInfo
partitionLogMsg :: Int -> Int -> String
partitionLogMsg i n = "Computing blob info "
++ "(" ++ show i ++ "/" ++ show n ++ ")"
-- | Similar migration for candidates
migrateCandidatePkgTarball_v1_to_v2 :: ServerEnv
-> StateComponent AcidState CandidatePackages
-> IO ()
migrateCandidatePkgTarball_v1_to_v2 env@ServerEnv{ serverVerbosity = verbosity }
candidatesState
= do
precomputedHashes <- readPrecomputedHashes env
CandidatePackages{candidateList} <- queryState candidatesState GetCandidatePackages
let allCandidates = PackageIndex.allPackages candidateList
partitionSz = PackageIndex.numPackageVersions candidateList `div` 10
partitioned = partition partitionSz allCandidates
stats <- forM (zip [1..] partitioned) $ \(i, candidates) -> do
let pkgs = map candPkgInfo candidates
logTiming verbosity (partitionLogMsg i (length partitioned)) $
migratePkgs env updatePackage precomputedHashes pkgs
loginfo verbosity $ prettyMigrationStats (mconcat stats)
where
updatePackage :: PackageId -> PkgInfo -> IO ()
updatePackage pkgId pkgInfo = do
_didUpdate <- updateState candidatesState $
UpdateCandidatePkgInfo pkgId pkgInfo
return ()
partitionLogMsg :: Int -> Int -> String
partitionLogMsg i n = "Computing candidates blob info "
++ "(" ++ show i ++ "/" ++ show n ++ ")"
migratePkgs :: ServerEnv
-> (PackageId -> PkgInfo -> IO ())
-> Precomputed
-> [PkgInfo]
-> IO MigrationStats
migratePkgs ServerEnv{ serverBlobStore = store } updatePackage precomputed =
liftM mconcat . mapM migratePkg
where
migratePkg :: PkgInfo -> IO MigrationStats
migratePkg pkg = do
tarballs' <- forM tarballs $ \(tarball, uploadInfo) -> do
tarball' <- migrateTarball tarball
return $ (, uploadInfo) <$> tarball'
-- Avoid updating the state of all packages already migrated
case sequence tarballs' of
AlreadyMigrated _ ->
return mempty
Migrated stats tarballs'' -> do
let pkg' = pkg { pkgTarballRevisions = Vec.fromList tarballs'' }
updatePackage (pkgInfoId pkg) pkg'
return stats
where
tarballs = Vec.toList (pkgTarballRevisions pkg)
migrateTarball :: PkgTarball -> IO (Migrated PkgTarball)
migrateTarball pkgTarball@PkgTarball{} =
return $ AlreadyMigrated pkgTarball
migrateTarball (PkgTarball_v2_v1 PkgTarball_v1{..}) =
case Map.lookup (blobMd5 v1_pkgTarballGz) precomputed of
Just (strSHA256, len) -> do
-- We assume all SHA hashes in the precomputed list parse OK
let Right sha256 = readDigest strSHA256
stats = MigrationStats 1 0
infoGz = BlobInfo {
blobInfoId = v1_pkgTarballGz
, blobInfoLength = len
, blobInfoHashSHA256 = sha256
}
return $ Migrated stats PkgTarball {
pkgTarballGz = infoGz
, pkgTarballNoGz = v1_pkgTarballNoGz
}
Nothing -> do
infoGz <- blobInfoFromId store v1_pkgTarballGz
let stats = MigrationStats 0 1
return $ Migrated stats PkgTarball {
pkgTarballGz = infoGz
, pkgTarballNoGz = v1_pkgTarballNoGz
}
{-------------------------------------------------------------------------------
Precomputed hashes
-------------------------------------------------------------------------------}
type MD5 = String
type SHA256 = String
type Length = Int
type Precomputed = Map MD5 (SHA256, Length)
-- | Read precomputed hashes (if any)
--
-- The result is guaranteed to be in normal form.
readPrecomputedHashes :: ServerEnv -> IO Precomputed
readPrecomputedHashes env@ServerEnv{ serverVerbosity = verbosity } = do
precomputed <- handle emptyOnError $
withFile (onDiskPrecomputedHashes env) ReadMode $ \h -> do
hashes <- Map.fromList . map parseEntry . lines <$> hGetContents h
evaluate $ rnf hashes
return hashes
loginfo verbosity $ "Found " ++ show (Map.size precomputed)
++ " precomputed hashes"
return precomputed
where
emptyOnError :: IOException -> IO Precomputed
emptyOnError err = if isDoesNotExistError err then return Map.empty
else throwIO err
parseEntry :: String -> (MD5, (SHA256, Length))
parseEntry line = let [md5, sha256, len] = words line
in (md5, (sha256, read len))
{-------------------------------------------------------------------------------
Migration infrastructure
-------------------------------------------------------------------------------}
data MigrationStats = MigrationStats {
-- | Number of hashes we lookup up in the precomputed map
migrationStatsPrecomputed :: !Int
-- | Number of hashes we had to compute
, migrationStatsComputed :: !Int
}
prettyMigrationStats :: MigrationStats -> String
prettyMigrationStats MigrationStats{..} = unwords [
show migrationStatsPrecomputed
, "hashes were precomputed, computed"
, show migrationStatsComputed
]
instance Monoid MigrationStats where
mempty = MigrationStats 0 0
(MigrationStats a b) `mappend` (MigrationStats a' b') =
MigrationStats (a + a') (b + b')
data Migrated a = Migrated MigrationStats a | AlreadyMigrated a
deriving (Functor)
instance Applicative Migrated where
pure = return
f <*> x = do f' <- f ; x' <- x ; return $ f' x'
instance Monad Migrated where
return = AlreadyMigrated
AlreadyMigrated a >>= f = f a
Migrated stats a >>= f =
case f a of
AlreadyMigrated b -> Migrated stats b
Migrated stats' b -> Migrated (stats `mappend` stats') b
{-------------------------------------------------------------------------------
Additional auxiliary
-------------------------------------------------------------------------------}
-- | Partition list
--
-- > partition 2 [1..5] = [[1,2],[3,4],[5]]
--
-- If partition size is 0, returns a single partition
partition :: Int -> [a] -> [[a]]
partition 0 xs = [xs]
partition _ [] = []
partition sz xs = let (firstPartition, xs') = splitAt sz xs
in firstPartition : partition sz xs'
| agrafix/hackage-server | Distribution/Server/Features/Security/Migration.hs | bsd-3-clause | 9,132 | 0 | 20 | 2,306 | 1,934 | 1,001 | 933 | 164 | 4 |
-- |
-- Copyright : Anders Claesson 2017
-- Maintainer : Anders Claesson <[email protected]>
-- License : BSD-3
--
-- Quotient difference algorithm for S- and J-fractions
module HOPS.GF.CFrac.QD
( stieltjes
, jacobi
, jacobi0
, jacobi1
) where
import Data.Function.Memoize
import Data.Vector (Vector, (!))
import qualified Data.Vector as V
import HOPS.GF.CFrac.Contraction
jacobi0 :: Fractional a => Vector a -> Vector a
jacobi0 = fst . jacobi
jacobi1 :: Fractional a => Vector a -> Vector a
jacobi1 = snd . jacobi
-- XXX: Jacobi0/1 is currently broken:
--
-- *Main> quickCheck (prop_Jacobi0_QD :: Series 3 -> Bool)
-- *** Failed! (after 6 tests):
-- Exception:
-- ./Data/Vector/Generic.hs:245 ((!)): index out of bounds (2,2)
-- CallStack (from HasCallStack):
-- error, called at .<snip>
-- series (Proxy :: Proxy 3) [Val (1 % 1),Val ((-3) % 4),Val (5 % 1)]
jacobi :: Fractional a => Vector a -> (Vector a, Vector a)
jacobi = contraction stieltjes
-- S-fraction using the Quotient-Difference Algorithm
stieltjes :: Fractional a => Vector a -> Vector a
stieltjes cs =
if V.null cs then
V.empty
else
V.fromList (cs ! 0 : twine qs es)
where
(m, m') =
case V.length cs of
n | odd n -> let k = (n-1) `div` 2 in (k, k)
| otherwise -> let k = n `div` 2 in (k, k-1)
qs = map (q 0) [ 1 .. m ]
es = map (e 0) [ 1 .. m' ]
qM = memoize2 q
eM = memoize2 e
e _ 0 = 0
e k j = eM (k+1) (j-1) + qM (k+1) j - qM k j
q k 1 = cs ! (k+1) / cs ! k
q k j = qM (k+1) (j-1) * eM (k+1) (j-1) / eM k (j-1)
twine :: [a] -> [a] -> [a]
twine [] bs = bs
twine (a:as) bs = a : twine bs as
| akc/gfscript | HOPS/GF/CFrac/QD.hs | bsd-3-clause | 1,707 | 0 | 17 | 458 | 626 | 337 | 289 | 35 | 4 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Text/Internal.hs" #-}
{-# LANGUAGE CPP, DeriveDataTypeable, UnboxedTuples #-}
{-# OPTIONS_HADDOCK not-home #-}
-- |
-- Module : Data.Text.Internal
-- Copyright : (c) 2008, 2009 Tom Harper,
-- (c) 2009, 2010 Bryan O'Sullivan,
-- (c) 2009 Duncan Coutts
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- A module containing private 'Text' internals. This exposes the
-- 'Text' representation and low level construction functions.
-- Modules which extend the 'Text' system may need to use this module.
--
-- You should not use this module unless you are determined to monkey
-- with the internals, as the functions here do just about nothing to
-- preserve data invariants. You have been warned!
module Data.Text.Internal
(
-- * Types
-- $internals
Text(..)
-- * Construction
, text
, textP
-- * Safety
, safe
-- * Code that must be here for accessibility
, empty
, empty_
-- * Utilities
, firstf
-- * Checked multiplication
, mul
, mul32
, mul64
-- * Debugging
, showText
) where
import Data.Bits
import Data.Int (Int32, Int64)
import Data.Text.Internal.Unsafe.Char (ord)
import Data.Typeable (Typeable)
import qualified Data.Text.Array as A
-- | A space efficient, packed, unboxed Unicode text type.
data Text = Text
{-# UNPACK #-} !A.Array -- payload (Word16 elements)
{-# UNPACK #-} !Int -- offset (units of Word16, not Char)
{-# UNPACK #-} !Int -- length (units of Word16, not Char)
deriving (Typeable)
-- | Smart constructor.
text_ :: A.Array -> Int -> Int -> Text
text_ arr off len =
Text arr off len
{-# INLINE text_ #-}
-- | /O(1)/ The empty 'Text'.
empty :: Text
empty = Text A.empty 0 0
{-# INLINE [1] empty #-}
-- | A non-inlined version of 'empty'.
empty_ :: Text
empty_ = Text A.empty 0 0
{-# NOINLINE empty_ #-}
-- | Construct a 'Text' without invisibly pinning its byte array in
-- memory if its length has dwindled to zero.
text :: A.Array -> Int -> Int -> Text
text arr off len | len == 0 = empty
| otherwise = text_ arr off len
{-# INLINE text #-}
textP :: A.Array -> Int -> Int -> Text
{-# DEPRECATED textP "Use text instead" #-}
textP = text
-- | A useful 'show'-like function for debugging purposes.
showText :: Text -> String
showText (Text arr off len) =
"Text " ++ show (A.toList arr off len) ++ ' ' :
show off ++ ' ' : show len
-- | Map a 'Char' to a 'Text'-safe value.
--
-- UTF-16 surrogate code points are not included in the set of Unicode
-- scalar values, but are unfortunately admitted as valid 'Char'
-- values by Haskell. They cannot be represented in a 'Text'. This
-- function remaps those code points to the Unicode replacement
-- character (U+FFFD, \'�\'), and leaves other code points
-- unchanged.
safe :: Char -> Char
safe c
| ord c .&. 0x1ff800 /= 0xd800 = c
| otherwise = '\xfffd'
{-# INLINE [0] safe #-}
-- | Apply a function to the first element of an optional pair.
firstf :: (a -> c) -> Maybe (a,b) -> Maybe (c,b)
firstf f (Just (a, b)) = Just (f a, b)
firstf _ Nothing = Nothing
-- | Checked multiplication. Calls 'error' if the result would
-- overflow.
mul :: Int -> Int -> Int
mul a b = fromIntegral $ fromIntegral a `mul64` fromIntegral b
{-# INLINE mul #-}
infixl 7 `mul`
-- | Checked multiplication. Calls 'error' if the result would
-- overflow.
mul64 :: Int64 -> Int64 -> Int64
mul64 a b
| a >= 0 && b >= 0 = mul64_ a b
| a >= 0 = -mul64_ a (-b)
| b >= 0 = -mul64_ (-a) b
| otherwise = mul64_ (-a) (-b)
{-# INLINE mul64 #-}
infixl 7 `mul64`
mul64_ :: Int64 -> Int64 -> Int64
mul64_ a b
| ahi > 0 && bhi > 0 = error "overflow"
| top > 0x7fffffff = error "overflow"
| total < 0 = error "overflow"
| otherwise = total
where (# ahi, alo #) = (# a `shiftR` 32, a .&. 0xffffffff #)
(# bhi, blo #) = (# b `shiftR` 32, b .&. 0xffffffff #)
top = ahi * blo + alo * bhi
total = (top `shiftL` 32) + alo * blo
{-# INLINE mul64_ #-}
-- | Checked multiplication. Calls 'error' if the result would
-- overflow.
mul32 :: Int32 -> Int32 -> Int32
mul32 a b = case fromIntegral a * fromIntegral b of
ab | ab < min32 || ab > max32 -> error "overflow"
| otherwise -> fromIntegral ab
where min32 = -0x80000000 :: Int64
max32 = 0x7fffffff
{-# INLINE mul32 #-}
infixl 7 `mul32`
-- $internals
--
-- Internally, the 'Text' type is represented as an array of 'Word16'
-- UTF-16 code units. The offset and length fields in the constructor
-- are in these units, /not/ units of 'Char'.
--
-- Invariants that all functions must maintain:
--
-- * Since the 'Text' type uses UTF-16 internally, it cannot represent
-- characters in the reserved surrogate code point range U+D800 to
-- U+DFFF. To maintain this invariant, the 'safe' function maps
-- 'Char' values in this range to the replacement character (U+FFFD,
-- \'�\').
--
-- * A leading (or \"high\") surrogate code unit (0xD800–0xDBFF) must
-- always be followed by a trailing (or \"low\") surrogate code unit
-- (0xDC00-0xDFFF). A trailing surrogate code unit must always be
-- preceded by a leading surrogate code unit.
| phischu/fragnix | tests/packages/scotty/Data.Text.Internal.hs | bsd-3-clause | 5,899 | 2 | 13 | 1,811 | 1,006 | 567 | 439 | 87 | 1 |
module BenchmarkTypes where
import Criterion
type BElem = (Int, Int, ())
data BenchmarkSet = BenchmarkSet
{ bGroupName :: String
, bMinView :: Pure
, bLookup :: Pure
, bInsertEmpty :: Pure
, bInsertNew :: Pure
, bInsertDuplicates :: Pure
, bDelete :: Pure
}
runBenchmark :: [BenchmarkSet] -> [Benchmark]
runBenchmark bset =
[ bgroup "minView" $ map (bench' bMinView) bset
, bgroup "lookup" $ map (bench' bLookup) bset
, bgroup "insertEmpty" $ map (bench' bInsertEmpty) bset
, bgroup "insertNew" $ map (bench' bInsertNew) bset
, bgroup "insertDuplicates" $ map (bench' bInsertDuplicates) bset
, bgroup "delete" $ map (bench' bDelete) bset
]
where
bench' f x = bench (bGroupName x) (f x)
| ariep/psqueues | benchmarks/BenchmarkTypes.hs | bsd-3-clause | 886 | 0 | 9 | 311 | 253 | 136 | 117 | 20 | 1 |
module Main where
import Language.Hakaru.Runtime.Prelude
import qualified System.Random.MWC as MWC
import Control.Monad
prog :: MWC.GenIO -> IO Double
prog = normal (real_ 0) (prob_ 3)
main :: IO ()
main = do
g <- MWC.createSystemRandom
forever $ run g prog
| zaxtax/hakaru | haskell/Language/Hakaru/Runtime/NormTest.hs | bsd-3-clause | 302 | 0 | 8 | 84 | 97 | 53 | 44 | 10 | 1 |
{-# LANGUAGE
TemplateHaskell,
FlexibleInstances,
FlexibleContexts,
TypeOperators,
GADTs,
KindSignatures,
IncoherentInstances #-}
-- base values
module Multi.DataTypes.Comp where
import Data.Comp.Derive
import Data.Comp.Multi
type ValueExpr = HTerm Value
type ExprSig = Value :++: Op
type Expr = HTerm ExprSig
type SugarSig = Value :++: Op :++: Sugar
type SugarExpr = HTerm SugarSig
type BaseType = HTerm ValueT
data ValueT e t = TInt
| TBool
| TPair (e t) (e t)
deriving (Eq)
data Value e t where
VInt :: Int -> Value e Int
VBool :: Bool -> Value e Bool
VPair :: e s -> e t -> Value e (s,t)
data Op e t where
Plus :: e Int -> e Int -> Op e Int
Mult :: e Int -> e Int -> Op e Int
If :: e Bool -> e t -> e t -> Op e t
Lt :: e Int -> e Int -> Op e Bool
Eq :: e Int -> e Int -> Op e Bool
And :: e Bool -> e Bool -> Op e Bool
Not :: e Bool -> Op e Bool
ProjLeft :: e (s,t) -> Op e s
ProjRight :: e (s,t) -> Op e t
data Sugar e t where
Neg :: e Int -> Sugar e Int
Minus :: e Int -> e Int -> Sugar e Int
Gt :: e Int -> e Int -> Sugar e Bool
Or :: e Bool -> e Bool -> Sugar e Bool
Impl :: e Bool -> e Bool -> Sugar e Bool
$(derive
[makeHFunctor, makeHFoldable, makeHTraversable, makeHEqF, smartHConstructors]
[''ValueT, ''Value, ''Op, ''Sugar])
showBinOp :: String -> String -> String -> String
showBinOp op x y = "("++ x ++ op ++ y ++ ")"
instance HShowF ValueT where
hshowF' TInt = "Int"
hshowF' TBool = "Bool"
hshowF' (TPair (K x) (K y)) = showBinOp "," x y
instance HShowF Value where
hshowF' (VInt i) = show i
hshowF' (VBool b) = show b
hshowF' (VPair (K x) (K y)) = showBinOp "," x y
instance HShowF Op where
hshowF' (Plus (K x) (K y)) = showBinOp "+" x y
hshowF' (Mult (K x) (K y)) = showBinOp "*" x y
hshowF' (If (K b) (K x) (K y)) = "if " ++ b ++ " then " ++ x ++ " else " ++ y ++ " fi"
hshowF' (Eq (K x) (K y)) = showBinOp "==" x y
hshowF' (Lt (K x) (K y)) = showBinOp "<" x y
hshowF' (And (K x) (K y)) = showBinOp "&&" x y
hshowF' (Not (K x)) = "~" ++ x
hshowF' (ProjLeft (K x)) = x ++ "!0"
hshowF' (ProjRight (K x)) = x ++ "!1" | spacekitteh/compdata | benchmark/Multi/DataTypes/Comp.hs | bsd-3-clause | 2,234 | 0 | 11 | 650 | 1,065 | 539 | 526 | 64 | 1 |
module HierarchicalImport where
import Hierarchical.Export
main :: Fay ()
main = putStrLn exported
| beni55/fay | tests/HierarchicalImport.hs | bsd-3-clause | 111 | 0 | 6 | 25 | 27 | 15 | 12 | 4 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="id-ID">
<title>Report Generation</title>
<maps>
<homeID>reports</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/reports/src/main/javahelp/org/zaproxy/addon/reports/resources/help_id_ID/helpset_id_ID.hs | apache-2.0 | 966 | 82 | 52 | 156 | 390 | 206 | 184 | -1 | -1 |
module M1 (g) where
import M
{- f :: T -> Int -}
{- f (C1 x y) = x + y -}
g = error "f (C1 1 2) no longer defined for T at line: 4"
l = k
| kmate/HaRe | old/testing/removeCon/M1_TokOut.hs | bsd-3-clause | 144 | 0 | 5 | 47 | 27 | 17 | 10 | 4 | 1 |
{-# LANGUAGE TypeFamilies, GADTs, EmptyDataDecls, FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
module SlowComp where
import Control.Monad
import Data.Kind
-------------------------------------------------------------------------------
-- Usual Peano integers.
class NatInt a where
natInt :: a -> Int
data D0 n = D0 {d0Arg :: n}
data D1 n = D1 {d1Arg :: n}
data C0
data C1
class DPosInt n where posInt :: n -> (Int,Int)
instance DPosInt () where posInt _ = (0,1)
instance DPosInt n => DPosInt (D0 n) where
posInt a = (dsum,w*2)
where
(dsum,w) = posInt $ d0Arg a
instance DPosInt n => DPosInt (D1 n) where
posInt a = (dsum+w,w*2)
where
(dsum,w) = posInt $ d1Arg a
instance NatInt () where natInt _ = 0
instance DPosInt n => NatInt (D0 n) where natInt a = fst $ posInt a
instance DPosInt n => NatInt (D1 n) where natInt a = fst $ posInt a
type family DRev a
type instance DRev a = DRev' a ()
type family DRev' x acc
type instance DRev' () acc = acc
type instance DRev' (D0 a) acc = DRev' a (D0 acc)
type instance DRev' (D1 a) acc = DRev' a (D1 acc)
type family DAddC c a b
type instance DAddC C0 (D0 a) (D0 b) = D0 (DAddC C0 a b)
type instance DAddC C0 (D1 a) (D0 b) = D1 (DAddC C0 a b)
type instance DAddC C0 (D0 a) (D1 b) = D1 (DAddC C0 a b)
type instance DAddC C0 (D1 a) (D1 b) = D0 (DAddC C1 a b)
type instance DAddC C1 (D0 a) (D0 b) = D1 (DAddC C0 a b)
type instance DAddC C1 (D1 a) (D0 b) = D0 (DAddC C1 a b)
type instance DAddC C1 (D0 a) (D1 b) = D0 (DAddC C1 a b)
type instance DAddC C1 (D1 a) (D1 b) = D1 (DAddC C1 a b)
type instance DAddC C0 () () = ()
type instance DAddC C1 () () = D1 ()
type instance DAddC c (D0 a) () = DAddC c (D0 a) (D0 ())
type instance DAddC c (D1 a) () = DAddC c (D1 a) (D0 ())
type instance DAddC c () (D0 b) = DAddC c (D0 b) (D0 ())
type instance DAddC c () (D1 b) = DAddC c (D1 b) (D0 ())
type family DNorm a
type instance DNorm () = D0 ()
type instance DNorm (D0 ()) = D0 ()
type instance DNorm (D0 (D1 a)) = D1 a
type instance DNorm (D0 (D0 a)) = DNorm a
type instance DNorm (D1 a) = D1 a
type family DPlus a b
type instance DPlus a b = DNorm (DRev (DAddC C0 (DRev a) (DRev b)))
type family DDepth a
type instance DDepth () = D0 ()
type instance DDepth (D0 ()) = D0 ()
type instance DDepth (D1 ()) = D1 ()
type instance DDepth (D1 (D0 n)) = DPlus ONE (DDepth (D1 n))
type instance DDepth (D1 (D1 n)) = DPlus ONE (DDepth (D1 n))
type family DLog2 a
type instance DLog2 a = DDepth a
type ZERO = D0 ()
type ONE = D1 ()
type TWO = DPlus ONE ONE
type THREE = DPlus ONE TWO
type FOUR = DPlus TWO TWO
type FIVE = DPlus ONE FOUR
type SIX = DPlus TWO FOUR
type SEVEN = DPlus ONE SIX
type EIGHT = DPlus FOUR FOUR
type NINE = DPlus FOUR FIVE
type TEN = DPlus EIGHT TWO
type SIZE8 = EIGHT
type SIZE9 = NINE
type SIZE10 = TEN
type SIZE12 = DPlus SIX SIX
type SIZE15 = DPlus EIGHT SEVEN
type SIZE16 = DPlus EIGHT EIGHT
type SIZE17 = DPlus ONE SIZE16
type SIZE24 = DPlus SIZE8 SIZE16
type SIZE32 = DPlus SIZE8 SIZE24
type SIZE30 = DPlus SIZE24 SIX
-------------------------------------------------------------------------------
-- Description of CPU.
class CPU cpu where
-- register address.
type RegAddrSize cpu
-- register width
type RegDataSize cpu
-- immediate width.
type ImmSize cpu
-- variables in CPU - register indices, command format variables, etc.
type CPUVars cpu :: Type -> Type
data Const size = Const Integer
data Var cpu size where
Temp :: Int -> Var cpu size
Var :: CPUVars cpu size -> Var cpu size
-------------------------------------------------------------------------------
-- Command description monad.
data Command cpu where
Command :: (Var cpu size) -> (Operation cpu size) -> Command cpu
type RegVar cpu = Var cpu (RegDataSize cpu)
type Immediate cpu = Const (ImmSize cpu)
data Operation cpu resultSize where
Add :: RegVar cpu -> Either (Immediate cpu) (RegVar cpu) -> Operation cpu (RegDataSize cpu)
Sub :: RegVar cpu -> Either (Immediate cpu) (RegVar cpu) -> Operation cpu (RegDataSize cpu)
type CDM cpu a = IO a
($=) :: Var cpu size -> Operation cpu size -> CDM cpu ()
var $= op = undefined
tempVar :: CDM cpu (Var cpu size)
tempVar = do
cnt <- liftM fst undefined
return $ Temp cnt
op :: Operation cpu size -> CDM cpu (Var cpu size)
op operation = do
v <- tempVar
v $= operation
return v
-------------------------------------------------------------------------------
-- Dummy CPU.
data DummyCPU = DummyCPU
data DummyVar size where
DummyFlag :: Flag -> DummyVar ONE
DummyReg :: Int -> DummyVar SIZE16
DummyZero :: DummyVar SIZE16
data Flag = C | Z | N | V
instance CPU DummyCPU where
type RegAddrSize DummyCPU = FIVE
type RegDataSize DummyCPU = SIZE16
type ImmSize DummyCPU = SIZE12
type CPUVars DummyCPU = DummyVar
-------------------------------------------------------------------------------
-- Long compiling program.
{- cnst has very simple code, and should be fast to typecheck
But if you insist on normalising (Immediate DummyCPU) you get
Immediate DummyCPU = Const (ImmSize DummyCPU)
-> Const SIZE12
= Const (DPlus SIX SIX)
...etc...
similarly for (RegVar DummyCPU).
So you get a lot of work and big coercions, for no gain.
-}
cnst :: Integer -> Either (Immediate DummyCPU) (RegVar DummyCPU)
cnst x = Left (Const x)
longCompilingProgram :: CDM DummyCPU ()
longCompilingProgram = do
-- the number of lines below greatly affects compilation time.
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
x10 <- op $ Add (Var DummyZero) (cnst 10)
return ()
| sdiehl/ghc | testsuite/tests/perf/compiler/T5030.hs | bsd-3-clause | 6,608 | 0 | 11 | 1,741 | 2,554 | 1,328 | 1,226 | -1 | -1 |
import Test.Cabal.Prelude
-- No cabal test because per-component is broken for it
main = setupTest $ do
withPackageDb $ do
withDirectory "p" $ do
setup_install ["q"]
setup_install ["p"]
setup_install ["foo"]
runInstalledExe "foo" []
| themoritz/cabal | cabal-testsuite/PackageTests/InternalLibraries/setup-per-component.test.hs | bsd-3-clause | 276 | 0 | 15 | 76 | 71 | 33 | 38 | 8 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Betfair.APING
( Context(..)
, initializeContext
-- GetResponse
, getDecodedResponse
-- Requests
-- Login
, sessionToken
-- Logout
, logout
-- PlaceOrders
, placeOrder
, placeOrderWithParams
-- KeepAlive
, keepAlive
, keepAliveOnceEvery10Minutes
-- ListMarketBook
, listMarketBook
, marketBook
, marketBooks
-- ListMarketCatalogue
, marketCatalogue
-- CancelOrders
, cancelOrder
, cancelOrderWithParams
-- Types
, APINGException
, AppKey
, BettingException
, CancelExecutionReport
, CancelInstruction
, CancelInstructionReport
, Competition
, Error
, ErrorData
, Event
, EventType
, ExBestOffersOverrides
, ExchangePrices
, ExecutionReportErrorCode
, ExecutionReportStatus
, InstructionReportErrorCode
, InstructionReportStatus
, LimitOnCloseOrder
, LimitOrder
, Login
, MarketBettingType
, MarketBook
, MarketCatalogue
, MarketDescription
, MarketFilter
, MarketOnCloseOrder
, MarketProjection
, MarketSort
, MarketStatus
, Match
, MatchProjection
, Order
, OrderProjection
, OrderStatus
, OrderType
, PersistenceType
, PlaceExecutionReport
, PlaceInstruction
, PlaceInstructionReport
, PriceData
, PriceProjection
, PriceSize
-- ,ResponseCancelOrders
-- ,ResponseMarketBook
-- ,ResponseMarketCatalogue
-- ,ResponsePlaceOrders
, RollupModel
, Runner
, RunnerCatalog
, RunnerStatus
, Side
, StartingPrices
, TimeRange
, Token
-- common types
, SelectionId
, MarketId
, EventName
, MarketName
, RunnerName
, Price
, Size
) where
import Protolude
-- API
-- Context
-- import Betfair.APING.API.APIRequest
import Betfair.APING.API.Context
import Betfair.APING.API.GetResponse
-- import Betfair.APING.API.Headers
-- import Betfair.APING.API.Log
import Betfair.APING.Requests.CancelOrders
import Betfair.APING.Requests.KeepAlive
import Betfair.APING.Requests.ListMarketBook
import Betfair.APING.Requests.ListMarketCatalogue
import Betfair.APING.Requests.Login
import Betfair.APING.Requests.Logout
import Betfair.APING.Requests.PlaceOrders
import Betfair.APING.Types.APINGException
import Betfair.APING.Types.AppKey
import Betfair.APING.Types.BettingException
import Betfair.APING.Types.CancelExecutionReport
import Betfair.APING.Types.CancelInstruction
import Betfair.APING.Types.CancelInstructionReport
import Betfair.APING.Types.Competition
import Betfair.APING.Types.Error
import Betfair.APING.Types.ErrorData
import Betfair.APING.Types.Event
import Betfair.APING.Types.EventType
import Betfair.APING.Types.ExBestOffersOverrides
import Betfair.APING.Types.ExchangePrices
import Betfair.APING.Types.ExecutionReportErrorCode
import Betfair.APING.Types.ExecutionReportStatus
import Betfair.APING.Types.InstructionReportErrorCode
import Betfair.APING.Types.InstructionReportStatus
import Betfair.APING.Types.LimitOnCloseOrder
import Betfair.APING.Types.LimitOrder
import Betfair.APING.Types.Login
import Betfair.APING.Types.MarketBettingType
import Betfair.APING.Types.MarketBook
import Betfair.APING.Types.MarketCatalogue
import Betfair.APING.Types.MarketDescription
import Betfair.APING.Types.MarketFilter
import Betfair.APING.Types.MarketOnCloseOrder
import Betfair.APING.Types.MarketProjection
import Betfair.APING.Types.MarketSort
import Betfair.APING.Types.MarketStatus
import Betfair.APING.Types.Match
import Betfair.APING.Types.MatchProjection
import Betfair.APING.Types.Order
import Betfair.APING.Types.OrderProjection
import Betfair.APING.Types.OrderStatus
import Betfair.APING.Types.OrderType
import Betfair.APING.Types.PersistenceType
import Betfair.APING.Types.PlaceExecutionReport
import Betfair.APING.Types.PlaceInstruction
import Betfair.APING.Types.PlaceInstructionReport
import Betfair.APING.Types.PriceData
import Betfair.APING.Types.PriceProjection
import Betfair.APING.Types.PriceSize
-- import Betfair.APING.Types.ResponseCancelOrders
-- import Betfair.APING.Types.ResponseMarketBook
-- import Betfair.APING.Types.ResponseMarketCatalogue
-- import Betfair.APING.Types.ResponsePlaceOrders
import Betfair.APING.Types.RollupModel
import Betfair.APING.Types.Runner
import Betfair.APING.Types.RunnerCatalog
import Betfair.APING.Types.RunnerStatus
import Betfair.APING.Types.Side
import Betfair.APING.Types.StartingPrices
import Betfair.APING.Types.TimeRange
import Betfair.APING.Types.Token
type MarketId = Text
type SelectionId = Integer
type EventName = Text
type MarketName = Text
type RunnerName = Text
type Price = Double
type Size = Double
| joe9/betfair-api | src/Betfair/APING.hs | mit | 4,712 | 0 | 5 | 585 | 714 | 505 | 209 | 144 | 0 |
----------------------------------------------------------------
--
-- | Compilation
-- Monad and combinators for quickly assembling simple
-- compilers.
--
-- @Control\/Compilation\/Trees.hs@
--
-- A generic compilation monad for quickly assembling simple
-- compilers for target languages that are primarily
-- expression trees.
--
----------------------------------------------------------------
--
module Control.Compilation.Trees
where
import Control.Compilation
----------------------------------------------------------------
-- | State extension class definition, including combinators
-- and convenient synonyms.
() = ()
--eof
| lapets/compilation | Control/Compilation/Trees.hs | mit | 656 | 0 | 5 | 84 | 40 | 31 | 9 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Ptt.Time.Clock
( hours
, minutesOfHours
, timeOfDay
, secondsToText
, secondsToLength
, secondsFromText
) where
import Prelude as P
import qualified Data.Text as T
import Control.Applicative
import Ptt.Util
hours :: Integral a => a -> Integer
hours seconds = fromIntegral $ seconds `div` 3600
minutesOfHours :: Integral a => a -> Int
minutesOfHours seconds = fromIntegral $ seconds `rem` 3600 `div` 60
secondsOfMinutes :: Integral a => a -> Int
secondsOfMinutes seconds = fromIntegral $ seconds `rem` 60
timeOfDay :: Integral a => a -> a -> Integer
timeOfDay hour minute =
let hourSeconds = hour * 3600
minuteSeconds = minute * 60
in fromIntegral $ hourSeconds + minuteSeconds
timeOfDayWithSeconds :: Integral a => a -> a -> a -> Integer
timeOfDayWithSeconds hour minute second =
timeOfDay hour minute + fromIntegral second
secondsToText :: Integral a => a -> T.Text
secondsToText seconds =
let s = secondsOfMinutes seconds
hs = pad $ hours seconds
ms = pad $ minutesOfHours seconds
hm = T.concat [hs, ":", ms]
in if s == 0 then hm else T.concat [hm, ":", pad s]
where pad i
| i < 10 = T.append "0" (tshow (abs i))
| otherwise = tshow i
secondsToLength :: Integral a => a -> T.Text
secondsToLength seconds =
let h = formatNonZero (hours seconds) "h"
m = formatNonZero (minutesOfHours seconds) "m"
in T.intercalate " " $ filter (not . T.null) [h, m]
where formatNonZero i s = if i > 0 then T.append (tshow i) s else ""
secondsFromText :: T.Text -> Maybe Integer
secondsFromText time =
case T.split isTimeSeparator time of
(hs:ms:ss:[]) ->
timeOfDayWithSeconds <$> readInt hs <*> readInt ms <*> readInt ss
(hs:ms:[]) -> timeOfDay <$> readInt hs <*> readInt ms
(hs:[]) -> timeOfDay <$> readInt hs <*> pure 0
_ -> Nothing
isTimeSeparator :: Char -> Bool
isTimeSeparator c = c `elem` ".:"
| jkpl/ptt | src/Ptt/Time/Clock.hs | mit | 1,943 | 0 | 12 | 428 | 730 | 376 | 354 | 52 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE PatternSynonyms #-}
module Ringo.Generator.Populate.Dimension (dimensionTablePopulateSQL) where
#if MIN_VERSION_base(4,8,0)
#else
import Control.Applicative ((<$>))
#endif
import Control.Monad.Reader (Reader, asks, withReader)
import Database.HsSqlPpp.Syntax (Statement, QueryExpr(..), Distinct(..), makeSelect, JoinType(..))
import Data.Maybe (fromJust)
import Data.Text (Text)
import Ringo.Extractor.Internal
import Ringo.Generator.Internal
import Ringo.Generator.Sql
import Ringo.Types
dimensionTablePopulateSQL :: TablePopulationMode -> Fact -> TableName -> Reader Env Text
dimensionTablePopulateSQL popMode fact dimTableName =
ppStatement <$> dimensionTablePopulateStmt popMode fact dimTableName
dimensionTablePopulateStmt :: TablePopulationMode -> Fact -> TableName -> Reader Env Statement
dimensionTablePopulateStmt popMode fact dimTableName = withReader envView $ do
Settings {..} <- asks envSettings
tables <- asks envTables
defaults <- asks envTypeDefaults
let factTable = fromJust $ findTable (factTableName fact) tables
colMapping = dimColumnMapping settingDimPrefix fact dimTableName
selectCols = [ flip sia (nmc cName) $ coalesceColumn defaults (factTableName fact) col
| (_, cName) <- colMapping
, let col = fromJust . findColumn cName $ tableColumns factTable ]
timeCol = head ([ cName | DimTimeV cName <- factColumns fact ] :: [ColumnName])
isNotNullC = parens . foldBinop "or" . map (postop "isnotnull" . ei . snd) $ colMapping
selectWhereC = Just . foldBinop "and" $
[ isNotNullC, binop "<" (ei timeCol) placeholder ] ++
[ binop ">=" (ei timeCol) placeholder | popMode == IncrementalPopulation ]
selectC = makeSelect
{ selDistinct = Distinct
, selSelectList = sl selectCols
, selTref = [tref $ factTableName fact]
, selWhere = selectWhereC
}
iTableName = suffixTableName popMode settingTableNameSuffixTemplate dimTableName
insertC = insert iTableName (map fst colMapping) $ case popMode of
FullPopulation -> selectC
IncrementalPopulation -> let alias = "x" in
makeSelect
{ selSelectList = sl [si $ qstar alias]
, selTref =
[ tjoin (subtrefa alias selectC) LeftOuter (tref dimTableName) . Just $
foldBinop "and" [ binop "=" (eqi dimTableName c1) (eqi alias c2) | (c1, c2) <- colMapping ] ]
, selWhere =
Just . foldBinop "and" . map (postop "isnull" . eqi dimTableName . fst) $ colMapping
}
return insertC
| quintype/ringo | src/Ringo/Generator/Populate/Dimension.hs | mit | 2,918 | 0 | 25 | 816 | 737 | 389 | 348 | 49 | 2 |
module OpenWeatherMap.Types
( module OpenWeatherMap.Types.Weather
, module OpenWeatherMap.Types.Coordinate
) where
import OpenWeatherMap.Types.Coordinate
import OpenWeatherMap.Types.Weather
| AndrewRademacher/open-weather-map | src/OpenWeatherMap/Types.hs | mit | 223 | 0 | 5 | 47 | 34 | 23 | 11 | 5 | 0 |
module Yage.Wire.Resources
(
-- * Resource Allocation Wires
acquireOnce
, allocationOnEvent
) where
import Yage.Prelude hiding (any, on)
import Yage.Resources
import Control.Wire
import Control.Wire.Unsafe.Event
import Yage.Wire.Types
-- | `YageResource` allocation wire
--
-- allocates a `YageResource` which is never freed (!)
-- (beside garbage collection of the haskell data structure)
acquireOnce :: YageResource a -> YageWire t b a
acquireOnce res = mkGenN $ \_ -> do
(_key, a) <- allocateAcquire res
return $ (Right a, mkConst $ Right a)
{-# INLINE acquireOnce #-}
-- | loads resources each time the carrying 'Event' occurs. The previous loaded
-- resource is freed.
allocationOnEvent :: YageWire t (Event (YageResource a)) (Event a)
allocationOnEvent = unloaded
where
unloaded =
mkGenN $ event (return (Right NoEvent, unloaded)) (\res -> do
(k, a) <- allocateAcquire res
return (Right $ Event a, loaded k)
)
loaded key =
mkGenN $ event (return (Right NoEvent, loaded key)) (\res -> do
release key
(k, a) <- allocateAcquire res
return (Right $ Event a, loaded k)
)
| MaxDaten/yage | src/Yage/Wire/Resources.hs | mit | 1,212 | 0 | 16 | 308 | 334 | 178 | 156 | 25 | 1 |
module BankAccount ( BankAccount
, openAccount, closeAccount
, getBalance, incrementBalance) where
import Control.Concurrent.STM
import Control.Applicative
import Prelude
newtype BankAccount = BankAccount { unBankAccount :: TVar (Maybe Int) }
openAccount :: IO BankAccount
openAccount = atomically $ BankAccount <$> newTVar (Just 0)
closeAccount :: BankAccount -> IO ()
closeAccount = atomically . flip writeTVar Nothing . unBankAccount
getBalance :: BankAccount -> IO (Maybe Int)
getBalance = atomically . readTVar . unBankAccount
incrementBalance :: BankAccount -> Int -> IO (Maybe Int)
incrementBalance acct delta = atomically $ do
let b = unBankAccount acct
bal <- fmap (delta +) <$> readTVar b
writeTVar b bal
return bal
| stevejb71/xhaskell | bank-account/example.hs | mit | 777 | 0 | 11 | 155 | 233 | 121 | 112 | 19 | 1 |
module Rascal.API where
import Control.Applicative ((<$>))
import Text.Printf (printf)
import Control.Exception (handle)
import Data.Aeson (parseJSON, FromJSON)
import Network.Curl.Aeson (curlAeson, noData, CurlAesonException, errorMsg, curlCode)
import Network.Curl.Opts (CurlOption(CurlUserAgent))
import Network.Curl.Code (CurlCode(CurlOK))
import Rascal.Constants
import Rascal.Types
-- |get posts according to selection in argument's subreddit as a listing
getListing :: String -> String -> Int -> Maybe String -> String -> IO NamedListing
getListing select subreddit cnt aftr uagent =
let apiurl = "http://www.reddit.com/r/" ++ subreddit ++ "/%s.json?count="
++ show cnt ++ maybe "" ("&after=" ++) aftr
in NamedListing (subreddit ++ " -- " ++ select) cnt <$>
getThing apiurl uagent select emptyListing
-- |get posts or comments from an apiurl, a sort order and a default in case
-- of error
getThing :: FromJSON a => String -> String -> String -> a -> IO a
getThing apiurl uagent sort emptyThing =
let sort' = if sort `notElem` map snd availableSorts
then snd . head $ availableSorts
else sort
apiurl' = printf apiurl sort'
in handle (handleCurlAesonException emptyThing) $ do
l <- curlAeson parseJSON "GET" apiurl' [CurlUserAgent uagent] noData
return $! l
-- |print error message if there is a cURL exception
handleCurlAesonException :: a -> CurlAesonException -> IO a
handleCurlAesonException x e = do
putStrLn $ red ++ "Caught exception: " ++ reset ++ errorMsg e
putStrLn $ if curlCode e == CurlOK
then "(Might indicate a non-existing subreddit)"
else "cURL code: " ++ (drop 4 . show . curlCode) e
return x
-- |request comments for a given article
getComments :: String -> String -> String -> String -> IO Comments
getComments subreddit article csort uagent =
let apiurl = "http://www.reddit.com/r/" ++ subreddit ++
"/comments/" ++ article ++ ".json?sort=%s"
in getThing apiurl uagent csort emptyComments
| soli/rascal | src/Rascal/API.hs | mit | 2,109 | 0 | 14 | 479 | 544 | 284 | 260 | 37 | 2 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeFamilies #-}
{-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-missing-methods #-}
----------------------------------------------------------------------
-- |
-- Module : Data.Dif
-- Copyright : (c) Conal Elliott 2008
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Automatic differentiation, as in Jerzy Karczmarczuk's paper /Functional
-- Differentiation of Computer Programs/ (ICFP version),
-- <http://citeseer.ist.psu.edu/karczmarczuk98functional.html>.
--
-- See also the blog post
-- <http://conal.net/blog/posts/beautiful-differentiation/>.
----------------------------------------------------------------------
--
-- Modified by Ruben Zilibowitz 31st March 2017
-- To deal with derivatives w.r.t. more than one variable
--
module Data.Dif (Dif(..), dId, dConst) where
import Data.Function (on)
import Data.NumInstances ()
-- | Tower of derivatives.
data Dif e a = D { dVal :: a, deriv :: e -> Dif e a }
-- | Differentiable identity function (sampled). Sometimes called "the
-- derivation variable" or similar, but it's not really a variable.
dId :: (Num a, Eq e) => e -> a -> Dif e a
dId name x = D x (\i -> if i == name then 1 else 0)
-- The papers refer to dId as a "derivation variable" or similar. I like
-- to reserve "variable" for a name (if syntax) or storage (if
-- semantics). @dId x@ is the derivative tower associated with the
-- identity function sampled at x.
-- | Differentiable constant function. See also 'dConstV'.
dConst :: Num a => a -> Dif e a
dConst x = D x (const 0)
-- I'm not sure about the next three, which discard information
instance Show a => Show (Dif e a) where show = show . dVal
instance Eq a => Eq (Dif e a) where (==) = (==) `on` dVal
instance Ord a => Ord (Dif e a) where compare = compare `on` dVal
-- The chain rule
infix 0 >-<
(>-<) :: (Num a) => (a -> a) -> (Dif e a -> Dif e a) -> (Dif e a -> Dif e a)
f >-< d = \ p@(D u u') -> D (f u) (\i -> d p * (u' i))
instance Num a => Num (Dif e a) where
fromInteger = dConst . fromInteger
D x x' + D y y' = D (x + y) (\i -> (x' i) + (y' i))
D x x' - D y y' = D (x - y) (\i -> (x' i) - (y' i))
p@(D x x') * q@(D y y') = D (x * y) (\i -> (x' i) * q + p * (y' i))
negate = negate >-< -1
abs = abs >-< signum
signum = signum >-< 0
-- More efficiently:
-- signum (D x _) = dConst (signum x)
-- Though really, signum isn't differentiable at zero, without something
-- like Dirac impulses.
instance Fractional a => Fractional (Dif e a) where
fromRational = dConst . fromRational
recip = recip >-< - sqr recip
-- More efficiently:
-- recip (D x x') = ip
-- where ip = D (recip x) (-x' * ip * ip)
sqr :: Num a => a -> a
sqr x = x*x
instance (Fractional a, Floating a) => Floating (Dif e a) where
pi = dConst pi
exp = exp >-< exp
log = log >-< recip
sqrt = sqrt >-< recip (2 * sqrt)
sin = sin >-< cos
cos = cos >-< - sin
sinh = sinh >-< cosh
cosh = cosh >-< sinh
asin = asin >-< recip (sqrt (1-sqr))
acos = acos >-< recip (- sqrt (1-sqr))
atan = atan >-< recip (1+sqr)
asinh = asinh >-< recip (sqrt (1+sqr))
acosh = acosh >-< recip (- sqrt (sqr-1))
atanh = atanh >-< recip (1-sqr)
-- More efficiently:
-- exp (D x x') = r where r = D (exp x) (x' * r)
| rzil/honours | DeepLearning/Data/Dif.hs | mit | 3,440 | 3 | 13 | 837 | 1,034 | 564 | 470 | 44 | 2 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Agent.PingPong.Manager.Send where
import Agent.Generic
import AgentSystem.Manager
import Agent.PingPong
import Control.Monad (when)
import Control.Concurrent (yield)
import Data.IORef
--------------------------------------------------------------------------------
-- | First sends 'Ping' message to _pong_ agent.
-- Then sends 'Ping' to _pong_ only in response to 'Pong' message.
-- Total number of 'Ping' messages sent is _nPings_.
pingDescriptor sys nPings =
GenericAgentDescriptor{
agName = "Ping"
, agDebug = _debug
, initialState = do nPingsRef <- newIORef nPings
firstTime <- newIORef True
return (nPingsRef, sys, firstTime)
, messageHandling = MessageHandling{
msgHandle = selectMessageHandler [
mbHandle $ \c Pong -> sendPing c
]
, msgRespond = selectResponse []
}
, action = AgentAction $
\c -> do let (_, _, firstTime') = agentState c
firstTime <- readIORef firstTime'
when firstTime $ do sendPing c
firstTime' `writeIORef` False
, emptyResult = EmptyResult :: EmptyResult ()
}
sendPing c = do let (i', sys, _) = agentState c
i <- readIORef i'
Just pong <- sys `findAgent` AgentId "Pong"
if i > 0 then do putStrLn $ "Ping (" ++ show i ++ ")"
pong `send` Ping
i' `writeIORef` (i-1)
else do putStrLn "Terminating Ping"
agentTerminate c
-- | Sends 'Pong' message to _ping_ agent in response to 'Ping'.
pongDescriptor sys =
GenericAgentDescriptor{
agName = "Pong"
, agDebug = _debug
, initialState = return sys
, messageHandling = MessageHandling{
msgHandle = selectMessageHandler [
mbHandle $ \c Ping -> do Just ping <- sys `findAgent` AgentId "Ping"
putStrLn "Pong"
ping `send` Pong
]
, msgRespond = selectResponse []
}
, action = agentNoAction
, emptyResult = EmptyResult :: EmptyResult ()
}
--------------------------------------------------------------------------------
runPingPong nPings = do putStrLn "<< Create Agents Manager >> "
m <- newSimpleAgentsManager
ping <- m `newAgent` pingDescriptor m nPings
pong <- m `newAgent` pongDescriptor m
putStrLn "Starting agents"
startAllAgents m
putStrLn "Waiting PING termination"
agentWaitTermination ping
putStrLn "Terminating agents"
terminateAllAgents m
putStrLn "Finished"
| fehu/h-agents | test/Agent/PingPong/Manager/Send.hs | mit | 3,009 | 0 | 17 | 1,114 | 605 | 312 | 293 | 58 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputlambdaprocessor.html
module Stratosphere.ResourceProperties.KinesisAnalyticsApplicationInputLambdaProcessor where
import Stratosphere.ResourceImports
-- | Full data type definition for
-- KinesisAnalyticsApplicationInputLambdaProcessor. See
-- 'kinesisAnalyticsApplicationInputLambdaProcessor' for a more convenient
-- constructor.
data KinesisAnalyticsApplicationInputLambdaProcessor =
KinesisAnalyticsApplicationInputLambdaProcessor
{ _kinesisAnalyticsApplicationInputLambdaProcessorResourceARN :: Val Text
, _kinesisAnalyticsApplicationInputLambdaProcessorRoleARN :: Val Text
} deriving (Show, Eq)
instance ToJSON KinesisAnalyticsApplicationInputLambdaProcessor where
toJSON KinesisAnalyticsApplicationInputLambdaProcessor{..} =
object $
catMaybes
[ (Just . ("ResourceARN",) . toJSON) _kinesisAnalyticsApplicationInputLambdaProcessorResourceARN
, (Just . ("RoleARN",) . toJSON) _kinesisAnalyticsApplicationInputLambdaProcessorRoleARN
]
-- | Constructor for 'KinesisAnalyticsApplicationInputLambdaProcessor'
-- containing required fields as arguments.
kinesisAnalyticsApplicationInputLambdaProcessor
:: Val Text -- ^ 'kaailpResourceARN'
-> Val Text -- ^ 'kaailpRoleARN'
-> KinesisAnalyticsApplicationInputLambdaProcessor
kinesisAnalyticsApplicationInputLambdaProcessor resourceARNarg roleARNarg =
KinesisAnalyticsApplicationInputLambdaProcessor
{ _kinesisAnalyticsApplicationInputLambdaProcessorResourceARN = resourceARNarg
, _kinesisAnalyticsApplicationInputLambdaProcessorRoleARN = roleARNarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputlambdaprocessor.html#cfn-kinesisanalytics-application-inputlambdaprocessor-resourcearn
kaailpResourceARN :: Lens' KinesisAnalyticsApplicationInputLambdaProcessor (Val Text)
kaailpResourceARN = lens _kinesisAnalyticsApplicationInputLambdaProcessorResourceARN (\s a -> s { _kinesisAnalyticsApplicationInputLambdaProcessorResourceARN = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputlambdaprocessor.html#cfn-kinesisanalytics-application-inputlambdaprocessor-rolearn
kaailpRoleARN :: Lens' KinesisAnalyticsApplicationInputLambdaProcessor (Val Text)
kaailpRoleARN = lens _kinesisAnalyticsApplicationInputLambdaProcessorRoleARN (\s a -> s { _kinesisAnalyticsApplicationInputLambdaProcessorRoleARN = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsApplicationInputLambdaProcessor.hs | mit | 2,683 | 0 | 13 | 222 | 267 | 153 | 114 | 29 | 1 |
{-# LANGUAGE FlexibleInstances, OverloadedStrings, RankNTypes, ScopedTypeVariables #-}
module Main where
import Codec.Binary.UTF8.String (encode)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.ListLike as ListLike (ListLike(..))
import Data.Maybe (mapMaybe)
import Data.Monoid (Monoid(..), (<>))
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Prelude hiding (length, concat, null)
import GHC.IO.Exception
import System.Exit
import System.Posix.Files (getFileStatus, fileMode, setFileMode, unionFileModes, ownerExecuteMode, groupExecuteMode, otherExecuteMode)
import System.Process (CreateProcess, proc, shell)
import System.Process.ListLike (readProcessWithExitCode, readCreateProcessWithExitCode, readCreateProcess, ListLikePlus(..), Chunk(..), readProcessChunks)
import Test.HUnit hiding (path)
-- | Merge adjacent and eliminate empty Stdout or Stderr chunks. This
-- may not be a good idea if we are looking to get our output as soon
-- as it becomes available.
canonicalChunks :: ListLikePlus a c => [Chunk a] -> [Chunk a]
canonicalChunks [] = []
canonicalChunks (Stdout a : Stdout b : more) = canonicalChunks (Stdout (a <> b) : more)
canonicalChunks (Stderr a : Stderr b : more) = canonicalChunks (Stderr (a <> b) : more)
canonicalChunks (Stdout a : more) | null a = canonicalChunks more
canonicalChunks (Stderr a : more) | null a = canonicalChunks more
canonicalChunks (a : more) = a : canonicalChunks more
fromString :: String -> B.ByteString
fromString = fromList . encode
lazyFromString :: String -> L.ByteString
lazyFromString = L.fromChunks . (: []) . fromString
instance Monoid Test where
mempty = TestList []
mappend (TestList a) (TestList b) = TestList (a ++ b)
mappend (TestList a) b = TestList (a ++ [b])
mappend a (TestList b) = TestList ([a] ++ b)
mappend a b = TestList [a, b]
testInstances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testInstances mkTest = mappend (testCharInstances mkTest) (testWord8Instances mkTest)
testStrictInstances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testStrictInstances mkTest = mappend (testStrictCharInstances mkTest) (testStrictWord8Instances mkTest)
testLazyInstances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testLazyInstances mkTest = mappend (testLazyCharInstances mkTest) (testLazyWord8Instances mkTest)
testCharInstances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testCharInstances mkTest = mappend (testLazyCharInstances mkTest) (testStrictCharInstances mkTest)
testLazyCharInstances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testLazyCharInstances mkTest =
TestList [ TestLabel "Lazy Text" $ mkTest LT.empty
, TestLabel "String" $ mkTest ("" :: String) ]
testStrictCharInstances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testStrictCharInstances mkTest =
TestList [ TestLabel "Strict Text" $ mkTest T.empty ]
testWord8Instances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testWord8Instances mkTest = mappend (testLazyWord8Instances mkTest) (testStrictWord8Instances mkTest)
testLazyWord8Instances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testLazyWord8Instances mkTest =
TestList [ TestLabel "Lazy ByteString" $ mkTest L.empty ]
testStrictWord8Instances :: (forall a c. (Show a, ListLikePlus a c) => a -> Test) -> Test
testStrictWord8Instances mkTest =
TestList [ TestLabel "Strict ByteString" $ mkTest B.empty ]
main :: IO ()
main =
do chmod "Tests/Test1.hs"
chmod "Tests/Test2.hs"
chmod "Tests/Test4.hs"
(c,st) <- runTestText putTextToShowS test1 -- (TestList (versionTests ++ sourcesListTests ++ dependencyTests ++ changesTests))
putStrLn (st "")
case (failures c) + (errors c) of
0 -> return ()
_ -> exitFailure
chmod :: FilePath -> IO ()
chmod path =
getFileStatus "Tests/Test1.hs" >>= \ status ->
setFileMode path (foldr unionFileModes (fileMode status) [ownerExecuteMode, groupExecuteMode, otherExecuteMode])
cps :: [CreateProcess]
cps = [ proc "true" []
, proc "false" []
, shell "foo"
, proc "foo" []
, shell "yes | cat -n | head 100"
, shell "yes | cat -n"
, proc "cat" ["Tests/text"]
, proc "cat" ["Tests/houseisclean.jpg"]
, proc "Tests/Test1.hs" []
]
test1 :: Test
test1 =
TestLabel "test1"
(TestList
[ TestLabel "[Output]" $
TestList
[ testCharInstances
(\ i -> TestCase (do b <- readProcessChunks (proc "cat" ["Tests/text"]) i
assertEqual
"UTF8"
["ProcessHandle <processhandle>",
-- For Text, assuming your locale is set to utf8, the result is unicode.
"Stdout \"Signed: Baishi laoren \\30333\\30707\\32769\\20154, painted in the artist\\8217s 87th year.\\n\"",
"Result ExitSuccess"] (ListLike.map show (canonicalChunks b))))
, testWord8Instances
(\ i -> TestCase (do b <- readProcessChunks (proc "cat" ["Tests/text"]) i
assertEqual
"UTF8"
["ProcessHandle <processhandle>",
-- For ByteString we get utf8 encoded text
"Stdout \"Signed: Baishi laoren \\231\\153\\189\\231\\159\\179\\232\\128\\129\\228\\186\\186, painted in the artist\\226\\128\\153s 87th year.\\n\"",
"Result ExitSuccess"] (ListLike.map show (canonicalChunks b))))
, testInstances
(\ i -> TestCase (do b <- readProcessChunks (proc "Tests/Test1.hs" []) i
assertEqual
"[Chunk]"
["ProcessHandle <processhandle>",
"Stderr \"This is an error message.\\n\"",
"Result (ExitFailure 123)"]
(ListLike.map show (canonicalChunks b))))
]
-- This gets "hGetContents: invalid argument (invalid byte sequence)" if we don't call
-- binary on the file handles in readProcessInterleaved.
, TestLabel "JPG" $
TestList
[ {- TestCase (do b <- readProcessChunks (proc "cat" ["Tests/houseisclean.jpg"]) B.empty >>=
return . mapMaybe (\ x -> case x of
Stdout s -> Just (length' s)
Stderr s -> Just (length' s)
_ -> Nothing)
assertEqual "ByteString Chunk Size"
[68668,0]
b
-- If we could read a jpg file into a string the chunks would look something like this:
-- [2048,2048,2048,1952,2048,2048,2048,1952,2048,2048,2048,1952,2048,2048,2048,1952,2048,2048,2048,1952,2048,2048,2048,1952,2048,2048,2048,1952,2048,2048,2048,1952,2048,1852]
)
, -}
testLazyWord8Instances
( \ i -> TestCase (do b <- readProcessChunks (proc "cat" ["Tests/houseisclean.jpg"]) i >>=
return . mapMaybe (\ x -> case x of
Stdout s -> Just (length s)
Stderr s -> Just (length s)
_ -> Nothing)
assertEqual "Chunk Size" [32752,32752,3164] b))
, testStrictWord8Instances
( \ i -> TestCase (do b <- readProcessChunks (proc "cat" ["Tests/houseisclean.jpg"]) i >>=
return . mapMaybe (\ x -> case x of
Stdout s -> Just (length s)
Stderr s -> Just (length s)
_ -> Nothing)
assertEqual "Chunk Size" [68668,0] b))
{- -- We don't seem to get an InvalidArgument exception back.
, TestCase (do b <- tryIOError (readProcessChunks (proc "cat" ["Tests/houseisclean.jpg"]) "") >>= return . either Left (Right . show)
assertEqual "String decoding exception" (Left (IOError { ioe_handle = Nothing
, ioe_type = InvalidArgument
, ioe_location = "recoverDecode"
, ioe_description = "invalid byte sequence"
, ioe_errno = Nothing
, ioe_filename = Nothing })) b)
Related to https://ghc.haskell.org/trac/ghc/ticket/9236. Try this:
import System.IO
import System.IO.Error
main = do
h <- openFile "Tests/houseisclean.jpg" ReadMode
r <- try (hGetContents h) >>= either exn str
hClose h
where
exn (e :: IOError) = putStrLn ("exn=" ++ show (ioe_handle e, ioe_type e, ioe_location e, ioe_description e, ioe_errno e, ioe_filename e))
str s = putStrLn ("s=" ++ show s)
The exception gets thrown and caught after the string result starts
being printed. You can see the open quote.
-}
]
{-
, TestLabel "ByteString" $
TestCase (do b <- readProcessWithExitCode "Tests/Test1.hs" [] B.empty
assertEqual "ByteString" (ExitFailure 123, fromString "", fromString "This is an error message.\n") b)
-}
, TestLabel "Lazy" $
TestCase (do l <- readProcessWithExitCode "Tests/Test1.hs" [] L.empty
assertEqual "Lazy ByteString" (ExitFailure 123, lazyFromString "", lazyFromString "This is an error message.\n") l)
{-
, TestLabel "Text" $
TestCase (do t <- readProcessWithExitCode "Tests/Test1.hs" [] T.empty
assertEqual "Text" (ExitFailure 123, T.pack "", T.pack "This is an error message.\n") t)
-}
, TestLabel "LazyText" $
TestCase (do lt <- readProcessWithExitCode "Tests/Test1.hs" [] LT.empty
assertEqual "LazyText" (ExitFailure 123, LT.pack "", LT.pack "This is an error message.\n") lt)
{-
, TestLabel "String" $
TestCase (do s <- readProcessWithExitCode "Tests/Test1.hs" [] ""
assertEqual "String" (ExitFailure 123, "", "This is an error message.\n") s)
-}
, TestLabel "pnmfile" $
TestCase (do out <- L.readFile "Tests/penguin.jpg" >>=
readCreateProcess (proc "djpeg" []) >>=
readCreateProcess (proc "pnmfile" [])
assertEqual "pnmfile" (lazyFromString "stdin:\tPPM raw, 96 by 96 maxval 255\n") out)
, TestLabel "pnmfile2" $
TestCase (do jpg <- L.readFile "Tests/penguin.jpg"
(code1, pnm, err1) <- readCreateProcessWithExitCode (proc "djpeg" []) jpg
out2 <- readCreateProcess (proc "pnmfile" []) pnm
assertEqual "pnmfile2" (ExitSuccess, empty, 2192, 27661, lazyFromString "stdin:\tPPM raw, 96 by 96 maxval 255\n") (code1, err1, length jpg, length pnm, out2))
, TestLabel "file closed 1" $
TestCase (do result <- readCreateProcessWithExitCode (proc "Tests/Test4.hs" []) (lazyFromString "a" :: L.ByteString)
assertEqual "file closed 1" (ExitSuccess, (lazyFromString "a"), (lazyFromString "Read one character: 'a'\n")) result)
, TestLabel "file closed 2" $
TestCase (do result <- readCreateProcessWithExitCode (proc "Tests/Test4.hs" []) (lazyFromString "" :: L.ByteString)
assertEqual "file closed 2" (ExitFailure 1, empty, (lazyFromString "Test4.hs: <stdin>: hGetChar: end of file\n")) result)
, TestLabel "file closed 3" $
TestCase (do result <- readCreateProcessWithExitCode (proc "Tests/Test4.hs" []) ("abcde" :: LT.Text)
assertEqual "file closed 3" (ExitSuccess, "a", "Read one character: 'a'\n") result)
, TestLabel "file closed 4" $
TestCase (do result <- readCreateProcessWithExitCode (proc "Tests/Test4.hs" []) ("abcde" :: LT.Text)
assertEqual "file closed 4" (ExitSuccess, "a", "Read one character: 'a'\n") result)
, TestLabel "exit code 0" $
TestCase (do result <- readCreateProcess (shell "echo \"hello, world\"") ("" :: LT.Text)
assertEqual "exit code 1" "\"hello, world\\n\"" (show result)
)
-- I'd like to test readCreateProcess but I can't seem to catch the exception it throws
, TestLabel "exit code 1" $
TestCase (do result <- readCreateProcessWithExitCode (proc "bash" ["-e", "exit", "1"]) ("" :: LT.Text)
assertEqual "exit code 1" "(ExitFailure 1,\"\",\"bash: exit: No such file or directory\\n\")" (show result)
)
])
| ddssff/process-listlike-old | Tests/Main.hs | mit | 13,726 | 0 | 29 | 4,575 | 2,759 | 1,434 | 1,325 | 160 | 5 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLOListElement
(js_setCompact, setCompact, js_getCompact, getCompact, js_setStart,
setStart, js_getStart, getStart, js_setReversed, setReversed,
js_getReversed, getReversed, js_setType, setType, js_getType,
getType, HTMLOListElement, castToHTMLOListElement,
gTypeHTMLOListElement)
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 (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
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.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"compact\"] = $2;"
js_setCompact :: HTMLOListElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.compact Mozilla HTMLOListElement.compact documentation>
setCompact :: (MonadIO m) => HTMLOListElement -> Bool -> m ()
setCompact self val = liftIO (js_setCompact (self) val)
foreign import javascript unsafe "($1[\"compact\"] ? 1 : 0)"
js_getCompact :: HTMLOListElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.compact Mozilla HTMLOListElement.compact documentation>
getCompact :: (MonadIO m) => HTMLOListElement -> m Bool
getCompact self = liftIO (js_getCompact (self))
foreign import javascript unsafe "$1[\"start\"] = $2;" js_setStart
:: HTMLOListElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.start Mozilla HTMLOListElement.start documentation>
setStart :: (MonadIO m) => HTMLOListElement -> Int -> m ()
setStart self val = liftIO (js_setStart (self) val)
foreign import javascript unsafe "$1[\"start\"]" js_getStart ::
HTMLOListElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.start Mozilla HTMLOListElement.start documentation>
getStart :: (MonadIO m) => HTMLOListElement -> m Int
getStart self = liftIO (js_getStart (self))
foreign import javascript unsafe "$1[\"reversed\"] = $2;"
js_setReversed :: HTMLOListElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.reversed Mozilla HTMLOListElement.reversed documentation>
setReversed :: (MonadIO m) => HTMLOListElement -> Bool -> m ()
setReversed self val = liftIO (js_setReversed (self) val)
foreign import javascript unsafe "($1[\"reversed\"] ? 1 : 0)"
js_getReversed :: HTMLOListElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.reversed Mozilla HTMLOListElement.reversed documentation>
getReversed :: (MonadIO m) => HTMLOListElement -> m Bool
getReversed self = liftIO (js_getReversed (self))
foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType ::
HTMLOListElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.type Mozilla HTMLOListElement.type documentation>
setType ::
(MonadIO m, ToJSString val) => HTMLOListElement -> val -> m ()
setType self val = liftIO (js_setType (self) (toJSString val))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
HTMLOListElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement.type Mozilla HTMLOListElement.type documentation>
getType ::
(MonadIO m, FromJSString result) => HTMLOListElement -> m result
getType self = liftIO (fromJSString <$> (js_getType (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLOListElement.hs | mit | 4,067 | 56 | 10 | 556 | 931 | 530 | 401 | 55 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Spellcheck.UniformLanguageModel
-- Copyright : (C) 2013 Yorick Laupa
-- License : (see the file LICENSE)
--
-- Maintainer : Yorick Laupa <[email protected]>
-- Stability : provisional
-- Portability : non-portable
--
-- A uniform language model. This simply counts the vocabulary size V of the
-- training corpus and assigns p(w) = 1/V for any word.
----------------------------------------------------------------------------
module Data.Spellcheck.UniformLanguageModel
( UniformLanguageModel
, train
, score
) where
import Data.Foldable (foldMap)
import Data.Monoid
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Vector as V
import Data.Spellcheck.Datum
import Data.Spellcheck.HolbrookCorpus
import Data.Spellcheck.LanguageModel
import Data.Spellcheck.Sentence
data UniformLanguageModel = ULM !(S.Set T.Text)
instance Monoid UniformLanguageModel where
mempty = ULM S.empty
mappend (ULM e) (ULM e') = ULM (S.union e e')
instance LanguageModel UniformLanguageModel where
train corpus = do
xs <- corpusLoad corpus
let model = foldMap (foldMap go) xs
return model
where
go (SDatum d) = ULM $ S.singleton (datumWord d)
go _ = ULM S.empty
score (ULM s) stc =
(fromIntegral $ V.length stc) * log (fromIntegral $ S.size s)
| YoEight/spellcheck | lib/Data/Spellcheck/UniformLanguageModel.hs | mit | 1,512 | 0 | 13 | 332 | 310 | 171 | 139 | 28 | 0 |
module Automata.Helpers where
import Data.Set (Set)
import qualified Data.Set as S
import Automata.Types
cartProd :: (Ord a, Ord b) => Set a -> Set b -> Set (a, b)
cartProd set1 set2 = S.fromList [(x,y) | x <- S.toList set1, y <- S.toList set2]
| terrelln/automata | src/Automata/Helpers.hs | mit | 247 | 0 | 10 | 46 | 122 | 66 | 56 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Process
( process
, processPipe
, htmlPipeline
, mdPipeline
, codePipeline ) where
import Prelude hiding (readFile, writeFile, getContents, putStr)
import Data.Text.IO (writeFile, readFile, getContents, putStr)
import System.FilePath.Posix (takeFileName, dropExtension)
import System.Directory
import System.FilePath.Posix
import Data.List (intercalate)
import qualified Data.Text as T
import Parse (encode)
import Code
import Html
import Markdown
import Types
process pipes file = do
stream <- readFile file
processString writeFile stream fileName pipes >> return ()
where
fileName = dropExtension $ takeFileName file
processPipe pipes = do
input <- getContents
processString writeStdout input "-" pipes >> return ()
where
writeStdout = (\name output -> putStr output)
processString writeOutput input fileName pipes = do
encoded <- return $ encode input
mapM_ (\f -> f fileName encoded writeOutput) pipes >> return ()
htmlPipeline dir mCss mLang name enc writeOutput = do
maybeCss <- cssRelativeToOutput dir mCss
let path = (addTrailingPathSeparator dir) ++ name ++ ".html"
output = Html.generate maybeCss mLang name enc
writeOutput path output
mdPipeline dir css mLang name enc writeOutput = writeOutput path output
where
path = (addTrailingPathSeparator dir) ++ name ++ ".md"
output = Markdown.generate mLang name enc
codePipeline dir css mLang name enc writeOutput = writeOutput path output
where
path = (addTrailingPathSeparator dir) ++ name
output = Code.generate enc
cssRelativeToOutput :: String -> Maybe String -> IO (Maybe String)
cssRelativeToOutput output mCss =
case mCss of
Nothing -> return Nothing
Just css -> do
getCurrentDirectory >>= canonicalizePath >>= \path -> return $ Just $ (join' . helper' . trim' . split') path
where
moves = filter (\str -> str /= ".") $ splitDirectories output
split' = splitDirectories
trim' = trimToMatchLength moves
helper' = reversePath moves []
join' path = (intercalate "/" path) </> css
trimToMatchLength list listToTrim =
let len1 = length list
len2 = length listToTrim
in
drop (len2 - len1) listToTrim
reversePath [] solution curPathParts = solution
reversePath (fst:rest) solution curPathParts =
if fst == ".."
then reversePath rest ((last curPathParts) : solution) (init curPathParts)
else reversePath rest (".." : solution) (curPathParts ++ [fst])
| tcrs/lit | src/Process.hs | gpl-2.0 | 2,571 | 0 | 17 | 560 | 791 | 408 | 383 | -1 | -1 |
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
module Web.BitTorrent.Tracker.Handlers.Scrape (
handleScrapeRequest
) where
import qualified Data.HashMap.Strict as Map
import qualified Data.Sequence as Sequence
import qualified Web.BitTorrent.Tracker.Utils as Utils
import Web.BitTorrent.Tracker.Types
import Web.BitTorrent.Tracker.Handlers.Common
handleScrapeRequest :: ScrapeRequestInner -> AppM Response
handleScrapeRequest innerRequest = do
let transactionID = _transactionID (innerRequest :: ScrapeRequestInner)
infoHashes = _infoHashes (innerRequest :: ScrapeRequestInner)
peerLists <- getPeerLists infoHashes
return $ ScrapeResponse $ ScrapeResponseInner {
_transactionID = transactionID,
_torrentStatistics = fmap buildStats peerLists
}
getPeerLists :: Sequence.Seq InfoHash -> AppM (Sequence.Seq (Sequence.Seq Peer))
getPeerLists infoHashes = do
tm <- Utils.getTorrentMap
return $ foldr (f tm) Sequence.empty infoHashes
where
f tm infoHash xs =
case Map.lookup infoHash tm of
Just peers -> peers Sequence.<| xs
Nothing -> xs
buildStats :: Sequence.Seq Peer -> TorrentScrapeStatistics
buildStats peers = TorrentScrapeStatistics {
_seeders = countSeeders peers,
_completed = NumberOfDownloads 0, -- Not implemented
_leechers = countLeechers peers
}
| greatest-ape/hs-bt-tracker | src/Web/BitTorrent/Tracker/Handlers/Scrape.hs | gpl-3.0 | 1,435 | 0 | 11 | 298 | 320 | 175 | 145 | 30 | 2 |
module WildFireFrontend where
import Graphics.Rendering.OpenGL as GL
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL (($=))
import Data.IORef
import Control.Monad
import WildFireBackend as Back
winSizeX :: GLsizei
winSizeX = 800
winSizeY :: GLsizei
winSizeY = 800
winSize :: GL.Size
winSize = (GL.Size winSizeX winSizeY)
winDimXInt :: GL.Size -> Int
winDimXInt (Size x y) = fromIntegral x
winDimYInt :: GL.Size -> Int
winDimYInt (Size x y) = fromIntegral y
green :: GL.Color3 GLdouble
green = GL.Color3 0.0 1.0 0.0
black :: GL.Color3 GLdouble
black = GL.Color3 0.0 0.0 0.0
greenShade :: GLdouble -> GL.Color3 GLdouble
greenShade s = GL.Color3 0.0 s 0.0
redShade :: GLdouble -> GL.Color3 GLdouble
redShade s = GL.Color3 s 0.0 0.0
initialize = do
GLFW.initialize
-- open window
GLFW.openWindow winSize [GLFW.DisplayAlphaBits 8] GLFW.Window
GLFW.windowTitle $= "GLFW Demo"
GL.shadeModel $= GL.Smooth
-- enable antialiasing
GL.lineSmooth $= GL.Enabled
GL.blend $= GL.Enabled
GL.blendFunc $= (GL.SrcAlpha, GL.OneMinusSrcAlpha)
GL.lineWidth $= 1.5
-- set the color to clear background
GL.clearColor $= Color4 1 1 1 0
-- set 2D orthogonal view inside windowSizeCallback because
-- any change to the Window size should result in different
-- OpenGL Viewport.
GLFW.windowSizeCallback $= \ size@(GL.Size w h) ->
do
GL.viewport $= (GL.Position 0 0, size)
GL.matrixMode $= GL.Projection
GL.loadIdentity
GL.ortho2D 0 (realToFrac w) (realToFrac h) 0
shutdown :: IO ()
shutdown = do
GLFW.closeWindow
GLFW.terminate
renderFrame :: [Back.CellState] -> (Int, Int) -> IO ()
renderFrame cells (dimX, dimY) = do
GL.clear [GL.ColorBuffer]
GL.renderPrimitive GL.Quads $ mapM_ (\c -> renderCell c cellDimPixels ) cells
GLFW.swapBuffers
where
cellDimPixels = cellDimensions (dimX, dimY)
renderCell :: Back.CellState -> (GLdouble, GLdouble) -> IO ()
renderCell cell (cellWidth, cellHeight) = do
GL.color $ color
GL.vertex topLeft
GL.vertex topRight
GL.vertex bottomRight
GL.vertex bottomLeft
where
(xIdx, yIdx) = csCoord cell
xCoord = (cellWidth * fromIntegral xIdx) :: GLdouble
yCoord = (cellHeight * fromIntegral yIdx) :: GLdouble
topLeft = GL.Vertex3 xCoord yCoord 0.0
topRight = GL.Vertex3 (xCoord + cellWidth) yCoord 0.0
bottomLeft = GL.Vertex3 xCoord (yCoord + cellHeight) 0.0
bottomRight = GL.Vertex3 (xCoord + cellWidth) (yCoord + cellHeight) 0.0
color = cellColor cell
cellColor :: Back.CellState -> GL.Color3 GLdouble
cellColor cell
| state == LIVING = greenShade fuel
| state == BURNING = redShade fuel
| state == DEAD = black
where
state = csStatus cell
fuel = csFuel cell
cellDimensions :: (Int, Int) -> (GLdouble, GLdouble)
cellDimensions (dimX, dimY) = (cellWidth, cellHeight)
where
cellWidth = ( fromIntegral (winDimXInt winSize) / fromIntegral dimX ) :: GLdouble
cellHeight = ( fromIntegral (winDimYInt winSize) / fromIntegral dimY ) :: GLdouble
checkMousePressed :: IORef Bool -> IO (Maybe (Int, Int))
checkMousePressed ref = do
b <- GLFW.getMouseButton GLFW.ButtonLeft
case b of
GLFW.Release -> do
writeIORef ref True
return Nothing
GLFW.Press -> do
previouslyReleased <- readIORef ref
writeIORef ref False
case previouslyReleased of
True -> do
(GL.Position x y) <- GL.get GLFW.mousePos
return (Just (fromIntegral x, fromIntegral y))
otherwise -> do
return Nothing
pixelCoordToCellCoord :: (Int, Int) -> (Int, Int) -> CellCoord
pixelCoordToCellCoord (xCoord, yCoord) (xDim, yDim) = (xIdx, yIdx)
where
x = fromIntegral xCoord
y = fromIntegral yCoord
xIdx = floor (x / cellWidth)
yIdx = floor (y / cellHeight)
(cellWidth, cellHeight) = cellDimensions (xDim, yDim) | thalerjonathan/phd | coding/prototyping/haskell/YampaWildfire/src/WildFireFrontend.hs | gpl-3.0 | 4,092 | 0 | 21 | 1,036 | 1,321 | 675 | 646 | 100 | 3 |
{-# LANGUAGE NamedFieldPuns, NoImplicitPrelude, OverloadedStrings, ExtendedDefaultRules, RecordWildCards#-}
module Main where
import BasicPrelude hiding ((</>), (<.>), FilePath)
import Filesystem.Path.CurrentOS
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.Map as M
import Control.Error
import Control.Lens
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit
import Data.Attoparsec.Text
import Nix.Packages
import Nix.Commands
import Nix.StorePaths
import Utils
import qualified Nix.OutputParser as P
---------------------------
-- Tests
---------------------------
ex_someInstalling :: [Text]
ex_someInstalling =
[ "installing `rxvt-unicode-9.16-with-perl'"
, " installing `subversion-1.7.13'"
, "installing `texlive-full'"
]
ex_someInstalling2 :: [Text]
ex_someInstalling2 =
[ "installing `rxvt-unicode-9.16-with-perl'"
, " installing `subversion-1.7.13'"
, "these derivations will be built:"
, " /nix/store/4w40vbz4cix0z474shpcnmfxjc7kh69z-texlive-core-2014.drv"
, "installing `texlive-full'"
]
ex_someUninstalling :: [Text]
ex_someUninstalling =
[ "uninstalling `texlive-full'"
, " uninstalling `aspell-0.60.6.1'"
, "uninstalling `aspell-dict-de-20030222-1'"
, "uninstalling `aspell-dict-en-7.1-0'"
]
ex_someBuilding :: [Text]
ex_someBuilding =
[ "/nix/store/njrzm1kkj9k22vr7xaggwjmz6cm7nsxv-haskell-env-ghc-7.6.3.drv"
]
ex_someFetching :: [Text]
ex_someFetching =
[ " /nix/store/h3q083n3yaap9vhcsd1hlrkcs8qph7fb-clucene-core-2.3.3.4"
, " /nix/store/hb2c7hbsxksgzl50n35dw42bp9z389s6-parcellite-1.1.6"
, " /nix/store/hcz4gl5nhchawv4b162xmcnn4gqw9z49-alex-3.0.5"
]
test_someInstalling = testCase "installing" $
rights (fmap (parseOnly P.fromInstalling) ex_someInstalling)
@=?
["rxvt-unicode-9.16-with-perl","subversion-1.7.13","texlive-full"]
test_someInstalling2 = testCase "installing2" $
rights (fmap (parseOnly P.fromInstalling) ex_someInstalling2)
@=?
["rxvt-unicode-9.16-with-perl","subversion-1.7.13","texlive-full"]
test_someUninstalling = testCase "uninstalling" $
rights (fmap (parseOnly P.fromUninstalling) ex_someUninstalling)
@=?
[ "texlive-full"
, "aspell-0.60.6.1"
, "aspell-dict-de-20030222-1"
, "aspell-dict-en-7.1-0"
]
test_someBuilding = testCase "building" $
rights (fmap (parseOnly p_fromBuilding) ex_someBuilding)
@=?
["haskell-env-ghc-7.6.3"]
test_someFetched = testCase "fetching" $
rights (fmap (parseOnly p_fromFetching) ex_someFetching)
@=?
[ "clucene-core-2.3.3.4"
, "parcellite-1.1.6"
, "alex-3.0.5"
]
main :: IO ()
main = defaultMain
[test_someInstalling
, test_someBuilding
, test_someUninstalling
, test_someFetched
, testGroup "successfull parses" $
[ testCase "local" $
parseOnly P.fromLocalQuery "clucene-core-2.3.3.4 /nix/store/bla"
@?=
Right (Just ("clucene-core-2.3.3.4", "/nix/store/bla", Present))
, testCase "remote prebuilt" $
parseOnly P.fromRemoteQuery "--S clucene-core-2.3.3.4 /nix/store/bla"
@?=
Right (Just ("clucene-core-2.3.3.4", "/nix/store/bla", Prebuilt))
, testCase "remote source" $
parseOnly P.fromRemoteQuery "--- clucene-core-2.3.3.4 /nix/store/bla"
@?=
Right (Just ("clucene-core-2.3.3.4", "/nix/store/bla", Source))
]
, testGroup "failing parses" $
[ testCase "missing path" $
(length . lefts . map (parseOnly P.fromQuery)
$ ["texlive-full ", "texlive-full"])
@?= 2
, testCase "parse local with status" $
isLeft (parseOnly P.fromLocalQuery "--- clucene-core-2.3.3.4 /nix/store/bla")
@?=
True
]
, testGroup "commands" $
[ testCase "install declared packages into profile" $
nixCmdStrings
(Nix { nixCommand = (NixInstall (NIOs False Nothing))
, nixSelection = Nothing
, nixDryRun = True
, nixProfile = ("some" </> "profile")
, nixFile = (Just $ "somedir" </> "declared-packages.nix")
, nixInclude = Nothing
})
@?=
("nix-env", [ "--dry-run"
, "--profile", "some/profile"
, "--file", "somedir/declared-packages.nix"
, "--install"
, "*"
])
, testCase "install selection of declared packages into profile" $
nixCmdStrings
(Nix { nixCommand = (NixInstall (NIOs False Nothing))
, nixSelection = (Just ["a", "b", "c"])
, nixDryRun = True
, nixProfile = ("some" </> "profile")
, nixFile = (Just $ "somedir" </> "declared-packages.nix")
, nixInclude = Nothing
})
@?=
("nix-env", [ "--dry-run"
, "--profile", "some/profile"
, "--file", "somedir/declared-packages.nix"
, "--install"
, "a"
, "b"
, "c"
])
, testCase "install all packages from profile into profile" $
over _2 S.fromList (nixCmdStrings
(Nix { nixCommand = (NixInstall (NIOs False (Just $ "source" </> "profile")))
, nixSelection = Nothing
, nixDryRun = True
, nixProfile = ("some" </> "profile")
, nixFile = Nothing
, nixInclude = Nothing
}))
@?=
("nix-env", S.fromList [ "--dry-run"
, "--profile", "some/profile"
, "--install"
, "--from-profile", "source/profile"
, "*"
])
, testCase "remove all packages from a profile" $
nixCmdStrings
(Nix { nixCommand = (NixUninstall)
, nixSelection = Nothing
, nixDryRun = False
, nixProfile = ("some" </> "profile")
, nixFile = Nothing
, nixInclude = Nothing
})
@?=
("nix-env", [ "--profile", "some/profile", "-e", "*"])
]
, testGroup "update"
[
testCase "match1" $
findUpdate' "cabal2nix-1.60" "cabal2nix-1.58"
@?= Just (mkUpd ("cabal2nix", "1.58", "1.60"))
, testCase "match2" $
findUpdate' "git-full-1.9.0 /nix/store/bla1" "git-1.8.5.2-full /nix/store/bla2" @?= Nothing
, testCase "match3" $
findUpdate' "git-annex-5.20140306" "git-annex-5.20140108"
@?= Just (mkUpd ("git-annex", "5.20140108", "5.20140306"))
, testCase "no match" $
findUpdate' "git-1.8.5.2-full" "giti-full-1.9.0" @?= Nothing
, testCase "no match, same prefix" $
findUpdate' "git-1.9.4" "git-annex-5.20140717" @?= Nothing
, testCase "filterUpd" $
calculateUpdatesFromLists
[ "cabal2nix-1.60"
, "duplicity-0.6.23"
, "feh-2.10"
, "git-annex-5.20140306"
]
[ "git-annex-5.20140108"
, "cabal-dev-0.9.2"
, "cabal2nix-1.58"
, "duplicity-0.6.22"
, "exif-0.6.21"
]
@?= expectedUpdates
[ ("cabal2nix", "1.58", "1.60")
, ("duplicity", "0.6.22", "0.6.23")
, ("git-annex", "5.20140108", "5.20140306")
]
["feh-2.10"]
[ "cabal-dev-0.9.2"
, "exif-0.6.21"
]
, testCase "filterUpd_same_prefixes" $
calculateUpdatesFromLists
[ "cabal2nix-1.60"
, "duplicity-0.6.23"
, "feh-2.10"
, "git-2.0"
, "git-annex-5.20140306"
]
[ "git-annex-5.20140108"
, "cabal-dev-0.9.2"
, "cabal2nix-1.58"
, "duplicity-0.6.22"
, "git-1.8"
, "exif-0.6.21"
]
@?= expectedUpdates
[ ("cabal2nix", "1.58" ,"1.60")
, ("duplicity", "0.6.22" ,"0.6.23")
, ("git-annex", "5.20140108", "5.20140306")
, ("git", "1.8", "2.0")
]
["feh-2.10"]
[ "cabal-dev-0.9.2" , "exif-0.6.21"]
, testCase "unversioned" $
let texliveOld = packageWithPathFromText "texlive-full /nix/store/bla1"
texliveNew = packageWithPathFromText "texlive-full /nix/store/bla2"
in (view _1 $ calculateUpdates (M.fromList [texliveNew])
(S.fromList [fst texliveOld])
) @?= S.fromList [ Upd { uName = "texlive-full"
, uOld = ""
, uOldPath = "/nix/store/bla1"
, uNew = ""
, uNewPath = "/nix/store/bla2"
, uStatus = Present
}
]
]
, testGroup "Result views"
[ testCase "wanted" $
wanted ex_result1 @?= fromPackageListWithStatus ["newpackage-1", "somepackage-1.1.1", "Agda-3.4", "emacs-24", "not-wanted-222", "libreoffice-2.3"] -- TODO: not-wanted-222 has the wrong name.. store paths are always wanted
, testCase "wantedFromDeclared" $
wantedFromDeclared ex_result1
@?= fromPackageListWithStatus["newpackage-1", "somepackage-1.1.1"]
, testCase "unversioned updates" $
wanted ex_texliveResults
@?= M.fromList
[ (Pwp { pwpPkg = VPkg { pName = "texlive-full" , pVer = ""}
, pwpPath = "/nix/store/lynr5fvcpp21rzjaz1ahjzn1zd7r0dkr-TeXLive-linkdir"
}, Present)
]
, testCase "unversioned blocked updates" $
blockedUpdates (ex_texliveResults { rStorePaths = M.keysSet (rInstalled ex_texliveResults) })
@?= S.fromList
[ Upd { uName = "texlive-full"
, uOld = ""
, uNew = ""
, uOldPath = "/nix/store/4lyy252ablh9snx5cr4dvfic0k0fcr0y-TeXLive-linkdir"
, uNewPath = "/nix/store/lynr5fvcpp21rzjaz1ahjzn1zd7r0dkr-TeXLive-linkdir"
, uStatus = Present
}
]
]
, testGroup "Store paths" $
let twoResults =
[ Right $ Pwp { pwpPkg = VPkg "auctex-zathura" "0.1.0.3"
, pwpPath = "/nix/store/wjmb5383wknpb9v3q2dpqbvi0zvxcs1w-auctex-zathura-0.1.0.3"}
, Right $ Pwp { pwpPkg = VPkg "owncloud-client" "1.7.1"
, pwpPath = "/nix/store/l83r37rzk53f6qmyqfn8hnr4i02lgja8-owncloud-client-1.7.1"}]
in [ testCase "Empty file" $ parsePackageFromStorePathContents "" @?= []
, testCase "Easy paths" $
parsePackageFromStorePathContents "\
\/nix/store/wjmb5383wknpb9v3q2dpqbvi0zvxcs1w-auctex-zathura-0.1.0.3\n\
\/nix/store/l83r37rzk53f6qmyqfn8hnr4i02lgja8-owncloud-client-1.7.1\n\
\"
@?= twoResults
, testCase "Easy path w/ newlines" $
parsePackageFromStorePathContents "\n\
\/nix/store/wjmb5383wknpb9v3q2dpqbvi0zvxcs1w-auctex-zathura-0.1.0.3\n\n\n\
\/nix/store/l83r37rzk53f6qmyqfn8hnr4i02lgja8-owncloud-client-1.7.1\n\
\"
@?= twoResults
, testCase "Easy path w/ newlines and comments" $
parsePackageFromStorePathContents "\n\
\/nix/store/wjmb5383wknpb9v3q2dpqbvi0zvxcs1w-auctex-zathura-0.1.0.3\n\n\n\
\ # A comment\n\n\
\/nix/store/l83r37rzk53f6qmyqfn8hnr4i02lgja8-owncloud-client-1.7.1\n\
\ ## Another one\n\n\
\"
@?= twoResults
, testCase "Easy path without trailing newlines" $
parsePackageFromStorePathContents "\n\
\/nix/store/wjmb5383wknpb9v3q2dpqbvi0zvxcs1w-auctex-zathura-0.1.0.3\n\n\n\
\ # A comment\n\n\
\/nix/store/l83r37rzk53f6qmyqfn8hnr4i02lgja8-owncloud-client-1.7.1"
@?= twoResults
]
]
ex_result1 = Results { rStorePaths = S.fromList $ map (mkOld . parseVersionedPackage)
[ "libreoffice-2.3"
, "Agda-3.4"
, "emacs-24"
, "not-wanted-222"
]
, rDeclared = M.fromList $ map (addPresentStatus . mkOld . parseVersionedPackage)
[ "libreoffice-2.4"
, "somepackage-1.1.1"
, "newpackage-1"
, "Agda-3.4"
, "emacs-25"
]
, rInstalled = M.fromList $ map (addPresentStatus . mkOld . parseVersionedPackage)
[ "libreoffice-2.4"
, "somepackage-1.1.2"
, "remove-me-1"
]
}
ex_texliveResults = Results { rStorePaths = S.empty
, rDeclared = M.fromList
. map (packageWithPathFromText)
$ [ "texlive-full /nix/store/lynr5fvcpp21rzjaz1ahjzn1zd7r0dkr-TeXLive-linkdir"
]
, rInstalled = M.fromList
. map (packageWithPathFromText)
$ [ "texlive-full /nix/store/4lyy252ablh9snx5cr4dvfic0k0fcr0y-TeXLive-linkdir"
]
}
findUpdate' p1 p2 = findUpdate (mkNew . parseVersionedPackage $ p1)
(mkOld . parseVersionedPackage $ p2)
fromPackageListWithStatus ps = M.fromList . map (addPresentStatus . mkOld . parseVersionedPackage) $ ps
fromPackageList ps = S.fromList . map (mkOld . parseVersionedPackage) $ ps
packageWithPathFromText s =
fromJustE ("packageWithPathFromText: no parse of "<>s)
. preview (_Right._Just)
. P.parsePackageWithPath P.fromLocalQuery
$ s
mkUpd (uName, uOld, uNew) = Upd { uName, uOld, uNew
, uOldPath = "/nix/store/bl1"
, uNewPath = "/nix/store/bl2"
, uStatus = Present }
mkOld vpkg = Pwp { pwpPkg = vpkg, pwpPath = "/nix/store/bl1"}
mkNew vpkg = (Pwp { pwpPkg = vpkg, pwpPath = "/nix/store/bl2"} , Present )
mkNewPackages = M.fromList . map (mkNew . parseVersionedPackage)
mkOldPackages = S.fromList . map (mkOld . parseVersionedPackage)
p_fromBuilding = P.fromBuilding "/nix/store"
p_fromFetching = P.fromFetching "/nix/store"
calculateUpdatesFromLists news olds =
calculateUpdates (mkNewPackages news)
(mkOldPackages olds)
expectedUpdates :: [(Text, Text, Text)] -> [Text] -> [Text]
-> (Set Upd, Map PackageWithPath PkgStatus, Set PackageWithPath)
expectedUpdates upds added removed =
( S.fromList . map mkUpd $ upds
, mkNewPackages added
, mkOldPackages removed )
addPresentStatus p = (p, Present)
| lu-fennell/nix-env-rebuild | src/Nix/Test/EnvRebuild.hs | gpl-3.0 | 15,581 | 0 | 23 | 5,423 | 2,645 | 1,489 | 1,156 | 306 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.DirectConnect.DescribeVirtualGateways
-- 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.
-- | Returns a list of virtual private gateways owned by the AWS account.
--
-- You can create one or more AWS Direct Connect private virtual interfaces
-- linking to a virtual private gateway. A virtual private gateway can be
-- managed via Amazon Virtual Private Cloud (VPC) console or the <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnGateway.html EC2CreateVpnGateway> action.
--
-- <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeVirtualGateways.html>
module Network.AWS.DirectConnect.DescribeVirtualGateways
(
-- * Request
DescribeVirtualGateways
-- ** Request constructor
, describeVirtualGateways
-- * Response
, DescribeVirtualGatewaysResponse
-- ** Response constructor
, describeVirtualGatewaysResponse
-- ** Response lenses
, dvgrVirtualGateways
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.DirectConnect.Types
import qualified GHC.Exts
data DescribeVirtualGateways = DescribeVirtualGateways
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DescribeVirtualGateways' constructor.
describeVirtualGateways :: DescribeVirtualGateways
describeVirtualGateways = DescribeVirtualGateways
newtype DescribeVirtualGatewaysResponse = DescribeVirtualGatewaysResponse
{ _dvgrVirtualGateways :: List "virtualGateways" VirtualGateway
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeVirtualGatewaysResponse where
type Item DescribeVirtualGatewaysResponse = VirtualGateway
fromList = DescribeVirtualGatewaysResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _dvgrVirtualGateways
-- | 'DescribeVirtualGatewaysResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dvgrVirtualGateways' @::@ ['VirtualGateway']
--
describeVirtualGatewaysResponse :: DescribeVirtualGatewaysResponse
describeVirtualGatewaysResponse = DescribeVirtualGatewaysResponse
{ _dvgrVirtualGateways = mempty
}
-- | A list of virtual private gateways.
dvgrVirtualGateways :: Lens' DescribeVirtualGatewaysResponse [VirtualGateway]
dvgrVirtualGateways =
lens _dvgrVirtualGateways (\s a -> s { _dvgrVirtualGateways = a })
. _List
instance ToPath DescribeVirtualGateways where
toPath = const "/"
instance ToQuery DescribeVirtualGateways where
toQuery = const mempty
instance ToHeaders DescribeVirtualGateways
instance ToJSON DescribeVirtualGateways where
toJSON = const (toJSON Empty)
instance AWSRequest DescribeVirtualGateways where
type Sv DescribeVirtualGateways = DirectConnect
type Rs DescribeVirtualGateways = DescribeVirtualGatewaysResponse
request = post "DescribeVirtualGateways"
response = jsonResponse
instance FromJSON DescribeVirtualGatewaysResponse where
parseJSON = withObject "DescribeVirtualGatewaysResponse" $ \o -> DescribeVirtualGatewaysResponse
<$> o .:? "virtualGateways" .!= mempty
| dysinger/amazonka | amazonka-directconnect/gen/Network/AWS/DirectConnect/DescribeVirtualGateways.hs | mpl-2.0 | 4,042 | 0 | 10 | 720 | 417 | 252 | 165 | 54 | 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.Cloudbuild.Projects.Locations.Builds.Create
-- 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)
--
-- Starts a build with the specified configuration. This method returns a
-- long-running \`Operation\`, which includes the build ID. Pass the build
-- ID to \`GetBuild\` to determine the build status (such as \`SUCCESS\` or
-- \`FAILURE\`).
--
-- /See:/ <https://cloud.google.com/cloud-build/docs/ Cloud Build API Reference> for @cloudbuild.projects.locations.builds.create@.
module Network.Google.Resource.Cloudbuild.Projects.Locations.Builds.Create
(
-- * REST Resource
ProjectsLocationsBuildsCreateResource
-- * Creating a Request
, projectsLocationsBuildsCreate
, ProjectsLocationsBuildsCreate
-- * Request Lenses
, proParent
, proXgafv
, proUploadProtocol
, proAccessToken
, proUploadType
, proPayload
, proProjectId
, proCallback
) where
import Network.Google.ContainerBuilder.Types
import Network.Google.Prelude
-- | A resource alias for @cloudbuild.projects.locations.builds.create@ method which the
-- 'ProjectsLocationsBuildsCreate' request conforms to.
type ProjectsLocationsBuildsCreateResource =
"v1" :>
Capture "parent" Text :>
"builds" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "projectId" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Build :> Post '[JSON] Operation
-- | Starts a build with the specified configuration. This method returns a
-- long-running \`Operation\`, which includes the build ID. Pass the build
-- ID to \`GetBuild\` to determine the build status (such as \`SUCCESS\` or
-- \`FAILURE\`).
--
-- /See:/ 'projectsLocationsBuildsCreate' smart constructor.
data ProjectsLocationsBuildsCreate =
ProjectsLocationsBuildsCreate'
{ _proParent :: !Text
, _proXgafv :: !(Maybe Xgafv)
, _proUploadProtocol :: !(Maybe Text)
, _proAccessToken :: !(Maybe Text)
, _proUploadType :: !(Maybe Text)
, _proPayload :: !Build
, _proProjectId :: !(Maybe Text)
, _proCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsBuildsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'proParent'
--
-- * 'proXgafv'
--
-- * 'proUploadProtocol'
--
-- * 'proAccessToken'
--
-- * 'proUploadType'
--
-- * 'proPayload'
--
-- * 'proProjectId'
--
-- * 'proCallback'
projectsLocationsBuildsCreate
:: Text -- ^ 'proParent'
-> Build -- ^ 'proPayload'
-> ProjectsLocationsBuildsCreate
projectsLocationsBuildsCreate pProParent_ pProPayload_ =
ProjectsLocationsBuildsCreate'
{ _proParent = pProParent_
, _proXgafv = Nothing
, _proUploadProtocol = Nothing
, _proAccessToken = Nothing
, _proUploadType = Nothing
, _proPayload = pProPayload_
, _proProjectId = Nothing
, _proCallback = Nothing
}
-- | The parent resource where this build will be created. Format:
-- \`projects\/{project}\/locations\/{location}\`
proParent :: Lens' ProjectsLocationsBuildsCreate Text
proParent
= lens _proParent (\ s a -> s{_proParent = a})
-- | V1 error format.
proXgafv :: Lens' ProjectsLocationsBuildsCreate (Maybe Xgafv)
proXgafv = lens _proXgafv (\ s a -> s{_proXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
proUploadProtocol :: Lens' ProjectsLocationsBuildsCreate (Maybe Text)
proUploadProtocol
= lens _proUploadProtocol
(\ s a -> s{_proUploadProtocol = a})
-- | OAuth access token.
proAccessToken :: Lens' ProjectsLocationsBuildsCreate (Maybe Text)
proAccessToken
= lens _proAccessToken
(\ s a -> s{_proAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
proUploadType :: Lens' ProjectsLocationsBuildsCreate (Maybe Text)
proUploadType
= lens _proUploadType
(\ s a -> s{_proUploadType = a})
-- | Multipart request metadata.
proPayload :: Lens' ProjectsLocationsBuildsCreate Build
proPayload
= lens _proPayload (\ s a -> s{_proPayload = a})
-- | Required. ID of the project.
proProjectId :: Lens' ProjectsLocationsBuildsCreate (Maybe Text)
proProjectId
= lens _proProjectId (\ s a -> s{_proProjectId = a})
-- | JSONP
proCallback :: Lens' ProjectsLocationsBuildsCreate (Maybe Text)
proCallback
= lens _proCallback (\ s a -> s{_proCallback = a})
instance GoogleRequest ProjectsLocationsBuildsCreate
where
type Rs ProjectsLocationsBuildsCreate = Operation
type Scopes ProjectsLocationsBuildsCreate =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsBuildsCreate'{..}
= go _proParent _proXgafv _proUploadProtocol
_proAccessToken
_proUploadType
_proProjectId
_proCallback
(Just AltJSON)
_proPayload
containerBuilderService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsBuildsCreateResource)
mempty
| brendanhay/gogol | gogol-containerbuilder/gen/Network/Google/Resource/Cloudbuild/Projects/Locations/Builds/Create.hs | mpl-2.0 | 6,083 | 0 | 18 | 1,351 | 867 | 507 | 360 | 124 | 1 |
module Codewars.Fibonacci where
fibs = 0 : 1 : (zipWith (+) fibs $ tail fibs)
sumFibs :: Int -> Integer
sumFibs n = sum $ filter even $ take (n + 1) fibs
| ice1000/OI-codes | codewars/101-200/sumfibs.hs | agpl-3.0 | 156 | 0 | 8 | 35 | 76 | 40 | 36 | 4 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module Data.UCI where
data MessageIn = UCI
| Debug (Maybe Bool)
| IsReady
| NewGame
| Position (Maybe String) [String]
| Go
| Quit
deriving Show
data MessageOut = ID String String
| OK
| ReadyOK
| BestMove String (Maybe String)
| Info String
deriving Show
class ReadIn a where readIn :: a -> [MessageIn]
class ShowOut a where showOut :: MessageOut -> [a]
instance ReadIn [String] where
readIn ["uci"] = [UCI]
readIn ["debug"] = [Debug Nothing]
readIn ["debug", "on"] = [Debug (Just True)]
readIn ["debug", "off"] = [Debug (Just False)]
readIn ["isready"] = [IsReady]
readIn ["ucinewgame"] = [NewGame]
readIn ("position":"fen":placement:_:_:_:_:_ :"moves":ws) = [Position undefined ws]
readIn ("position":"startpos" :"moves":ws) = [Position undefined ws]
readIn ("position" :"moves":ws) = [Position undefined ws]
readIn ("go":_) = [Go]
readIn ws = []
instance ShowOut [String] where
showOut (ID name author) = [["id", "name", name], ["id", "author", author]]
showOut OK = [["uciok"]]
showOut ReadyOK = [["readyok"]]
showOut (BestMove m1 Nothing) = [["bestmove", m1]]
showOut (BestMove m1 (Just m2)) = [["bestmove", m1, "ponder", m2]]
showOut (Info xs) = [["info", "string", xs]]
instance ReadIn String where readIn = readIn . words
instance ShowOut String where showOut m = map unwords (showOut m)
| shockkolate/hs-uci | src/Data/UCI.hs | unlicense | 2,018 | 0 | 16 | 885 | 610 | 336 | 274 | 39 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.RepositoryImportSpec where
import GHC.Generics
import Openshift.V1.ObjectReference
import Openshift.V1.TagImportPolicy
import qualified Data.Aeson
-- |
data RepositoryImportSpec = RepositoryImportSpec
{ from :: ObjectReference -- ^ the source for the image repository to import; only kind DockerImage and a name of a Docker image repository is allowed
, importPolicy :: Maybe TagImportPolicy -- ^ policy controlling how the image is imported
, includeManifest :: Maybe Bool -- ^ if true, return the manifest for each image in the response
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON RepositoryImportSpec
instance Data.Aeson.ToJSON RepositoryImportSpec
| minhdoboi/deprecated-openshift-haskell-api | openshift/lib/Openshift/V1/RepositoryImportSpec.hs | apache-2.0 | 880 | 0 | 9 | 132 | 107 | 66 | 41 | 17 | 0 |
module Interactive where
import Parse(parseInit, parseQuery)
import BackwardChaining(resolve)
import Types
import Data.List()
import System.IO
askForChange:: Either String ([Relation], Init, Query) -> IO()
askForChange (Right parsed) = do
print "Do you want to change the initial facts given? (y/n) :"
rep <- getLine
if rep == "y"
then do {displayInitDatas (Right parsed);promptAddData (Right parsed); askForChange (Right parsed)}
else print "Bye"
askForChange (Left _) = print "Their was an error in your file correct it before using interactive maode with it";
displayInitDatas (Right(rls, i, q)) =
let
displayRule [r] = print r
displayRule (r:rs) = do { print r ; displayRule rs}
in do { displayRule rls; print i; print q}
displayInitDatas _ = print "no datas from the previous resolution"
prompt :: ([Relation], Init, Query) -> IO(Either String ([Relation], Init, Query))
prompt datas = do
putStr "$> "
hFlush stdout
line <- getLine
if line == "q"
then return (Right datas)
else readEntry datas line
(+++) :: Either String a -> Either String a -> Either String a
Left _ +++ other = other
Right a +++ _ = Right a
readEntry :: ([Relation], Init, Query) -> String ->IO(Either String ([Relation], Init, Query))
readEntry (r, i, q) line =
let res = fmap (\x -> (r, x, q)) (parseInit line) +++
fmap (\x -> (r, i, x)) (parseQuery line)
in
case res of
Right triple -> prompt triple
Left err -> do {print ("input: " ++ err); prompt (r, i, q);}
promptAddData :: Either String ([Relation], Init, Query) -> IO()
promptAddData (Right triple) = do
datas <- prompt triple
print (datas >>= resolve)
return ()
promptAddData _ = print "your previous file was incorrect, impossible to launch the interactive mode"
| tmielcza/demiurge | src/Interactive.hs | apache-2.0 | 1,790 | 0 | 14 | 370 | 722 | 371 | 351 | 44 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.