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
-- Test -fdefer-type-errors -- Should compile and run {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# OPTIONS_GHC -fdefer-type-errors #-} module Main where t5624 :: IO () t5624 = putStr "Hello World" >> putStr ',' a :: Int a = 'p' data B = B b :: B -> Bool b x = x == x data C a where C1 :: C Int C2 :: Bool -> C Bool c :: C Int -> Bool c (C2 x) = True d :: a -> a d = 1 e = 'p' f = e 'q' h :: a -> (Char,Char) h x = (x,'c') data T a where K :: a -> T a i a = seq (not (K a)) () class MyClass a where myOp :: a -> String j = myOp 23 -- Two errors, should not combine them -- No longer reported as an error: #12466 k :: (Int ~ Bool) => Int -> Bool k x = x l :: IO () l = putChar >> putChar 'p' main :: IO () main = print "No errors!"
sdiehl/ghc
testsuite/tests/typecheck/should_run/Defer01.hs
bsd-3-clause
770
0
9
207
319
173
146
33
1
{-# LANGUAGE TypeFamilies, TypeFamilyDependencies #-} module T13651 where type family F r s = f | f -> r s type instance F (Bar h (Foo r)) (Bar h (Foo s)) = Bar h (Bar r s) data Bar s b data Foo a foo :: (F cr cu ~ Bar h (Bar r u), F cu cs ~ Bar (Foo h) (Bar u s)) => Bar h (Bar r u) -> Bar (Foo h) (Bar u s) -> cu -> Foo (cr -> cs) -- A variant of T13651 which fixes 'cu' -- as well as the other type args foo = undefined
shlevy/ghc
testsuite/tests/typecheck/should_compile/T13651a.hs
bsd-3-clause
447
0
11
128
210
113
97
-1
-1
{-# LANGUAGE PatternGuards #-} module Distribution.Server.Features.BuildReports.Backup ( dumpBackup, restoreBackup, buildReportsToExport, packageReportsToExport ) where import Distribution.Server.Features.BuildReports.BuildReport (BuildReport) import qualified Distribution.Server.Features.BuildReports.BuildReport as Report import Distribution.Server.Features.BuildReports.BuildReports (BuildReports(..), PkgBuildReports(..), BuildReportId(..), BuildLog(..)) import qualified Distribution.Server.Features.BuildReports.BuildReports as Reports import qualified Distribution.Server.Framework.BlobStorage as BlobStorage import Distribution.Server.Framework.BackupDump import Distribution.Server.Framework.BackupRestore import Distribution.Server.Util.Parse (unpackUTF8, packUTF8) import Distribution.Package import Distribution.Text (display, simpleParse) import Distribution.Version import Control.Monad (foldM) import Data.Map (Map) import qualified Data.Map as Map import System.FilePath (splitExtension) import Data.ByteString.Lazy (ByteString) dumpBackup :: BuildReports -> [BackupEntry] dumpBackup = buildReportsToExport restoreBackup :: RestoreBackup BuildReports restoreBackup = updateReports Reports.emptyReports Map.empty -- when logs are encountered before their corresponding build reports type PartialLogs = Map (PackageId, BuildReportId) BuildLog updateReports :: BuildReports -> PartialLogs -> RestoreBackup BuildReports updateReports buildReports partialLogs = RestoreBackup { restoreEntry = \entry -> do case entry of BackupByteString ["package", pkgStr, reportItem] bs | Just pkgId <- simpleParse pkgStr , (num, ".txt") <- splitExtension reportItem -> do checkPackageVersion pkgStr pkgId (buildReports', partialLogs') <- importReport pkgId num bs buildReports partialLogs return (updateReports buildReports' partialLogs') BackupBlob ["package", pkgStr, reportItem] blobId | Just pkgId <- simpleParse pkgStr , (num, ".log") <- splitExtension reportItem -> do checkPackageVersion pkgStr pkgId (buildReports', partialLogs') <- importLog pkgId num blobId buildReports partialLogs return (updateReports buildReports' partialLogs') _ -> return (updateReports buildReports partialLogs) , restoreFinalize = foldM insertLog buildReports (Map.toList partialLogs) } insertLog :: BuildReports -> ((PackageId, BuildReportId), BuildLog) -> Restore BuildReports insertLog buildReps ((pkgId, reportId), buildLog) = case Reports.setBuildLog pkgId reportId (Just buildLog) buildReps of Just buildReps' -> return buildReps' Nothing -> fail $ "Build log #" ++ display reportId ++ " exists for " ++ display pkgId ++ " but report itself does not" checkPackageVersion :: String -> PackageIdentifier -> Restore () checkPackageVersion pkgStr pkgId = case packageVersion pkgId of Version [] [] -> fail $ "Build report package id " ++ show pkgStr ++ " must specify a version" _ -> return () importReport :: PackageId -> String -> ByteString -> BuildReports -> PartialLogs -> Restore (BuildReports, PartialLogs) importReport pkgId repIdStr contents buildReps partialLogs = do reportId <- parseText "report id" repIdStr report <- either fail return $ Report.parse (unpackUTF8 contents) let (mlog, partialLogs') = Map.updateLookupWithKey (\_ _ -> Nothing) (pkgId, reportId) partialLogs buildReps' = Reports.unsafeSetReport pkgId reportId (report, mlog) buildReps --doesn't check for duplicates return (buildReps', partialLogs') importLog :: PackageId -> String -> BlobStorage.BlobId -> BuildReports -> PartialLogs -> Restore (BuildReports, PartialLogs) importLog pkgId repIdStr blobId buildReps logs = do reportId <- parseText "report id" repIdStr let buildLog = BuildLog blobId case Reports.setBuildLog pkgId reportId (Just buildLog) buildReps of Nothing -> return (buildReps, Map.insert (pkgId, reportId) buildLog logs) Just buildReps' -> return (buildReps', logs) ------------------------------------------------------------------------------ buildReportsToExport :: BuildReports -> [BackupEntry] buildReportsToExport buildReports = concatMap (uncurry packageReportsToExport) (Map.toList $ Reports.reportsIndex buildReports) packageReportsToExport :: PackageId -> PkgBuildReports -> [BackupEntry] packageReportsToExport pkgId pkgReports = concatMap (uncurry $ reportToExport prefix) (Map.toList $ Reports.reports pkgReports) where prefix = ["package", display pkgId] reportToExport :: [FilePath] -> BuildReportId -> (BuildReport, Maybe BuildLog) -> [BackupEntry] reportToExport prefix reportId (report, mlog) = BackupByteString (getPath ".txt") (packUTF8 $ Report.show report) : case mlog of Nothing -> []; Just (BuildLog blobId) -> [blobToBackup (getPath ".log") blobId] where getPath ext = prefix ++ [display reportId ++ ext]
ocharles/hackage-server
Distribution/Server/Features/BuildReports/Backup.hs
bsd-3-clause
5,017
0
18
819
1,311
700
611
80
3
{-# LANGUAGE TypeFamilies #-} module ShouldFail where data family C9 a b :: * data instance C9 Int Int = C9IntInt data instance C9 [a] Int = C9ListInt data instance C9 [Int] [a] = C9ListList2 -- must fail: conflicting data instance C9 [a] [Int] = C9ListList
ghc-android/ghc
testsuite/tests/indexed-types/should_fail/SimpleFail11d.hs
bsd-3-clause
264
0
6
52
86
50
36
7
0
-- The type sig for 'test' is illegal in H98 because of the -- partial application of the type sig. -- But with the LiberalTypeSynonyms extension enabled it -- should be OK because when you expand the type synonyms -- it's just Int->Int -- c.f should_compile/tc155.hs module ShouldFail where type Thing m = m () type Const a b = a test :: Thing (Const Int) -> Thing (Const Int) test = test
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail107.hs
bsd-3-clause
393
0
8
76
62
38
24
5
1
module Expr where import Text.Printf (printf) data EOpType = EOpAdd | EOpSub deriving Show data Expr = ExprInteger Integer | ExprRef String | ExprOp EOpType Expr Expr instance Show Expr where show (ExprInteger n) = printf "0x%02x=%d" n n resolved :: Expr -> Bool resolved (ExprInteger _) = True resolved _ = False
nyaxt/dmix
nkmd/as/Expr.hs
mit
327
0
8
66
110
60
50
12
1
module Y2018.M06.D18.Solution where {-- Yesterday we wrote a SQL DELETE statement, but, NOT SO FAST! Yesterday we discovered duplicates in the data set, ... but are there 'non-duplicates'? Let's find out today. --} import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromJust) -- below imports available via 1HaskellADay git repository import Control.List (weave) import Y2018.M06.D15.Solution {-- First load in the article set and sort them. >>> arts <- readArticleDuplicates (exDir ++ tsvFile) >>> sorts <- sortedArticles arts --} -- Question 1: how many UUIDs have more than 2 articles? type MapAArts = Map ArticleId [Article] moreThan2 :: MapAArts -> MapAArts moreThan2 = Map.filter ((> 2) . length) {-- If you look at the above results you see that the UUIDs that have more than two articles the articles for each of the UUIDs have different published dates. That leads me to believe there are UUIDs that have more than one article but these articles for the same UUID are different. Talk about misuse of a datatype! "I have an UUID!" "I have one, too, but I was published nearly a year later!" Fancy that, Hedda! Well, this analysis worked for the moreThan2 set, ... how about in general? --} nonDuplicate :: MapAArts -> MapAArts nonDuplicate = Map.filter (\(h:t) -> any (\art -> published h /= published art) t) {-- >>> length (nonDuplicate (sortedArticles arts)) 30 --} -- Save out these non-duplicates as uuid,id,publish_dt-CSV file nonDuplicateReport :: FilePath -> MapAArts -> IO () nonDuplicateReport toFile = writeFile toFile . unlines . ("uuid,id,publish_dt":) . map (\(Art i a t p u) -> weave [a,show i,show (fromJust p)]) . concat . Map.elems . nonDuplicate -- and present to management and say: "So, what're we gonna do with these, boss?" -- ... they love* it when you present findings like these. Trust me; I know. -- And whilst management is wringing their hands and will eventually say: -- "Well, you do something. Figure it out! You're the Expert(tm)" -- You regenerate the SQL DELETE statement, but this time without the -- non-duplicate ids {-- >>> writeFile "Y2018/M06/D18/deleteDups.sql" . deleteStmt . concat . Map.elems . Map.map duplicateIds $ sorts Map.\\ nonDuplicate sorts Saved to deleteDups.sql in this directory. --} -- Question: how many ids in total are there in arts? How many duplicate IDs -- are you eliminating? ids :: [Article] -> [Idx] ids = map idx dupIds :: [Article] -> [Idx] dupIds = concat . Map.elems . Map.map duplicateIds . ((Map.\\) <*> nonDuplicate) . sortedArticles -- there should be fewer duplicate IDs than IDs in extracted set. {-- >>> length (ids arts) 4723 >>> length (dupIds arts) 2316 >>> length (dupIds arts) * 2 4632 Good. That looks 'kinda' reasonable. I'll execute that DELETE statement now. --}
geophf/1HaskellADay
exercises/HAD/Y2018/M06/D18/Solution.hs
mit
2,854
0
16
526
357
206
151
21
1
-- | Check for overlapping routes. module Yesod.Routes.Overlap ( findOverlaps , findOverlapNames , Overlap (..) ) where import Yesod.Routes.TH.Types import Data.List (intercalate) data Overlap t = Overlap { overlapParents :: [String] -> [String] -- ^ parent resource trees , overlap1 :: ResourceTree t , overlap2 :: ResourceTree t } findOverlaps :: ([String] -> [String]) -> [ResourceTree t] -> [Overlap t] findOverlaps _ [] = [] findOverlaps front (x:xs) = concatMap (findOverlap front x) xs ++ findOverlaps front xs findOverlap :: ([String] -> [String]) -> ResourceTree t -> ResourceTree t -> [Overlap t] findOverlap front x y = here rest where here | overlaps (resourceTreePieces x) (resourceTreePieces y) (hasSuffix x) (hasSuffix y) = (Overlap front x y:) | otherwise = id rest = case x of ResourceParent name _ children -> findOverlaps (front . (name:)) children ResourceLeaf{} -> [] hasSuffix :: ResourceTree t -> Bool hasSuffix (ResourceLeaf r) = case resourceDispatch r of Subsite{} -> True Methods Just{} _ -> True Methods Nothing _ -> False hasSuffix ResourceParent{} = True overlaps :: [(CheckOverlap, Piece t)] -> [(CheckOverlap, Piece t)] -> Bool -> Bool -> Bool -- No pieces on either side, will overlap regardless of suffix overlaps [] [] _ _ = True -- No pieces on the left, will overlap if the left side has a suffix overlaps [] _ suffixX _ = suffixX -- Ditto for the right overlaps _ [] _ suffixY = suffixY -- As soon as we ignore a single piece (via CheckOverlap == False), we say that -- the routes don't overlap at all. In other words, disabling overlap checking -- on a single piece disables it on the whole route. overlaps ((False, _):_) _ _ _ = False overlaps _ ((False, _):_) _ _ = False -- Compare the actual pieces overlaps ((True, pieceX):xs) ((True, pieceY):ys) suffixX suffixY = piecesOverlap pieceX pieceY && overlaps xs ys suffixX suffixY piecesOverlap :: Piece t -> Piece t -> Bool -- Statics only match if they equal. Dynamics match with anything piecesOverlap (Static x) (Static y) = x == y piecesOverlap _ _ = True findOverlapNames :: [ResourceTree t] -> [(String, String)] findOverlapNames = map go . findOverlaps id where go (Overlap front x y) = (go' $ resourceTreeName x, go' $ resourceTreeName y) where go' = intercalate "/" . front . return {- -- n^2, should be a way to speed it up findOverlaps :: [Resource a] -> [[Resource a]] findOverlaps = go . map justPieces where justPieces :: Resource a -> ([Piece a], Resource a) justPieces r@(Resource _ ps _) = (ps, r) go [] = [] go (x:xs) = mapMaybe (mOverlap x) xs ++ go xs mOverlap :: ([Piece a], Resource a) -> ([Piece a], Resource a) -> Maybe [Resource a] mOverlap _ _ = Nothing {- FIXME mOverlap mOverlap (Static x:xs, xr) (Static y:ys, yr) | x == y = mOverlap (xs, xr) (ys, yr) | otherwise = Nothing mOverlap (MultiPiece _:_, xr) (_, yr) = Just (xr, yr) mOverlap (_, xr) (MultiPiece _:_, yr) = Just (xr, yr) mOverlap ([], xr) ([], yr) = Just (xr, yr) mOverlap ([], _) (_, _) = Nothing mOverlap (_, _) ([], _) = Nothing mOverlap (_:xs, xr) (_:ys, yr) = mOverlap (xs, xr) (ys, yr) -} -}
piyush-kurur/yesod
yesod-routes/Yesod/Routes/Overlap.hs
mit
3,358
0
13
821
798
424
374
47
3
----------------------------------------------------------------------------- -- | -- Module : Palette.BrewerSet -- Copyright : (c) 2013 Jeffrey Rosenbluth -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- Sets of between 3 and 12 colors. -- This product includes color specifications and designs developed by -- Cynthia Brewer (http://colorbrewer.org/). -- ----------------------------------------------------------------------------- module BrewerSet ( -- * Color schemes from Cynthia Brewer. brewerSet -- ** Synonym for Colour Double , Kolor -- ** Colour Categories , ColorCat(..) ) where import qualified Data.Map.Lazy as M import Data.Colour import Data.Colour.SRGB (sRGB24read) type Kolor = Colour Double -- > ylgn = bar $ brewerSet YlGn 9 -- > ylgnbu = bar $ brewerSet YlGnBu 9 -- > gnbu = bar $ brewerSet GnBu 9 -- > bugn = bar $ brewerSet BuGn 9 -- > pubugn = bar $ brewerSet PuBuGn 9 -- > pubu = bar $ brewerSet PuBu 9 -- > bupu = bar $ brewerSet BuPu 9 -- > rdpu = bar $ brewerSet RdPu 9 -- > pudr = bar $ brewerSet PuRd 9 -- > orrd = bar $ brewerSet OrRd 9 -- > ylorrd = bar $ brewerSet YlOrRd 9 -- > ylorbr = bar $ brewerSet YlOrBr 9 -- > purples = bar $ brewerSet Purples 9 -- > blues = bar $ brewerSet Blues 9 -- > greens = bar $ brewerSet Greens 9 -- > oranges = bar $ brewerSet Oranges 9 -- > reds = bar $ brewerSet Reds 9 -- > greys = bar $ brewerSet Greys 9 -- > puor = bar $ brewerSet PuOr 11 -- > brbg = bar $ brewerSet BrBG 11 -- > prgn = bar $ brewerSet PRGn 11 -- > piyg = bar $ brewerSet PiYG 11 -- > rdbu = bar $ brewerSet RdBu 11 -- > rdgy = bar $ brewerSet RdGy 11 -- > rdylbu = bar $ brewerSet RdYlBu 11 -- > spectral = bar $ brewerSet Spectral 11 -- > rdylgn = bar $ brewerSet RdYlGn 11 -- > accent = bar $ brewerSet Accent 8 -- > dark2 = bar $ brewerSet Dark2 8 -- > paired = bar $ brewerSet Paired 12 -- > pastel1 = bar $ brewerSet Pastel1 9 -- > pastel2 = bar $ brewerSet Pastel2 8 -- > set1 = bar $ brewerSet Set1 9 -- > set2 = bar $ brewerSet Set2 8 -- > set3 = bar $ brewerSet Set3 12 -- | Categories of color sets. Each category has several lists of colors. -- Each one containing the number of colors in the range specfied. data ColorCat = YlGn -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_ylgn.svg#diagram=ylgn&width=100>> 3 - 9, sequential multihue | YlGnBu -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_ylgnbu.svg#diagram=ylgnbu&width=100>> 3 - 9, sequential multihue | GnBu -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_gnbu.svg#diagram=gnbu&width=100>> 3 - 9, sequential multihue | BuGn -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_bugn.svg#diagram=bugn&width=100>> 3 - 9, sequential multihue | PuBuGn -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_pubugn.svg#diagram=pubugn&width=100>> 3 - 9, sequential multihue | PuBu -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_pubu.svg#diagram=pubu&width=100>> 3 - 9, sequential multihue | BuPu -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_bupu.svg#diagram=bupu&width=100>> 3 - 9, sequential multihue | RdPu -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_rdpu.svg#diagram=rdpu&width=100>> 3 - 9, sequential multihue | PuRd -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_pudr.svg#diagram=pudr&width=100>> 3 - 9, sequential multihue | OrRd -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_orrd.svg#diagram=orrd&width=100>> 3 - 9, sequential multihue | YlOrRd -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_ylorrd.svg#diagram=ylorrd&width=100>> 3 - 9, sequential multihue | YlOrBr -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_ylorbr.svg#diagram=ylorbr&width=100>> 3 - 9, sequential multihue | Purples -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_purples.svg#diagram=purples&width=100>> 3 - 9, sequential single hue | Blues -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_blues.svg#diagram=blues&width=100>> 3 - 9, sequential single hue | Greens -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_greens.svg#diagram=greens&width=100>> 3 - 9, sequential single hue | Oranges -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_oranges.svg#diagram=oranges&width=100>> 3 - 9, sequential single hue | Reds -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_reds.svg#diagram=reds&width=100>> 3 - 9, sequential single hue | Greys -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_greys.svg#diagram=greys&width=100>> 3 - 9, sequential single hue | PuOr -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_puor.svg#diagram=puor&width=100>> 3 - 11, diverging | BrBG -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_brbg.svg#diagram=brbg&width=100>> 3 - 11, diverging | PRGn -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_prgn.svg#diagram=prgn&width=100>> 3 - 11, diverging | PiYG -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_piyg.svg#diagram=piyg&width=100>> 3 - 11, diverging | RdBu -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_rdbu.svg#diagram=rdbu&width=100>> 3 - 11, diverging | RdGy -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_rdgy.svg#diagram=rdgy&width=100>> 3 - 11, diverging | RdYlBu -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_rdylbu.svg#diagram=rdylbu&width=100>> 3 - 11, diverging | Spectral -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_spectral.svg#diagram=spectral&width=100>> 3 - 11, diverging | RdYlGn -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_rdylgn.svg#diagram=rdylgn&width=100>> 3 - 11, diverging | Accent -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_accent.svg#diagram=accent&width=100>> 3 - 8, qualitative | Dark2 -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_dark2.svg#diagram=dark2&width=100>> 3 - 8, qualitative | Paired -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_paired.svg#diagram=paired&width=100>> 3 - 12, qualitative | Pastel1 -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_pastel1.svg#diagram=pastel1&width=100>> 3 - 9, qualitative | Pastel2 -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_pastel2.svg#diagram=pastel2&width=100>> 3 - 8, qualitative | Set1 -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_set1.svg#diagram=set1&width=100>> 3 - 9, qualitative | Set2 -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_set2.svg#diagram=set2&width=100>> 3 - 8, qualitative | Set3 -- ^ <<diagrams/src_Data_Colour_Palette_BrewerSet_set3.svg#diagram=set3&width=100>> 3 - 12, qualitative deriving (Eq, Ord) data ColorSet = ColorSet ColorCat Int deriving (Eq, Ord) -- > import Data.Colour.Palette.BrewerSet -- > gr = 1.618 -- golden ratio -- > -- > bar [] = centerXY $ square gr # fc black -- > bar cs = centerXY $ hcat [square gr # scaleX s # fc k # lw 0 | k <- cs] -- > where s = gr / (fromIntegral (length cs)) -- > gb = bar $ brewerSet GnBu 9 -- green/blue, sequential multihue -- > po = bar $ brewerSet PuOr 11 -- purple/orange, diverging -- > bs = bar $ brewerSet Paired 11 -- qualitative -- > brewersample = hcat' (with & sep .~ 0.5) [gb, po, bs] -- | Obtain a list of colors for the color scheme designated by category and -- number `n` of colors in the theme. If the category and/or number does not -- exist then returns a list `black` repeated `n` times. brewerSet :: ColorCat -> Int -> [Kolor] brewerSet cat n = maybe (replicate n black) (map sRGB24read) b where b = M.lookup (ColorSet cat n) brewerColor brewerColor :: M.Map ColorSet [String] brewerColor = M.fromList brewer -- Color set data ----------------------------------------------------------------------- ------------------------------------------------------------------------------- brewer :: [(ColorSet, [String])] brewer = [ (ColorSet Spectral 11, ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"]), (ColorSet Spectral 10, ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"]), (ColorSet Spectral 3, ["#fc8d59","#ffffbf","#99d594"]), (ColorSet Spectral 5, ["#d7191c","#fdae61","#ffffbf","#abdda4","#2b83ba"]), (ColorSet Spectral 4, ["#d7191c","#fdae61","#abdda4","#2b83ba"]), (ColorSet Spectral 7, ["#d53e4f","#fc8d59","#fee08b","#ffffbf","#e6f598","#99d594","#3288bd"]), (ColorSet Spectral 6, ["#d53e4f","#fc8d59","#fee08b","#e6f598","#99d594","#3288bd"]), (ColorSet Spectral 9, ["#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd"]), (ColorSet Spectral 8, ["#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd"]), (ColorSet RdYlGn 11, ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]), (ColorSet RdYlGn 10, ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]), (ColorSet RdYlGn 3, ["#fc8d59","#ffffbf","#91cf60"]), (ColorSet RdYlGn 5, ["#d7191c","#fdae61","#ffffbf","#a6d96a","#1a9641"]), (ColorSet RdYlGn 4, ["#d7191c","#fdae61","#a6d96a","#1a9641"]), (ColorSet RdYlGn 7, ["#d73027","#fc8d59","#fee08b","#ffffbf","#d9ef8b","#91cf60","#1a9850"]), (ColorSet RdYlGn 6, ["#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"]), (ColorSet RdYlGn 9, ["#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850"]), (ColorSet RdYlGn 8, ["#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850"]), (ColorSet Set2 3, ["#66c2a5","#fc8d62","#8da0cb"]), (ColorSet Set2 5, ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854"]), (ColorSet Set2 4, ["#66c2a5","#fc8d62","#8da0cb","#e78ac3"]), (ColorSet Set2 7, ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494"]), (ColorSet Set2 6, ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f"]), (ColorSet Set2 8, ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"]), (ColorSet Accent 3, ["#7fc97f","#beaed4","#fdc086"]), (ColorSet Accent 5, ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0"]), (ColorSet Accent 4, ["#7fc97f","#beaed4","#fdc086","#ffff99"]), (ColorSet Accent 7, ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17"]), (ColorSet Accent 6, ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f"]), (ColorSet Accent 8, ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"]), (ColorSet OrRd 3, ["#fee8c8","#fdbb84","#e34a33"]), (ColorSet OrRd 5, ["#fef0d9","#fdcc8a","#fc8d59","#e34a33","#b30000"]), (ColorSet OrRd 4, ["#fef0d9","#fdcc8a","#fc8d59","#d7301f"]), (ColorSet OrRd 7, ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"]), (ColorSet OrRd 6, ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#e34a33","#b30000"]), (ColorSet OrRd 9, ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"]), (ColorSet OrRd 8, ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"]), (ColorSet Set1 3, ["#e41a1c","#377eb8","#4daf4a"]), (ColorSet Set1 5, ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"]), (ColorSet Set1 4, ["#e41a1c","#377eb8","#4daf4a","#984ea3"]), (ColorSet Set1 7, ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628"]), (ColorSet Set1 6, ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33"]), (ColorSet Set1 9, ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"]), (ColorSet Set1 8, ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf"]), (ColorSet PuBu 3, ["#ece7f2","#a6bddb","#2b8cbe"]), (ColorSet PuBu 5, ["#f1eef6","#bdc9e1","#74a9cf","#2b8cbe","#045a8d"]), (ColorSet PuBu 4, ["#f1eef6","#bdc9e1","#74a9cf","#0570b0"]), (ColorSet PuBu 7, ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"]), (ColorSet PuBu 6, ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#2b8cbe","#045a8d"]), (ColorSet PuBu 9, ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"]), (ColorSet PuBu 8, ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"]), (ColorSet Set3 11, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5"]), (ColorSet Set3 10, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd"]), (ColorSet Set3 12, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"]), (ColorSet Set3 3, ["#8dd3c7","#ffffb3","#bebada"]), (ColorSet Set3 5, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3"]), (ColorSet Set3 4, ["#8dd3c7","#ffffb3","#bebada","#fb8072"]), (ColorSet Set3 7, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69"]), (ColorSet Set3 6, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462"]), (ColorSet Set3 9, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9"]), (ColorSet Set3 8, ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5"]), (ColorSet BuPu 3, ["#e0ecf4","#9ebcda","#8856a7"]), (ColorSet BuPu 5, ["#edf8fb","#b3cde3","#8c96c6","#8856a7","#810f7c"]), (ColorSet BuPu 4, ["#edf8fb","#b3cde3","#8c96c6","#88419d"]), (ColorSet BuPu 7, ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"]), (ColorSet BuPu 6, ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8856a7","#810f7c"]), (ColorSet BuPu 9, ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"]), (ColorSet BuPu 8, ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"]), (ColorSet Dark2 3, ["#1b9e77","#d95f02","#7570b3"]), (ColorSet Dark2 5, ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e"]), (ColorSet Dark2 4, ["#1b9e77","#d95f02","#7570b3","#e7298a"]), (ColorSet Dark2 7, ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d"]), (ColorSet Dark2 6, ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02"]), (ColorSet Dark2 8, ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"]), (ColorSet RdBu 11, ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"]), (ColorSet RdBu 10, ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"]), (ColorSet RdBu 3, ["#ef8a62","#f7f7f7","#67a9cf"]), (ColorSet RdBu 5, ["#ca0020","#f4a582","#f7f7f7","#92c5de","#0571b0"]), (ColorSet RdBu 4, ["#ca0020","#f4a582","#92c5de","#0571b0"]), (ColorSet RdBu 7, ["#b2182b","#ef8a62","#fddbc7","#f7f7f7","#d1e5f0","#67a9cf","#2166ac"]), (ColorSet RdBu 6, ["#b2182b","#ef8a62","#fddbc7","#d1e5f0","#67a9cf","#2166ac"]), (ColorSet RdBu 9, ["#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac"]), (ColorSet RdBu 8, ["#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac"]), (ColorSet Oranges 3, ["#fee6ce","#fdae6b","#e6550d"]), (ColorSet Oranges 5, ["#feedde","#fdbe85","#fd8d3c","#e6550d","#a63603"]), (ColorSet Oranges 4, ["#feedde","#fdbe85","#fd8d3c","#d94701"]), (ColorSet Oranges 7, ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"]), (ColorSet Oranges 6, ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#e6550d","#a63603"]), (ColorSet Oranges 9, ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]), (ColorSet Oranges 8, ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"]), (ColorSet BuGn 3, ["#e5f5f9","#99d8c9","#2ca25f"]), (ColorSet BuGn 5, ["#edf8fb","#b2e2e2","#66c2a4","#2ca25f","#006d2c"]), (ColorSet BuGn 4, ["#edf8fb","#b2e2e2","#66c2a4","#238b45"]), (ColorSet BuGn 7, ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"]), (ColorSet BuGn 6, ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#2ca25f","#006d2c"]), (ColorSet BuGn 9, ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"]), (ColorSet BuGn 8, ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"]), (ColorSet PiYG 11, ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"]), (ColorSet PiYG 10, ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"]), (ColorSet PiYG 3, ["#e9a3c9","#f7f7f7","#a1d76a"]), (ColorSet PiYG 5, ["#d01c8b","#f1b6da","#f7f7f7","#b8e186","#4dac26"]), (ColorSet PiYG 4, ["#d01c8b","#f1b6da","#b8e186","#4dac26"]), (ColorSet PiYG 7, ["#c51b7d","#e9a3c9","#fde0ef","#f7f7f7","#e6f5d0","#a1d76a","#4d9221"]), (ColorSet PiYG 6, ["#c51b7d","#e9a3c9","#fde0ef","#e6f5d0","#a1d76a","#4d9221"]), (ColorSet PiYG 9, ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221"]), (ColorSet PiYG 8, ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221"]), (ColorSet YlOrBr 3, ["#fff7bc","#fec44f","#d95f0e"]), (ColorSet YlOrBr 5, ["#ffffd4","#fed98e","#fe9929","#d95f0e","#993404"]), (ColorSet YlOrBr 4, ["#ffffd4","#fed98e","#fe9929","#cc4c02"]), (ColorSet YlOrBr 7, ["#ffffd4","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"]), (ColorSet YlOrBr 6, ["#ffffd4","#fee391","#fec44f","#fe9929","#d95f0e","#993404"]), (ColorSet YlOrBr 9, ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"]), (ColorSet YlOrBr 8, ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"]), (ColorSet YlGn 3, ["#f7fcb9","#addd8e","#31a354"]), (ColorSet YlGn 5, ["#ffffcc","#c2e699","#78c679","#31a354","#006837"]), (ColorSet YlGn 4, ["#ffffcc","#c2e699","#78c679","#238443"]), (ColorSet YlGn 7, ["#ffffcc","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"]), (ColorSet YlGn 6, ["#ffffcc","#d9f0a3","#addd8e","#78c679","#31a354","#006837"]), (ColorSet YlGn 9, ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"]), (ColorSet YlGn 8, ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"]), (ColorSet Pastel2 3, ["#b3e2cd","#fdcdac","#cbd5e8"]), (ColorSet Pastel2 5, ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9"]), (ColorSet Pastel2 4, ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4"]), (ColorSet Pastel2 7, ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc"]), (ColorSet Pastel2 6, ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae"]), (ColorSet Pastel2 8, ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"]), (ColorSet RdPu 3, ["#fde0dd","#fa9fb5","#c51b8a"]), (ColorSet RdPu 5, ["#feebe2","#fbb4b9","#f768a1","#c51b8a","#7a0177"]), (ColorSet RdPu 4, ["#feebe2","#fbb4b9","#f768a1","#ae017e"]), (ColorSet RdPu 7, ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"]), (ColorSet RdPu 6, ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#c51b8a","#7a0177"]), (ColorSet RdPu 9, ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"]), (ColorSet RdPu 8, ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"]), (ColorSet Greens 3, ["#e5f5e0","#a1d99b","#31a354"]), (ColorSet Greens 5, ["#edf8e9","#bae4b3","#74c476","#31a354","#006d2c"]), (ColorSet Greens 4, ["#edf8e9","#bae4b3","#74c476","#238b45"]), (ColorSet Greens 7, ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"]), (ColorSet Greens 6, ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#31a354","#006d2c"]), (ColorSet Greens 9, ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"]), (ColorSet Greens 8, ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"]), (ColorSet PRGn 11, ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"]), (ColorSet PRGn 10, ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"]), (ColorSet PRGn 3, ["#af8dc3","#f7f7f7","#7fbf7b"]), (ColorSet PRGn 5, ["#7b3294","#c2a5cf","#f7f7f7","#a6dba0","#008837"]), (ColorSet PRGn 4, ["#7b3294","#c2a5cf","#a6dba0","#008837"]), (ColorSet PRGn 7, ["#762a83","#af8dc3","#e7d4e8","#f7f7f7","#d9f0d3","#7fbf7b","#1b7837"]), (ColorSet PRGn 6, ["#762a83","#af8dc3","#e7d4e8","#d9f0d3","#7fbf7b","#1b7837"]), (ColorSet PRGn 9, ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837"]), (ColorSet PRGn 8, ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837"]), (ColorSet YlGnBu 3, ["#edf8b1","#7fcdbb","#2c7fb8"]), (ColorSet YlGnBu 5, ["#ffffcc","#a1dab4","#41b6c4","#2c7fb8","#253494"]), (ColorSet YlGnBu 4, ["#ffffcc","#a1dab4","#41b6c4","#225ea8"]), (ColorSet YlGnBu 7, ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"]), (ColorSet YlGnBu 6, ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#2c7fb8","#253494"]), (ColorSet YlGnBu 9, ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]), (ColorSet YlGnBu 8, ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"]), (ColorSet RdYlBu 11, ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"]), (ColorSet RdYlBu 10, ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"]), (ColorSet RdYlBu 3, ["#fc8d59","#ffffbf","#91bfdb"]), (ColorSet RdYlBu 5, ["#d7191c","#fdae61","#ffffbf","#abd9e9","#2c7bb6"]), (ColorSet RdYlBu 4, ["#d7191c","#fdae61","#abd9e9","#2c7bb6"]), (ColorSet RdYlBu 7, ["#d73027","#fc8d59","#fee090","#ffffbf","#e0f3f8","#91bfdb","#4575b4"]), (ColorSet RdYlBu 6, ["#d73027","#fc8d59","#fee090","#e0f3f8","#91bfdb","#4575b4"]), (ColorSet RdYlBu 9, ["#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4"]), (ColorSet RdYlBu 8, ["#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4"]), (ColorSet Paired 11, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99"]), (ColorSet Paired 10, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a"]), (ColorSet Paired 12, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"]), (ColorSet Paired 3, ["#a6cee3","#1f78b4","#b2df8a"]), (ColorSet Paired 5, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99"]), (ColorSet Paired 4, ["#a6cee3","#1f78b4","#b2df8a","#33a02c"]), (ColorSet Paired 7, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f"]), (ColorSet Paired 6, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c"]), (ColorSet Paired 9, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6"]), (ColorSet Paired 8, ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00"]), (ColorSet BrBG 11, ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"]), (ColorSet BrBG 10, ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"]), (ColorSet BrBG 3, ["#d8b365","#f5f5f5","#5ab4ac"]), (ColorSet BrBG 5, ["#a6611a","#dfc27d","#f5f5f5","#80cdc1","#018571"]), (ColorSet BrBG 4, ["#a6611a","#dfc27d","#80cdc1","#018571"]), (ColorSet BrBG 7, ["#8c510a","#d8b365","#f6e8c3","#f5f5f5","#c7eae5","#5ab4ac","#01665e"]), (ColorSet BrBG 6, ["#8c510a","#d8b365","#f6e8c3","#c7eae5","#5ab4ac","#01665e"]), (ColorSet BrBG 9, ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e"]), (ColorSet BrBG 8, ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e"]), (ColorSet Purples 3, ["#efedf5","#bcbddc","#756bb1"]), (ColorSet Purples 5, ["#f2f0f7","#cbc9e2","#9e9ac8","#756bb1","#54278f"]), (ColorSet Purples 4, ["#f2f0f7","#cbc9e2","#9e9ac8","#6a51a3"]), (ColorSet Purples 7, ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"]), (ColorSet Purples 6, ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#756bb1","#54278f"]), (ColorSet Purples 9, ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]), (ColorSet Purples 8, ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"]), (ColorSet Reds 3, ["#fee0d2","#fc9272","#de2d26"]), (ColorSet Reds 5, ["#fee5d9","#fcae91","#fb6a4a","#de2d26","#a50f15"]), (ColorSet Reds 4, ["#fee5d9","#fcae91","#fb6a4a","#cb181d"]), (ColorSet Reds 7, ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"]), (ColorSet Reds 6, ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#de2d26","#a50f15"]), (ColorSet Reds 9, ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]), (ColorSet Reds 8, ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"]), (ColorSet Pastel1 3, ["#fbb4ae","#b3cde3","#ccebc5"]), (ColorSet Pastel1 5, ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6"]), (ColorSet Pastel1 4, ["#fbb4ae","#b3cde3","#ccebc5","#decbe4"]), (ColorSet Pastel1 7, ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd"]), (ColorSet Pastel1 6, ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc"]), (ColorSet Pastel1 9, ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]), (ColorSet Pastel1 8, ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec"]), (ColorSet GnBu 3, ["#e0f3db","#a8ddb5","#43a2ca"]), (ColorSet GnBu 5, ["#f0f9e8","#bae4bc","#7bccc4","#43a2ca","#0868ac"]), (ColorSet GnBu 4, ["#f0f9e8","#bae4bc","#7bccc4","#2b8cbe"]), (ColorSet GnBu 7, ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"]), (ColorSet GnBu 6, ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#43a2ca","#0868ac"]), (ColorSet GnBu 9, ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"]), (ColorSet GnBu 8, ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"]), (ColorSet Greys 3, ["#f0f0f0","#bdbdbd","#636363"]), (ColorSet Greys 5, ["#f7f7f7","#cccccc","#969696","#636363","#252525"]), (ColorSet Greys 4, ["#f7f7f7","#cccccc","#969696","#525252"]), (ColorSet Greys 7, ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"]), (ColorSet Greys 6, ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#636363","#252525"]), (ColorSet Greys 9, ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]), (ColorSet Greys 8, ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"]), (ColorSet RdGy 11, ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"]), (ColorSet RdGy 10, ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"]), (ColorSet RdGy 3, ["#ef8a62","#ffffff","#999999"]), (ColorSet RdGy 5, ["#ca0020","#f4a582","#ffffff","#bababa","#404040"]), (ColorSet RdGy 4, ["#ca0020","#f4a582","#bababa","#404040"]), (ColorSet RdGy 7, ["#b2182b","#ef8a62","#fddbc7","#ffffff","#e0e0e0","#999999","#4d4d4d"]), (ColorSet RdGy 6, ["#b2182b","#ef8a62","#fddbc7","#e0e0e0","#999999","#4d4d4d"]), (ColorSet RdGy 9, ["#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d"]), (ColorSet RdGy 8, ["#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d"]), (ColorSet YlOrRd 3, ["#ffeda0","#feb24c","#f03b20"]), (ColorSet YlOrRd 5, ["#ffffb2","#fecc5c","#fd8d3c","#f03b20","#bd0026"]), (ColorSet YlOrRd 4, ["#ffffb2","#fecc5c","#fd8d3c","#e31a1c"]), (ColorSet YlOrRd 7, ["#ffffb2","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"]), (ColorSet YlOrRd 6, ["#ffffb2","#fed976","#feb24c","#fd8d3c","#f03b20","#bd0026"]), (ColorSet YlOrRd 9, ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"]), (ColorSet YlOrRd 8, ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"]), (ColorSet PuOr 11, ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"]), (ColorSet PuOr 10, ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"]), (ColorSet PuOr 3, ["#f1a340","#f7f7f7","#998ec3"]), (ColorSet PuOr 5, ["#e66101","#fdb863","#f7f7f7","#b2abd2","#5e3c99"]), (ColorSet PuOr 4, ["#e66101","#fdb863","#b2abd2","#5e3c99"]), (ColorSet PuOr 7, ["#b35806","#f1a340","#fee0b6","#f7f7f7","#d8daeb","#998ec3","#542788"]), (ColorSet PuOr 6, ["#b35806","#f1a340","#fee0b6","#d8daeb","#998ec3","#542788"]), (ColorSet PuOr 9, ["#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788"]), (ColorSet PuOr 8, ["#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788"]), (ColorSet PuRd 3, ["#e7e1ef","#c994c7","#dd1c77"]), (ColorSet PuRd 5, ["#f1eef6","#d7b5d8","#df65b0","#dd1c77","#980043"]), (ColorSet PuRd 4, ["#f1eef6","#d7b5d8","#df65b0","#ce1256"]), (ColorSet PuRd 7, ["#f1eef6","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"]), (ColorSet PuRd 6, ["#f1eef6","#d4b9da","#c994c7","#df65b0","#dd1c77","#980043"]), (ColorSet PuRd 9, ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"]), (ColorSet PuRd 8, ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"]), (ColorSet Blues 3, ["#deebf7","#9ecae1","#3182bd"]), (ColorSet Blues 5, ["#eff3ff","#bdd7e7","#6baed6","#3182bd","#08519c"]), (ColorSet Blues 4, ["#eff3ff","#bdd7e7","#6baed6","#2171b5"]), (ColorSet Blues 7, ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"]), (ColorSet Blues 6, ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#3182bd","#08519c"]), (ColorSet Blues 9, ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]), (ColorSet Blues 8, ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"]), (ColorSet PuBuGn 3, ["#ece2f0","#a6bddb","#1c9099"]), (ColorSet PuBuGn 5, ["#f6eff7","#bdc9e1","#67a9cf","#1c9099","#016c59"]), (ColorSet PuBuGn 4, ["#f6eff7","#bdc9e1","#67a9cf","#02818a"]), (ColorSet PuBuGn 7, ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"]), (ColorSet PuBuGn 6, ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#1c9099","#016c59"]), (ColorSet PuBuGn 9, ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"]), (ColorSet PuBuGn 8, ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"])]
NickAger/LearningHaskell
haskellForMacMiscPlayground/Diagrams with Sunflower.hsproj/BrewerSet.hs
mit
32,387
0
9
3,872
9,190
5,787
3,403
318
1
-- This file is covered by an MIT license. See 'LICENSE' for details. -- Author: Bertram Felgenhauer module Util.Relation ( Rel, member, empty, insert, union, difference, pred, succ, null, restrict, fromList, toList, ) where import Prelude hiding (pred, succ, elem, null) import qualified Data.Map as M import qualified Data.Set as S import Data.List (foldl') import Control.Monad data Rel a = Rel { suc :: M.Map a (S.Set a), pre :: M.Map a (S.Set a) } member :: Ord a => (a, a) -> Rel a -> Bool member (a, b) rel = maybe False (S.member b) $ a `M.lookup` suc rel insert :: Ord a => (a, a) -> Rel a -> Rel a insert (a, b) rel = Rel{ suc = insert' a b (suc rel), pre = insert' b a (pre rel) } where insert' a b = M.alter (Just . maybe (S.singleton b) (S.insert b)) a empty :: Rel a empty = Rel{ suc = M.empty, pre = M.empty } succ :: Ord a => Rel a -> a -> S.Set a succ rel a = maybe S.empty id $ a `M.lookup` suc rel pred :: Ord a => Rel a -> a -> S.Set a pred rel a = maybe S.empty id $ a `M.lookup` pre rel union :: Ord a => Rel a -> Rel a -> Rel a union rel rel' = Rel{ suc = union' (suc rel) (suc rel'), pre = union' (pre rel) (pre rel') } where union' a b = M.unionWith (S.union) a b difference :: Ord a => Rel a -> Rel a -> Rel a difference rel rel' = Rel{ suc = difference' (suc rel) (suc rel'), pre = difference' (pre rel) (pre rel') } where difference' = M.differenceWith (\a b -> let r = S.difference a b in guard (S.null r) >> return r) null :: Ord a => Rel a -> Bool null rel = M.fold (\a b -> S.null a && b) True (suc rel) fromList :: Ord a => [(a, a)] -> Rel a fromList = foldl' (flip insert) empty toList :: Ord a => Rel a -> [(a, a)] toList rel = [(a, b) | (a, bs) <- M.toList (suc rel), b <- S.toList bs] restrict :: Ord a => (a -> Bool) -> Rel a -> Rel a restrict dom rel = Rel{ suc = restrict' (suc rel), pre = restrict' (pre rel) } where restrict' = M.map (S.filter dom) . (M.filterWithKey (const . dom))
haskell-rewriting/confluence-tool
src/Util/Relation.hs
mit
2,094
0
16
581
1,067
558
509
49
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} module Nauva.CSS.Types where import Data.Aeson (ToJSON(..), FromJSON(..)) import qualified Data.Aeson as A import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.String import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.ByteString.Lazy (toStrict) import qualified Data.ByteString.Char8 as BC import Data.Char import Control.Monad.Writer.Lazy import Crypto.MAC.SipHash (SipHash(..), SipKey(..)) import qualified Crypto.MAC.SipHash as SH import Numeric import Prelude ------------------------------------------------------------------------------- -- | These values can appear as the right-hand-side of a CSS declaration. For -- example in @color: magenta@ the string @magenta@ would be a 'CSSValue'. -- -- There is a 'IsString' instance to make it easier to create custom values for -- which we don't have a combinator or helper function yet. -- -- > let widthValue = "calc(100% - 20px)" :: CSSValue newtype CSSValue = CSSValue { unCSSValue :: Text } instance Show CSSValue where show = show . unCSSValue instance ToJSON CSSValue where toJSON = toJSON . unCSSValue instance FromJSON CSSValue where parseJSON x = CSSValue <$> parseJSON x instance IsString CSSValue where fromString = CSSValue . T.pack ------------------------------------------------------------------------------- -- | A basic CSS declaration (property-value pair) whose value isn't processed -- any further and taken at face value. If you put garbage in, you'll get -- garbage out. These pairs are written verbatim into the output file or -- a StyleSheet object in the browser. type CSSDeclaration = (Text, CSSValue) ------------------------------------------------------------------------------- -- | A block of CSS declarations. Equivalent to stuff between curly braces in -- plain CSS. Such blocks may appear as bodies of 'CSSStyleRule', -- 'CSSFontFaceRule' etc. -- -- Keys can appear multiple times, with the the last one overwriting all previous -- occurrences. type CSSStyleDeclaration = [CSSDeclaration] ------------------------------------------------------------------------------- -- | Mimics a IDL CSSRule. Though only some of the variants are supported. -- -- In addition to the stuff which is needed to generate the CSS text, it also -- contains a unique 'Hash' which can be used to quickly compare two objects -- or track which ones have been inserted into the DOM to avoid inserting -- the same 'CSSRule' multiple times. data CSSRule = CSSStyleRule !Text !Hash ![Condition] ![Suffix] !CSSStyleDeclaration | CSSFontFaceRule !Hash !CSSStyleDeclaration deriving (Show) instance A.ToJSON CSSRule where toJSON (CSSStyleRule name hash conditions suffixes styleDeclaration) = A.toJSON [ A.toJSON (1 :: Int) , A.toJSON name , A.toJSON hash , A.toJSON conditions , A.toJSON suffixes , A.toJSON $ M.fromList styleDeclaration ] toJSON (CSSFontFaceRule hash styleDeclaration) = A.toJSON [ A.toJSON (5 :: Int) , A.toJSON hash , A.toJSON $ M.fromList styleDeclaration ] cssRuleHash :: CSSRule -> Hash cssRuleHash (CSSStyleRule _ hash _ _ _) = hash cssRuleHash (CSSFontFaceRule hash _) = hash ------------------------------------------------------------------------------- -- | Statements are the lowest-level building blocks of a CSS style. Users -- of this library don't deal with this though. There are combinators and helper -- functions to create values of this type. data Statement = SEmit !Declaration -- ^ Emit a single CSS declaration into the current context. | SCondition !Condition !(Writer [Statement] ()) -- ^ Wrap a block in a condition (@media or @supports). | SSuffix !Suffix !(Writer [Statement] ()) -- ^ Wrap a block in a suffix (pseudo selector or pseudo class). ------------------------------------------------------------------------------- -- | Similar to 'CSSDeclaration' but has special support for certain -- properties. These properties are expanded while generating the output and -- may cause additional CSS rules to be emitted. data Declaration = DPlain !Text !CSSValue | DFontFamily !CSSStyleDeclaration deriving (Show) ------------------------------------------------------------------------------- -- | A 'Style' is the maximally prepared, preprocessed, precompiled object we -- can create at compile time. Any remaining transformations need to be -- applied at runtime, because they depend on the host (browser). newtype Style = Style { unStyle :: [CSSRule] } instance A.ToJSON Style where toJSON = A.toJSON . unStyle mkStyle :: Writer [Statement] () -> Style mkStyle = mkStyle' "" mkStyle' :: Text -> Writer [Statement] () -> Style mkStyle' name = Style . execWriter . writeRules . M.toList . flatten . execWriter where -- Convert a list of statements into unique declaration blocks (unique by the -- context, which is the list of suffixes for now). flatten :: [Statement] -> Map ([Condition], [Suffix]) [Declaration] flatten = foldl (go ([],[])) mempty where go k m (SEmit decl) = M.insertWith (flip (<>)) k [decl] m go (cs,ss) m (SCondition c n) = foldl (go (cs <> [c], ss)) (M.insert (cs <> [c], ss) [] m) (execWriter n) go (cs,ss) m (SSuffix s n) = foldl (go (cs, ss <> [s])) (M.insert (cs, ss <> [s]) [] m) (execWriter n) -- Convert a list of declaration blocks into a list of CSS rules. One declaration block -- may map to multiple CSS rules (in the presence of DFontFamily and other special -- declaration types). writeRules :: [(([Condition], [Suffix]), [Declaration])] -> Writer [CSSRule] () writeRules [] = pure () writeRules (((conditions, suffixes), decls):xs) = do styleDeclaration <- forM decls $ \decl -> case decl of (DPlain property value) -> pure (property, value) (DFontFamily ffdecl) -> do let hash = cssStyleDeclarationHash ffdecl -- If the original block doesn't contain a "font-family" declaration, -- generate one from the block hash. let (fontFamily, ffdecl') = case lookup "font-family" ffdecl of Nothing -> let ff = CSSValue ("f-" <> unHash hash) in (ff, ffdecl <> [("font-family", ff)]) Just ff -> (ff, ffdecl) tell [CSSFontFaceRule hash ffdecl'] pure ("font-family", fontFamily) let hash = cssStyleDeclarationHash styleDeclaration tell [CSSStyleRule name hash conditions suffixes styleDeclaration] writeRules xs noStyle :: Style noStyle = Style [] ------------------------------------------------------------------------------- -- | For the purposes of nauva-css, a 'Hash' is simply a newtype around 'Text'. -- It is derived from a 'CSSStyleDeclaration' (which is actually just a list -- of 'CSSDeclaration'). newtype Hash = Hash { unHash :: Text } deriving (Eq, Ord) instance Show Hash where show = show . unHash instance A.ToJSON Hash where toJSON = A.toJSON . unHash cssStyleDeclarationHash :: CSSStyleDeclaration -> Hash cssStyleDeclarationHash = Hash . T.decodeUtf8 . encodeBase58I . fromIntegral . unSipHash . SH.hash sipKey . toStrict . A.encode . toJSON where sipKey = SipKey 0 1 unSipHash (SipHash x) = x encodeBase58I :: Integer -> ByteString encodeBase58I i = BC.pack $ showIntAtBase 58 f i "" where f :: Int -> Char f = chr . fromIntegral . BS.index alphabet . fromIntegral alphabet :: ByteString alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ------------------------------------------------------------------------------- -- | A condition under which a 'CSSStyleRule' should be active. Corresponds to -- @media and @supports conditional group rules. -- -- NB. There is also @document, but it's weird and we don't support that. data Condition = CMedia !Text | CSupports !Text deriving (Eq, Ord) instance Show Condition where show (CMedia x) = "@media(" <> T.unpack x <> ")" show (CSupports x) = "@supports(" <> T.unpack x <> ")" instance A.ToJSON Condition where toJSON (CMedia x) = A.toJSON [A.toJSON (1 :: Int), A.toJSON x] toJSON (CSupports x) = A.toJSON [A.toJSON (2 :: Int), A.toJSON x] ------------------------------------------------------------------------------- -- | A suffix is a pseudo-class or pseudo-element. -- -- The inner text includes any leading colons that are required by the selector. newtype Suffix = Suffix { unSuffix :: Text } deriving (Eq, Ord) instance Show Suffix where show = show . unSuffix instance A.ToJSON Suffix where toJSON = A.toJSON . unSuffix instance IsString Suffix where fromString = Suffix . T.pack ------------------------------------------------------------------------------- class CSSTerm a where cssTerm :: Text -> a instance CSSTerm CSSValue where cssTerm = CSSValue instance (a ~ (), v1 ~ CSSValue) => CSSTerm (v1 -> Writer [Statement] a) where cssTerm property v1 = tell [SEmit $ DPlain property v1] instance (a ~ (), v1 ~ CSSValue, v2 ~ CSSValue) => CSSTerm (v1 -> v2 -> Writer [Statement] a) where cssTerm property (CSSValue v1) (CSSValue v2) = tell [SEmit $ DPlain property $ CSSValue $ v1 <> " " <> v2] instance (a ~ (), v1 ~ CSSValue, v2 ~ CSSValue, v3 ~ CSSValue) => CSSTerm (v1 -> v2 -> v3 -> Writer [Statement] a) where cssTerm property (CSSValue v1) (CSSValue v2) (CSSValue v3) = tell [SEmit $ DPlain property $ CSSValue $ v1 <> " " <> v2 <> " " <> v3] instance (a ~ (), v1 ~ CSSValue, v2 ~ CSSValue, v3 ~ CSSValue, v4 ~ CSSValue) => CSSTerm (v1 -> v2 -> v3 -> v4 -> Writer [Statement] a) where cssTerm property (CSSValue v1) (CSSValue v2) (CSSValue v3) (CSSValue v4) = tell [SEmit $ DPlain property $ CSSValue $ v1 <> " " <> v2 <> " " <> v3 <> " " <> v4] instance (a ~ (), v ~ CSSValue) => CSSTerm (v -> Writer [CSSDeclaration] a) where cssTerm property value = tell [(property, value)]
wereHamster/nauva
pkg/hs/nauva-css/src/Nauva/CSS/Types.hs
mit
10,534
7
31
2,271
2,449
1,330
1,119
173
6
----------------------------------------------------------------------------- -- -- Module : DecisionTrees.TreeBranching.Debug -- Copyright : -- License : MIT -- -- Maintainer : -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module DecisionTrees.TreeBranching.Debug ( TreeBranchingDebug(..) ) where import DecisionTrees.TreeBranching import DecisionTrees.Definitions import Data.Set (Set) -- | An abstraction for debugging decision trees building process. class (TreeBranching entry conf) => TreeBranchingDebug entry conf where -- | best attributes for splitting is descending order. selectBestAttrSplitting' :: (?clazz :: ClassDescriptor, ?config :: conf ) => [entry] -- ^ select from -> Set AttributeName -- ^ except given attributes -> [(([AttrValSet], Float), [[(AttributeContainer, Int)]])] -- ^ sorted splitting
fehu/min-dat--decision-trees
src/DecisionTrees/TreeBranching/Debug.hs
mit
1,026
0
14
235
140
92
48
-1
-1
module TexParser ( Kind , Eval , functionDispatch , Record , parseDocument , toTex , texHeader , onlyExternalize ) where import Text.ParserCombinators.Parsec -- a data type that specifies the kind of operation on contents of a tex command data Operation = Environment String | Command1 String | Enclosed String | Paragraph | Text | Link String | Empty deriving (Show, Eq) -- specifies how to handle the parsed pieces data Eval = Header | Convert Operation | Externalize Operation | ExternalizeInline Operation deriving (Show, Eq) -- specifies the integer that is necessary to keep track of what number the external files will have type Record = Int -- the composed type which will be used as the results of parsing a single logical statement type Kind = ((Eval, Record) , String) -- recursively apply the parseRules and keep track of the record until the end of the LaTeX document is reached parseDocument rec = do first@((eval, newRec), str) <- parseRules rec next <- endOfFile <|> parseDocument newRec return (first:next) -- the end of the LaTeX file endOfFile = do try (string "\\end{document}") return [] -- which parsing rules to apply. Note that the order is important parseRules i = try (header i) <|> try (environment i) <|> try (link i) <|> try (command1 i) <|> try (paragraphStart1 i) <|> try (paragraphStart2 i) <|> try (paragraphContinue i) <|> try (emptyLines i) <|> try (lineBreak i) <|> try (dollarMathEqn i) <|> try (inlineMath i) <|> try (comments i) -------------------------------------------------- -- Parsing -------------------------------------------------- -- the LaTeX header header i = do string "\\documentclass" -- begins with the documentclass statement manyTill anyChar (char '}') -- and some statements and arguments ending with '}' skipMany (oneOf " \n") -- there might be some spaces or newline characters -- everything until \begin{document} is considered the header: arg <- manyTill anyChar (try (string ("\\begin{document}"))) -- Fix me: spaces? skipMany (oneOf " \n") -- if there are some spaces or newlines, we will skip them return ((Header, i), arg) -- save the header -- an environment begins with \begin{...} and ends with \end{...} environment i = do string "\\begin" -- it's only an environment if it begins with \begin spaces -- followd by possibly some spaces char '{' -- and then the argument description <- manyTill anyChar (char '}') -- what kind of environment? -- parse anything until the \end{...} statement. NO NESTING SUPPORTED: arg <- manyTill anyChar (try (string ("\\end{" ++ description ++ "}"))) many (oneOf " \n") -- skip trailing whitespace and newlines -- for now all environments are externalized. -- the Record integer is increased by one: return ((Externalize (Environment description), i+1), arg) -- except environments, all commands with one argument like \command{...} are handled here command1 i = do char '\\' -- always begins with a backslash description <- many1 (noneOf " {") -- followed by the name of the commands spaces -- possibly some whitespace char '{' -- argument of the command arg <- manyTill anyChar (char '}') -- argument ends with '}' return ((Convert (Command1 description), i), arg ) -- mark for conversion to HTML -- a hyperlink link i = do char '\\' -- always starts with a \ try (string "href") -- followed by the command href spaces -- possibly some whitespace char '{' -- and the first argument url <- manyTill anyChar (char '}') -- that contains the URL spaces -- followed by zero or more whitespace char '{' -- and the second argument name <- manyTill anyChar (char '}') -- that contains the name of the link return ( (Convert (Link url), i), name) -- hyperlinks are converted to HTML -- a paragraph that needs a <p> in the beginning paragraphStart1 i = do char '\n' -- if there is a newline spaces -- followed by zero or more whitespace char '\n' -- and another newline, we know that anything that follows is a new paragraph many (oneOf " \n") -- all other whitespace and newlines don't matter. arg <- many1 (noneOf stopChars) -- anything that follows that is not a key character return ((Convert Paragraph,i) , arg) -- is a paragraph -- another possibility for a paragraph is that it appears after some section statement -- note that command1 has its trailing newline not removed while math environments have them removed paragraphStart2 i = do char '\n' many (oneOf " ") arg <- many1 (noneOf stopChars) return ((Convert Paragraph,i) , arg) -- if there are no newline characters, we can assume that the text is not meant to be a new paragraph paragraphContinue i = do arg <- many1 (noneOf stopChars) return ((Convert Text,i) , arg) -- all things starting with a % character are considered a comment and removed comments i = do char '%' skipMany (noneOf "\n") return ((Convert Empty, i), []) -- if for some reason, there are blank lines, we will remove them emptyLines i = do char '\n' spaces char '\n' return ((Convert Empty,i) , []) -- if all else fails and we have still lineBreaks, we will remove them lineBreak i = do many1 (oneOf "\n") return ((Convert Empty,i) , []) -- this is the typical math equation initiated and concluded by $$ dollarMathEqn i = do try (string "$$") arg <- manyTill anyChar (try (string "$$")) many (oneOf " ") char '\n' return ((Externalize (Enclosed "$$"), i+1), arg) -- inline math initiated and concluded with $. Note that this needs to be distinguished from other Math environments as it needs a different CSS style inlineMath i = do char '$' arg <- manyTill anyChar (char '$') return ((ExternalizeInline (Enclosed "$"), i+1), arg) -- characters that should trigger to stop parsing text. stopChars = "$%\n\\" -------------------------------------------------- --this function defines how our internal represantation as a Kind data type is translated to HTML. functionDispatch :: Kind -> String -- the TeX header should be completely omitted functionDispatch ( (Header, _) , _ ) = "" -- paragraphs should be initiated by a <p> functionDispatch ( (Convert Paragraph, _) , arg ) = "<p>" ++ arg ++ "\n" -- continued text (no new paragraph) should be taken verbatim functionDispatch ( (Convert Text, _) , arg ) = arg ++ "\n" -- parsed content that contains no information functionDispatch ( (Convert Empty, _) , arg ) = "" -- all commands with one argument are translated to the <div> tags with the class attribute being the command name functionDispatch ( (Convert (Command1 str), _) , arg ) = htmlEnv "div" ("class=\"" ++ str ++ "\"") arg -- all hyperlinks are translated to <a> tags with class attribute "textlink" functionDispatch ( (Convert (Link str), _) , arg ) = htmlEnv "a" ("class=\"textlink\" href=\"" ++ str ++ "\"") arg -- all externalized equations are included with the <img> tag with class "eqn". Note that we need to refer to the correct file by assuming that it is named i.svg where i is the record of the externalized equation functionDispatch ( (Externalize _ , i), arg) = (htmlImg "eqn" ((show i) ++ ".svg")) ++ "\n" -- inlined math is handled the same as equation environments but with class attribute "eqninline" for separate CSS style modifications functionDispatch ( (ExternalizeInline _ , i), arg) = htmlImg "eqninline" ((show i) ++ ".svg") -- if all fails, it fails functionDispatch _ = error "functionDispatch: failed to find suitable function" -- This function wraps a statement that needs to be externalized into a complete tex file with standalone documentclass toTex :: String -> String -> Kind -> String -- environments need to be rewrapped into \begin{...} and \end{...} statements toTex document_commands xs ((Externalize (Environment str), _), arg) = xs ++ document document_commands (env str arg) -- enclosed math environments like $$ need to be rewrapped as well toTex document_commands xs ((Externalize (Enclosed str), _), arg) = xs ++ document document_commands (enclose str arg) -- inline math environments need to be wrapped into $ symbols and we need to add invisible \bigl. and \bigr. statements to make vertical alignment possible. The SVG files contain no information on the baseline of the font, thus we need to somewhat ensure that the height of all inline math is the same toTex document_commands xs ((ExternalizeInline (Enclosed str), _), arg) = xs ++ document document_commands (enclose str ("\\bigl." ++ arg ++ "\\bigr.") ) -- if all fails, it fails toTex _ _ _ = error "toTex: didn't define the operation yet" -- builds a string for an HTML statement embraced into tags htmlEnv :: String -> String -> String -> String htmlEnv tag options content = "<" ++ tag ++ " " ++ options ++ ">" ++ content ++ "</" ++ tag ++ ">\n" -- creates a string denoting an HTML img htmlImg :: String -> String -> String htmlImg c src = "<img class=\"" ++ c ++ "\" src=\"" ++ src ++ "\"/>" -- creates a LaTeX environment env name content = "\\begin{" ++ name ++ "}" ++ content ++ "\\end{" ++ name ++ "}\n" enclose name content = name ++ content ++ name ++ "\n" document document_commands content = "\\begin{document}\n" ++ document_commands ++ content ++ "\\end{document}" -- extracts the Header from a list of parsed content and appends it to a another documentclass statement texHeader :: String -> [Kind] -> String texHeader header ( ((eval, rec), arg) :xs) | eval == Header = header ++ arg | otherwise = error "No header found in .tex file" -- filters all parsed content that needs to be externalized onlyExternalize :: [Kind] -> [Kind] onlyExternalize [] = [] onlyExternalize (first@((Externalize str, rec),arg):xs) = first: onlyExternalize xs onlyExternalize (first@((ExternalizeInline str, rec),arg):xs) = first: onlyExternalize xs onlyExternalize (_:xs) = onlyExternalize xs
dino-r/casttex
src/TexParser.hs
mit
10,169
0
18
2,131
2,220
1,150
1,070
140
1
-- Haskell uses normal order evaluation test x y = if x == 0 then 0 else y -- Newton's Square Root Method squareRoot x = squareIter x 1 where squareIter num guess = if goodEnough guess then guess else squareIter num (imporvedGuess guess) where goodEnough guess = (abs $ num - guess * guess) < 0.0001 imporvedGuess var = (var + num/var) / 2 squareRoot2 x = squareIter x 1 1 where squareIter num guess delta = let newDelta = goodEnough guess in if (abs $ delta - newDelta) < 0.001 then guess else squareIter num (improvedGuess guess) (newDelta) where goodEnough guess = (abs $ num -guess * guess) improvedGuess var = (var + num/var) / 2 -- Factorial of a number -- Recursive Procedure Recursive Process factorialIf num = if (num == 0) || (num == 1) then 1 else num * factorialIf (num - 1) factorialCase num = case num of 0 -> 1 1 -> 1 _ -> num * factorialCase (num - 1) factorialGaurds num | num == 0 = 1 | num == 1 = 1 | otherwise = num *factorialGaurds (num - 1) -- Factorial Using Recursive Procedure and Iterative Process -- Uses Tail Call Optimization factorialIter num = factIterative 1 1 num where factIterative result counter num = if counter > num then result else factIterative (result * counter) (counter + 1) num -- Fibbonacci Series -- 0, 1, 1, 2, 3, 5, 8 fib n | n == 0 = 0 | n == 1 = 1 | otherwise = fib (n-1) + fib (n-2) consecutiveSum (x:y:xs) = x+y : consecutiveSum (y:xs) consecutiveSum (x:xs) = [] consecutiveSum [] = [] pascalTriangle num = if num == 1 then [1] else [1] ++ (consecutiveSum $ pascalTriangle (num-1)) ++ [1] expr base power = expHelp base power 1 where expHelp base power result = if power == 0 then result else expHelp base (power-1) (result * base) expfast base power | power == 0 = 1 | even power = (expfast base (power `div` 2)) ** 2 | otherwise = base * expfast base (power-1) expSquare base power = expSquare base power 1 where expSquare base power a | power == 0 = a | even power = expSquare (base * base) (power `div` 2) a | otherwise = expSquare (base) (power-1) (a * base) mul a b | b == 1 = a | otherwise = a + mul a (b-1) mulIterative a b = mulhelp a b 0 where mulhelp a b result | b == 0 = result | otherwise = mulhelp a (b - 1) (result + a) mulfast a b = mulhelp a b 0 where mulhelp a b result | b == 0 = result | even b = mulhelp a (b `div` 2) (result * 2) | otherwise = mulhelp a (b - 1) (result + a) double :: (Num a) => a -> a double x = x + x mulfastR a b | b == 0 = 0 | even b = double(mulfastR a (b `div` 2)) | otherwise = a + mulfastR a (b-1) cube x = x * x * x p x = 3 * x - 4 * cube x sine angle count = if abs angle < 0.1 then (angle, count-1) else sine (angle/3) (count+1) fibIter num = fibhelper 0 1 num where fibhelper a b num | num == 0 = a | otherwise = fibhelper b (a+b) (num-1) -- GCD algorithms are based on the fact that gcd(x, y) = gcd(y, x/y) -- It is possible to show that after repeated reductions will always -- eventually produce a pair where second number is zero. mygcd a b | a < b = gcdhelper b a | otherwise = gcdhelper a b where gcdhelper x y = if y == 0 then x else gcdhelper y (x `mod` y)
gitrookie/functionalcode
code/Haskell/sicp/chap1/first.hs
mit
4,075
0
13
1,656
1,474
742
732
76
3
{-# LANGUAGE UnicodeSyntax #-} module F91 where import Data.Peano ( PeanoNat ) f91 ∷ PeanoNat → PeanoNat f91 n = if n > 100 then n - 10 else f91 (f91 (n + 11))
asr/fotc
notes/FOT/FOTC/Program/McCarthy91/F91.hs
mit
167
0
10
37
64
36
28
5
2
{- | Module : Control.Monad.Levels.Writer.Strict Description : Strict writer monad Copyright : (c) Ivan Lazar Miljenovic License : MIT Maintainer : [email protected] -} module Control.Monad.Levels.Writer.Strict ( writer , tell , HasWriter , listen , CanListen , ListenFn , pass , CanPass , PassFn , WriterT(..) , IsWriter ) where import Control.Monad.Levels.Writer import Control.Monad.Trans.Writer.Strict (WriterT (..))
ivan-m/monad-levels
Control/Monad/Levels/Writer/Strict.hs
mit
485
0
6
111
73
51
22
14
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} -- | -- Module: BigE.Types -- Copyright: (c) 2017 Patrik Sandahl -- Licence: MIT -- Maintainer: Patrik Sandahl <[email protected]> -- Stability: experimental -- Portability: portable module BigE.Types ( ToGLenum (..) , ToGLint (..) , BufferTarget (..) , BufferUsage (..) , Primitive (..) , ShaderType (..) , Location (..) , Shader (..) , Program (..) , Buffer (..) , Framebuffer (..) , Texture (..) , TextureFormat (..) , TextureMagFilter (..) , TextureMinFilter (..) , TextureWrap (..) , VertexArray (..) , Uniform (..) ) where import Control.Monad.IO.Class (MonadIO, liftIO) import Foreign (castPtr, with) import Graphics.GL (GLenum, GLfloat, GLint, GLuint) import qualified Graphics.GL as GL import Linear (M44, V2, V3, V4) class ToGLenum a where toGLenum :: a -> GLenum class ToGLint a where toGLint :: a -> GLint data BufferTarget = ArrayBuffer deriving Show instance ToGLenum BufferTarget where toGLenum ArrayBuffer = GL.GL_ARRAY_BUFFER data BufferUsage = DynamicDraw | StaticDraw deriving Show instance ToGLenum BufferUsage where toGLenum DynamicDraw = GL.GL_DYNAMIC_DRAW toGLenum StaticDraw = GL.GL_STATIC_DRAW data ShaderType = VertexShader | FragmentShader deriving Show instance ToGLenum ShaderType where toGLenum VertexShader = GL.GL_VERTEX_SHADER toGLenum FragmentShader = GL.GL_FRAGMENT_SHADER data Primitive = Triangles deriving Show instance ToGLenum Primitive where toGLenum Triangles = GL.GL_TRIANGLES newtype Location = Location GLint deriving Show newtype Shader = Shader GLuint deriving Show newtype Program = Program GLuint deriving Show newtype Buffer = Buffer GLuint deriving Show newtype Framebuffer = Framebuffer GLuint deriving Show newtype Texture = Texture GLuint deriving Show data TextureFormat = RGB8 | RGBA8 deriving Show data TextureMagFilter = MagLinear | MagNearest deriving Show instance ToGLint TextureMagFilter where toGLint MagLinear = fromIntegral GL.GL_LINEAR toGLint MagNearest = fromIntegral GL.GL_NEAREST data TextureMinFilter = MinLinear | MinNearest | MinNearestMipmapNearest | MinLinearMipmapNearest | MinNearestMipmapLinear | MinLinearMipmapLinear deriving Show instance ToGLint TextureMinFilter where toGLint MinLinear = fromIntegral GL.GL_LINEAR toGLint MinNearest = fromIntegral GL.GL_NEAREST toGLint MinNearestMipmapNearest = fromIntegral GL.GL_NEAREST_MIPMAP_NEAREST toGLint MinLinearMipmapNearest = fromIntegral GL.GL_LINEAR_MIPMAP_NEAREST toGLint MinNearestMipmapLinear = fromIntegral GL.GL_NEAREST_MIPMAP_LINEAR toGLint MinLinearMipmapLinear = fromIntegral GL.GL_LINEAR_MIPMAP_LINEAR data TextureWrap = WrapRepeat | WrapClampToEdge | WrapClampToBorder deriving Show instance ToGLint TextureWrap where toGLint WrapRepeat = fromIntegral GL.GL_REPEAT toGLint WrapClampToEdge = fromIntegral GL.GL_CLAMP_TO_EDGE toGLint WrapClampToBorder = fromIntegral GL.GL_CLAMP_TO_BORDER newtype VertexArray = VertexArray GLuint deriving Show -- | Class for setting a uniform value to a location. class Uniform a where setUniform :: MonadIO m => Location -> a -> m () -- | Uniform instance for GLint. instance Uniform GLint where setUniform (Location loc) = GL.glUniform1i loc -- | Uniform instance for GLfloat. instance Uniform GLfloat where setUniform (Location loc) = GL.glUniform1f loc -- | Uniform instance for V2 GLfloat. instance Uniform (V2 GLfloat) where setUniform (Location loc) value = liftIO $ with value $ GL.glUniform2fv loc 1 . castPtr -- | Uniform instance for V3 GLfloat. instance Uniform (V3 GLfloat) where setUniform (Location loc) value = liftIO $ with value $ GL.glUniform3fv loc 1 . castPtr -- | Uniform instance for V4 GLfloat. instance Uniform (V4 GLfloat) where setUniform (Location loc) value = liftIO $ with value $ GL.glUniform4fv loc 1 . castPtr -- | Uniform instance for M44 GLfloat. instance Uniform (M44 GLfloat) where setUniform (Location loc) value = liftIO $ with value $ GL.glUniformMatrix4fv loc 1 GL.GL_TRUE . castPtr
psandahl/big-engine
src/BigE/Types.hs
mit
4,462
0
11
1,013
1,005
562
443
120
0
-- Problems/Problem029Spec.hs module Problems.Problem029Spec (main, spec) where import Test.Hspec import Problems.Problem029 main :: IO() main = hspec spec spec :: Spec spec = describe "Problem 29" $ it "Should evaluate to 9183" $ p29 `shouldBe` 9183
Sgoettschkes/learning
haskell/ProjectEuler/tests/Problems/Problem029Spec.hs
mit
266
0
8
51
73
41
32
9
1
--produces statistics on the probes grouped by core sequence --for each core, reports the number of probes, mean intensity, median intensity, min intensity, --max intensity, and standard deviation of the intensity for probes with that core --usage: flankstats core=core_size < extracted microarray alldata file --author: Tristan Bepler ([email protected]) --requires the vector and statistics packages on hackage import Data.List import System.Environment import qualified Data.Map as Map import qualified Data.Vector as Vector import qualified Statistics.Sample as Stats --http://stackoverflow.com/a/16111081 import qualified Data.Set as Set rmdups :: Ord a => [a] -> [a] rmdups = rmdups' Set.empty where rmdups' _ [] = [] rmdups' a (b:c) = if Set.member b a then rmdups' a c else b : rmdups' (Set.insert b a) c data Probe = Probe {name :: String, sqnc :: String, intensity :: Double} instance Read Probe where readsPrec _ s = [(Probe (tokens !! 0) (tokens !! 1) (read $ tokens !! 2), unwords $ drop 3 tokens)] where tokens = words s instance Show Probe where show probe = unwords [name probe, sqnc probe, show $ intensity probe] groupByCore :: Int -> [Probe] -> [(String, [Probe])] groupByCore coreSize probes = groupByCore' coreSize probes Map.empty where groupByCore' :: Int -> [Probe] -> Map.Map String [Probe] -> [(String, [Probe])] groupByCore' coreSize [] probeMap = Map.toList probeMap groupByCore' coreSize (cur:remainder) probeMap = if Map.member coreSeq probeMap then groupByCore' coreSize remainder (Map.insert coreSeq (cur : (probeMap Map.! coreSeq)) probeMap) else groupByCore' coreSize remainder (Map.insert coreSeq [cur] probeMap) where coreSeq = core coreSize cur core :: Int -> Probe -> String core size probe = drop flank $ take (flank + size) (sqnc probe) where flank = ((length $ sqnc probe) - size) `div` 2 cores :: Int -> [Probe] -> [String] cores size probes = rmdups $ map (core size) probes stats :: [Probe] -> (Int, [Double]) stats probes = (num, [meanVal, medianVal, minVal, maxVal, stdDev]) where listInten = map (intensity) probes inten = Vector.fromList listInten num = fromIntegral $ length listInten maxVal = roundDec 2 $ Vector.maximum inten minVal = roundDec 2 $ Vector.minimum inten meanVal = roundDec 2 $ Stats.mean inten medianVal = roundDec 2 $ median listInten stdDev = roundDec 2 $ Stats.stdDev inten roundDec :: Int -> Double -> Double roundDec dec num = (fromIntegral $ round (num * 10^^dec)) / (fromIntegral 10^^dec) median :: [Double] -> Double median xs = if length xs `mod` 2 == 0 then ((sorted !! middle) + (sorted !! (middle - 1))) / 2.0 else sorted !! middle where sorted = sort xs middle = ((length xs) `div` 2) coreStats :: [(String, [Probe])] -> [(String, (Int, [Double]))] coreStats xs = map (\(coreSeq, probes) -> (coreSeq, stats probes)) xs statHeader :: String statHeader = unwords ["Core", "Count", "Mean", "Median", "Min", "Max", "StdDev"] statsToString :: [(String, (Int, [Double]))] -> String statsToString stats = unlines $ [statHeader] ++ map (statToString) stats statToString :: (String, (Int, [Double])) -> String statToString (coreSeq, (count, stats)) = unwords $ [coreSeq] ++ [(show count)] ++ (map (show) stats) toString :: [(String, [Probe])] -> String toString ((coreSeq, probes):xs) = coreSeq ++ "\n" ++ (unlines $ map (show) probes) ++ "\n" ++ toString xs main = do args <- getArgs let coreSize = if length args >= 1 then read $ head args else error "No core size specified." interact(\x-> statsToString $ coreStats $ groupByCore coreSize $ map (read) $ lines x)
tbepler/PBM-Analysis
flankstats.hs
mit
3,600
12
14
622
1,389
757
632
63
3
{-# LANGUAGE OverloadedStrings #-} module Network.Freddy ( connect, disconnect, Connection, respondTo, tapInto, deliverWithResponse, deliver, cancelConsumer, Consumer, Delivery (..), Error (..) ) where import Control.Concurrent (forkIO) import qualified Network.AMQP as AMQP import Data.Text (Text, pack) import Data.ByteString.Lazy.Char8 (ByteString) import qualified Control.Concurrent.BroadcastChan as BC import System.Timeout (timeout) import Network.Freddy.ResultType (ResultType) import qualified Network.Freddy.ResultType as ResultType import qualified Network.Freddy.Request as Request import Network.Freddy.CorrelationIdGenerator (CorrelationId, generateCorrelationId) type Payload = ByteString type QueueName = Text type ReplyWith = Payload -> IO () type FailWith = Payload -> IO () type ResponseChannelEmitter = BC.BroadcastChan BC.In (Maybe AMQP.PublishError, AMQP.Message) type ResponseChannelListener = BC.BroadcastChan BC.Out (Maybe AMQP.PublishError, AMQP.Message) data Error = InvalidRequest Payload | TimeoutError deriving (Show, Eq) type Response = Either Error Payload data Delivery = Delivery Payload ReplyWith FailWith data Reply = Reply QueueName AMQP.Message data Connection = Connection { amqpConnection :: AMQP.Connection, amqpProduceChannel :: AMQP.Channel, amqpResponseChannel :: AMQP.Channel, responseQueueName :: Text, eventChannel :: ResponseChannelEmitter } data Consumer = Consumer { consumerTag :: AMQP.ConsumerTag, consumerChannel :: AMQP.Channel } {-| Creates a connection with the message queue. __Example__: @ connection <- Freddy.connect "127.0.0.1" "/" "guest" "guest" @ -} connect :: String -- ^ server host -> Text -- ^ virtual host -> Text -- ^ user name -> Text -- ^ password -> IO Connection connect host vhost user pass = do connection <- AMQP.openConnection host vhost user pass produceChannel <- AMQP.openChannel connection responseChannel <- AMQP.openChannel connection AMQP.declareExchange produceChannel AMQP.newExchange { AMQP.exchangeName = topicExchange, AMQP.exchangeType = "topic", AMQP.exchangeDurable = False } eventChannel <- BC.newBroadcastChan (responseQueueName, _, _) <- declareQueue responseChannel "" AMQP.consumeMsgs responseChannel responseQueueName AMQP.NoAck $ responseCallback eventChannel AMQP.addReturnListener produceChannel (returnCallback eventChannel) return $ Connection { amqpConnection = connection, amqpResponseChannel = responseChannel, amqpProduceChannel = produceChannel, responseQueueName = responseQueueName, eventChannel = eventChannel } {-| Closes the connection with the message queue. __Example__: @ connection <- Freddy.connect "127.0.0.1" "/" "guest" "guest" Freddy.disconnect connection @ -} disconnect :: Connection -> IO () disconnect = AMQP.closeConnection . amqpConnection {-| Sends a message and waits for the response. __Example__: @ import qualified Network.Freddy as Freddy import qualified Network.Freddy.Request as R connection <- Freddy.connect "127.0.0.1" "/" "guest" "guest" response <- Freddy.deliverWithResponse connection R.newReq { R.queueName = "echo", R.body = "{\\"msg\\": \\"what did you say?\\"}" } case response of Right payload -> putStrLn "Received positive result" Left (Freddy.InvalidRequest payload) -> putStrLn "Received error" Left Freddy.TimeoutError -> putStrLn "Request timed out" @ -} deliverWithResponse :: Connection -> Request.Request -> IO Response deliverWithResponse connection request = do correlationId <- generateCorrelationId let msg = AMQP.newMsg { AMQP.msgBody = Request.body request, AMQP.msgCorrelationID = Just correlationId, AMQP.msgDeliveryMode = Just AMQP.NonPersistent, AMQP.msgType = Just "request", AMQP.msgReplyTo = Just $ responseQueueName connection, AMQP.msgExpiration = Request.expirationInMs request } responseChannelListener <- BC.newBChanListener $ eventChannel connection AMQP.publishMsg' (amqpProduceChannel connection) "" (Request.queueName request) True msg AMQP.publishMsg (amqpProduceChannel connection) topicExchange (Request.queueName request) msg responseBody <- timeout (Request.timeoutInMicroseconds request) $ do let messageMatcher = matchingCorrelationId correlationId waitForResponse responseChannelListener messageMatcher case responseBody of Just (Nothing, msg) -> return . createResponse $ msg Just (Just error, _) -> return . Left . InvalidRequest $ "Publish Error" Nothing -> return $ Left TimeoutError createResponse :: AMQP.Message -> Either Error Payload createResponse msg = do let msgBody = AMQP.msgBody msg case AMQP.msgType msg of Just msgType -> if (ResultType.fromText msgType) == ResultType.Success then Right msgBody else Left . InvalidRequest $ msgBody _ -> Left . InvalidRequest $ "No message type" {-| Send and forget type of delivery. It sends a message to given destination without waiting for a response. This is useful when there are multiple consumers that are using 'tapInto' or you just do not care about the response. __Example__: @ import qualified Network.Freddy as Freddy import qualified Network.Freddy.Request as R connection <- Freddy.connect "127.0.0.1" "/" "guest" "guest" Freddy.deliver connection R.newReq { R.queueName = "notifications.user_signed_in", R.body = "{\\"user_id\\": 1}" } @ -} deliver :: Connection -> Request.Request -> IO () deliver connection request = do let msg = AMQP.newMsg { AMQP.msgBody = Request.body request, AMQP.msgDeliveryMode = Just AMQP.NonPersistent, AMQP.msgExpiration = Request.expirationInMs request } AMQP.publishMsg (amqpProduceChannel connection) "" (Request.queueName request) msg AMQP.publishMsg (amqpProduceChannel connection) topicExchange (Request.queueName request) msg return () {-| Responds to messages on a given destination. It is useful for messages that have to be processed once and then a result must be sent. __Example__: @ processMessage (Freddy.Delivery body replyWith failWith) = replyWith body connection <- Freddy.connect "127.0.0.1" "/" "guest" "guest" Freddy.respondTo connection "echo" processMessage @ -} respondTo :: Connection -> QueueName -> (Delivery -> IO ()) -> IO Consumer respondTo connection queueName callback = do let produceChannel = amqpProduceChannel connection consumeChannel <- AMQP.openChannel . amqpConnection $ connection declareQueue consumeChannel queueName tag <- AMQP.consumeMsgs consumeChannel queueName AMQP.NoAck $ replyCallback callback produceChannel return Consumer { consumerChannel = consumeChannel, consumerTag = tag } {-| Listens for messages on a given destination or destinations without consuming them. __Example__: @ processMessage body = putStrLn body connection <- Freddy.connect "127.0.0.1" "/" "guest" "guest" Freddy.tapInto connection "notifications.*" processMessage @ -} tapInto :: Connection -> QueueName -> (Payload -> IO ()) -> IO Consumer tapInto connection queueName callback = do consumeChannel <- AMQP.openChannel . amqpConnection $ connection declareExlusiveQueue consumeChannel queueName AMQP.bindQueue consumeChannel "" topicExchange queueName let consumer = callback . AMQP.msgBody .fst tag <- AMQP.consumeMsgs consumeChannel queueName AMQP.NoAck consumer return Consumer { consumerChannel = consumeChannel, consumerTag = tag } {-| Stops the consumer from listening new messages. __Example__: @ connection <- Freddy.connect "127.0.0.1" "/" "guest" "guest" consumer <- Freddy.tapInto connection "notifications.*" processMessage threadDelay tenMinutes $ Freddy.cancelConsumer consumer @ -} cancelConsumer :: Consumer -> IO () cancelConsumer consumer = do AMQP.cancelConsumer (consumerChannel consumer) $ consumerTag consumer AMQP.closeChannel (consumerChannel consumer) returnCallback :: ResponseChannelEmitter -> (AMQP.Message, AMQP.PublishError) -> IO () returnCallback eventChannel (msg, error) = BC.writeBChan eventChannel (Just error, msg) responseCallback :: ResponseChannelEmitter -> (AMQP.Message, AMQP.Envelope) -> IO () responseCallback eventChannel (msg, _) = BC.writeBChan eventChannel (Nothing, msg) replyCallback :: (Delivery -> IO ()) -> AMQP.Channel -> (AMQP.Message, AMQP.Envelope) -> IO () replyCallback userCallback channel (msg, env) = do let requestBody = AMQP.msgBody msg let replyWith = sendReply msg channel ResultType.Success let failWith = sendReply msg channel ResultType.Error let delivery = Delivery requestBody replyWith failWith forkIO . userCallback $ delivery return () sendReply :: AMQP.Message -> AMQP.Channel -> ResultType -> Payload -> IO () sendReply originalMsg channel resType body = case buildReply originalMsg resType body of Just (Reply queueName message) -> do AMQP.publishMsg channel "" queueName message return () Nothing -> putStrLn "Could not reply" buildReply :: AMQP.Message -> ResultType -> Payload -> Maybe Reply buildReply originalMsg resType body = do queueName <- AMQP.msgReplyTo originalMsg let msg = AMQP.newMsg { AMQP.msgBody = body, AMQP.msgCorrelationID = AMQP.msgCorrelationID originalMsg, AMQP.msgDeliveryMode = Just AMQP.NonPersistent, AMQP.msgType = Just . ResultType.serializeResultType $ resType } Just $ Reply queueName msg matchingCorrelationId :: CorrelationId -> AMQP.Message -> Bool matchingCorrelationId correlationId msg = case AMQP.msgCorrelationID msg of Just msgCorrelationId -> msgCorrelationId == correlationId Nothing -> False topicExchange :: Text topicExchange = "freddy-topic" waitForResponse :: ResponseChannelListener -> (AMQP.Message -> Bool) -> IO (Maybe AMQP.PublishError, AMQP.Message) waitForResponse eventChannelListener predicate = do (error, msg) <- BC.readBChan eventChannelListener if predicate msg then return (error, msg) else waitForResponse eventChannelListener predicate declareQueue :: AMQP.Channel -> QueueName -> IO (Text, Int, Int) declareQueue channel queueName = AMQP.declareQueue channel AMQP.newQueue {AMQP.queueName = queueName} declareExlusiveQueue :: AMQP.Channel -> QueueName -> IO (Text, Int, Int) declareExlusiveQueue channel queueName = AMQP.declareQueue channel AMQP.newQueue { AMQP.queueName = queueName, AMQP.queueExclusive = True }
salemove/freddy-hs
src/Network/Freddy.hs
mit
10,672
1
14
1,905
2,305
1,190
1,115
176
3
{-# LANGUAGE BangPatterns #-} module Integrators where import Physics import Numeric.Units.Dimensional.Prelude as D import Numeric.Units.Dimensional.NonSI import qualified Prelude import Graphics.Rendering.OpenGL as GL import BodyGravityForces import DataStructures as DS import Data.List as List import Data.Sequence as Seq stepsize = 2000 *~ second --foo :: (a -> b -> a) -> a -> b -> a --foo f y t = y -- where y_next = y + stepsize/6 * (k1 + 2*k2 + 2*k3 + k4) -- t_next = t + stepsize -- k1 = f t y -- k2 = f (t + stepsize / 2) (y + stepsize/2 * k1) -- k3 = f (t + stepsize / 2) (y + stepsize/2 * k2) -- k4 = f (t + stepsize) (y + stepsize * k3) --bar t ((Vector3 px, py, pz), (Vector3 vx, vy, vz)) -- http://spiff.rit.edu/richmond/nbody/OrbitRungeKutta4.pdf yay --vi_next ri = a*ri --alternatingly: --update acceleration --do runge kutta step --or in other words: -- ??? --symplectic useVelocityVerlet objects = objects `seq` (flip (velocityVerlet calculateAccelerationsFromGravity) stepsize $! accClearedObjs) where accClearedObjs = fmap (\(Object p o v a m) -> (Object p o v (Vector3 zeroAcc zeroAcc zeroAcc) m)) objects zeroAcc = (0 *~ (meter / second / second)) optUseVelocityVerlet objects = objects `seq` (flip (velocityVerlet optimizedCalculateAccelerationsFromGravity) stepsize $! accClearedObjs) where accClearedObjs = fmap (\(Object p o v a m) -> (Object p o v (Vector3 zeroAcc zeroAcc zeroAcc) m)) objects zeroAcc = (0 *~ (meter / second / second)) velocityVerlet accFunc objects t = objsVel1 where objsVel0_5 = fmap (\(Object p o v a m) -> (Object p o (vel0_5 v a) a m)) objects vel0_5 vel0 acc0 = vectorAdd vel0 (vectorTimesScalar acc0 ((num 0.5) * t)) objsPos1 = fmap (\(Object p o v a m) -> (Object (pos1 p v) o v a m)) objsVel0_5 pos1 pos0 vel0_5 = vectorAdd pos0 (vectorTimesScalar vel0_5 t) objsAcc1 = accFunc objsPos1 -- actually: derive acc1 from the interaction potential using x1 objsVel1 = fmap (\(Object p o v a m) -> (Object p o (vel1 v a) a m)) objsAcc1 vel1 vel0_5 acc1 = vectorAdd vel0_5 (vectorTimesScalar acc1 ((num 0.5) * t)) useExplicitEuler = flip (explicitEuler optimizedCalculateAccelerationsFromGravity) stepsize explicitEuler accFunc objects t = fmap (\(Object p o v a m) -> (Object (pos1 v) o (vel1 a) a m)) objAcc0 where pos1 vel0 = vectorTimesScalar vel0 t vel1 acc0 = vectorTimesScalar acc0 t objAcc0 = accFunc objects useStroemerMethod :: Time GLdouble -> Seq.Seq Object -> Seq.Seq Object useStroemerMethod = flip (stroemerMethod optimizedCalculateAccelerationsFromGravity) stroemerMethod accFunc objects t = objsPos where objsPos = fmap (\(Object !p !o !v !a !m) -> (Object (pos_new p (vectorTimesScalar v (1 *~ second)) a) o (vectorTimesScalar p ((num 1) / (1 *~ second))) nullAccVec m)) objsAccNew pos_new p p_old a = (vectorAdd (vectorSubstract (vectorTimesScalar p (num 2)) p_old) (vectorTimesScalar a (t * t))) objsAccNew = accFunc objects nullAccVec = (Vector3 nullAcc nullAcc nullAcc) nullAcc = 0 *~ (meter / second / second) --a1 = a1 + a1inc --a2 = a2 + a2inc --(a1inc,a2inc) = (\(a,b) -> ((acc m a),(acc m b))) $ getGravityForceVector m1 m2 p1 p2 --main = print helper --helper = (foldl (\acc f -> useVelocityVerlet acc) objMaker $ [1..864000])
Stratege/NBody-Simulation
integrators.hs
mit
3,277
33
18
599
737
438
299
39
1
data Color = WHITE | BLACK | PURPLE | RED | GREEN | ORANGE cutWire :: Color -> [Color] -> Bool cutWire _ [] = False cutWire WHITE (WHITE:xs) = True cutWire WHITE (BLACK:xs) = True cutWire BLACK (WHITE:xs) = True cutWire BLACK (GREEN:xs) = True cutWire BLACK (ORANGE:xs) = True cutWire PURPLE (PURPLE:xs) = True cutWire PURPLE (GREEN:xs) = True cutWire PURPLE (ORANGE:xs) = True cutWire PURPLE (WHITE:xs) = True cutWire RED (WHITE:xs) = True cutWire RED (BLACK:xs) = True cutWire RED (PURPLE:xs) = True cutWire RED (RED:xs) = True cutWire RED (ORANGE:xs) = True cutWire ORANGE (WHITE:xs) = True cutWire ORANGE (PURPLE:xs) = True cutWire ORANGE (GREEN:xs) = True cutWire ORANGE (ORANGE:xs) = True cutWire GREEN (BLACK:xs) = True cutWire GREEN (PURPLE:xs) = True cutWire GREEN (RED:xs) = True cutWire GREEN (GREEN:xs) = True cutWire _ (x:xs) = cutWire x xs test :: [[Color]] -> [String] test [] = [] test (x:xs) | (cutWire (head x) (tail x)) = ["Boom"] ++ test xs | otherwise = ["Bomb defused"] ++ test xs main = mapM_ putStrLn $ test [[WHITE, RED, GREEN, WHITE], [WHITE, ORANGE, GREEN, WHITE]]
dariosilva/dailyProgrammer
easy/293/main.hs
mit
1,113
0
11
208
592
316
276
32
1
module Main (main) where import CabalFull (projectName) main :: IO () main = putStrLn ("Benchmarks for " ++ projectName)
vrom911/hs-init
summoner-cli/examples/cabal-full/benchmark/Main.hs
mit
124
0
7
22
42
24
18
4
1
module Draw where import Graphics.UI.GLUT import Colors import Util drawNGon :: ColorFG -> Position -> GLint -> GLint -> GLfloat -> IO () drawNGon c (Position x_ y_) n_ d_ phi = do let [x, y, d, n] = map fromIntegral [x_, y_, d_, n_] :: [GLfloat] color c renderPrimitive Polygon $ mapM_ vertex $ do let cossin = (,) <$> cos <*> sin (dx, dy) <- map (onTuple (d *) . cossin . (+ phi) . ((2 * pi / n) *)) [1 .. n] return $ Vertex2 (x + dx) (y + dy)
mrlovre/LMTetrys
src/Draw.hs
gpl-2.0
536
0
17
185
249
133
116
13
1
module E.CPR(Val(..), cprAnalyzeDs, cprAnalyzeProgram) where import Control.Monad.Writer(Writer(..),runWriter,tell,Monoid(..)) import Data.Binary import Data.Monoid() import Data.Typeable import qualified Data.Map as Map import Cmm.Number import DataConstructors import Doc.DocLike import E.E import E.Program import GenUtil import Name.Name import Name.Names import Name.VConsts import Util.SameShape import qualified Doc.Chars as C import qualified E.Demand as Demand import qualified Info.Info as Info newtype Env = Env (Map.Map TVr Val) deriving(Monoid) data Val = Top -- the top. | Fun Val -- function taking an arg | Tup Name [Val] -- A constructed product | VInt Number -- A number | Tag [Name] -- A nullary constructor, like True, False | Bot -- the bottom deriving(Eq,Ord,Typeable) {-! derive: Binary !-} trimVal v = f (0::Int) v where f !n Tup {} | n > 5 = Top f n (Tup x vs) = Tup x (map (f (n + 1)) vs) f n (Fun v) = Fun (f n v) f _ x = x toVal c = case conSlots c of [] -> Tag [conName c] ss -> Tup (conName c) [ Top | _ <- ss] instance Show Val where showsPrec _ Top = C.top showsPrec _ Bot = C.bot showsPrec n (Fun v) = C.lambda <> showsPrec n v showsPrec _ (Tup n [x,xs]) | n == dc_Cons = shows x <> showChar ':' <> shows xs showsPrec _ (Tup n xs) | Just _ <- fromTupname n = tupled (map shows xs) showsPrec _ (Tup n xs) = shows n <> tupled (map shows xs) showsPrec _ (VInt n) = shows n showsPrec _ (Tag [n]) | n == dc_EmptyList = showString "[]" showsPrec _ (Tag [n]) = shows n showsPrec _ (Tag ns) = shows ns lub :: Val -> Val -> Val lub Bot a = a lub a Bot = a lub Top a = Top lub a Top = Top lub (Tup a xs) (Tup b ys) | a == b, sameShape1 xs ys = Tup a (zipWith lub xs ys) | a == b = error "CPR.lub this shouldn't happen" | otherwise = Top lub (Fun l) (Fun r) = Fun (lub l r) lub (VInt n) (VInt n') | n == n' = VInt n lub (Tag xs) (Tag ys) = Tag (smerge xs ys) lub (Tag _) (Tup _ _) = Top lub (Tup _ _) (Tag _) = Top lub _ _ = Top --lub a b = error $ "CPR.lub: " ++ show (a,b) instance Monoid Val where mempty = Bot mappend = lub {-# NOINLINE cprAnalyzeProgram #-} cprAnalyzeProgram :: Program -> Program cprAnalyzeProgram prog = ans where nds = cprAnalyzeDs (progDataTable prog) (programDs prog) ans = programSetDs' nds prog -- { progStats = progStats prog `mappend` stats } cprAnalyzeDs :: DataTable -> [(TVr,E)] -> [(TVr,E)] cprAnalyzeDs dataTable ds = fst $ cprAnalyzeBinds dataTable mempty ds cprAnalyzeBinds :: DataTable -> Env -> [(TVr,E)] -> ([(TVr,E)],Env) cprAnalyzeBinds dataTable env bs = f env (decomposeDs bs) [] where f env (Left (t,e):rs) zs = case cprAnalyze dataTable env e of (e',v) -> f (envInsert t v env) rs ((tvrInfo_u (Info.insert $ trimVal v) t,e'):zs) f env (Right xs:rs) zs = g (length xs + 2) ([ (t,(e,Bot)) | (t,e) <- xs]) where g 0 mp = f nenv rs ([ (tvrInfo_u (Info.insert $ trimVal b) t,e) | (t,(e,b)) <- mp] ++ zs) where nenv = Env (Map.fromList [ (t,b) | (t,(e,b)) <- mp]) `mappend` env g n mp = g (n - 1) [ (t,cprAnalyze dataTable nenv e) | (t,e) <- xs] where nenv = Env (Map.fromList [ (t,b) | (t,(e,b)) <- mp]) `mappend` env f env [] zs = (reverse zs,env) envInsert :: TVr -> Val -> Env -> Env envInsert tvr val (Env mp) = Env $ Map.insert tvr val mp cprAnalyze :: DataTable -> Env -> E -> (E,Val) cprAnalyze dataTable env e = cprAnalyze' env e where cprAnalyze' (Env mp) (EVar v) | Just t <- Map.lookup v mp = (EVar v,t) | Just t <- Info.lookup (tvrInfo v) = (EVar v,t) | otherwise = (EVar v,Top) cprAnalyze' env ELetRec { eDefs = ds, eBody = e } = (ELetRec ds' e',val) where (ds',env') = cprAnalyzeBinds dataTable env ds (e',val) = cprAnalyze' (env' `mappend` env) e cprAnalyze' env (ELam t e) | Just (Demand.S _) <- Info.lookup (tvrInfo t), Just c <- getProduct dataTable (tvrType t) = let (e',val) = cprAnalyze' (envInsert t (toVal c) env) e in (ELam t e',Fun val) cprAnalyze' env (ELam t e) = (ELam t e',Fun val) where (e',val) = cprAnalyze' (envInsert t Top env) e cprAnalyze' env ec@(ECase {}) = runWriter (caseBodiesMapM f ec) where f e = do (e',v) <- return $ cprAnalyze' env e tell v return e' cprAnalyze' env (EAp fun arg) = (EAp fun_cpr arg,res_res) where (fun_cpr, fun_res) = cprAnalyze' env fun res_res = case fun_res of Fun x -> x Top -> Top Bot -> Bot v -> error $ "cprAnalyze'.res_res: " ++ show v cprAnalyze' env e = (e,f e) where f (ELit (LitInt n _)) = VInt n f (ELit LitCons { litName = n, litArgs = [], litType = _ }) = Tag [n] f (ELit LitCons { litName = n, litArgs = xs, litType = _ }) = Tup n (map g xs) f (EPi t e) = Tup tc_Arrow [g $ tvrType t, g e] f (EPrim {}) = Top -- TODO fix primitives f (EError {}) = Bot f e = error $ "cprAnalyze'.f: " ++ show e g = snd . cprAnalyze' env
dec9ue/jhc_copygc
src/E/CPR.hs
gpl-2.0
5,200
0
19
1,452
2,481
1,292
1,189
-1
-1
module ModelLoader where import Sg import Prelude hiding (catch) import Foreign import Foreign.Marshal.Alloc import Graphics.Formats.Assimp hiding(Clamp) import Graphics.Rendering.OpenGL.GL hiding (Diffuse) import Data.Array.Storable import Data.Array.MArray import Data.Array.IArray hiding (indices) import qualified Graphics.Rendering.OpenGL.Raw as Raw import Codec.Image.DevIL import System.FilePath.Posix import Graphics.UI.GLUT.Objects import Control.Exception import TgaLoader processing = [ CalcTangentSpace , Triangulate , JoinIdenticalVertices ] getEigiRenderAction :: IO (IO ()) getEigiRenderAction = do let objs = [ ("body.obj","EigiBodyColor.jpg","EigiBody_NORMAL.jpg") -- , ("drool.obj","EigiDrool_COLOR.png","EigiDrool_NORMAL.jpg") , ("eyes.obj","EigiEye_COLOR.jpg","EigiEye_NORMAL.jpg") , ("lowerTeeth.obj","EigiTeeth_COLOR.jpg","EigiTeeth_NORMAL.jpg") , ("upperTeeth.obj","EigiTeeth_COLOR.jpg","EigiTeeth_NORMAL.jpg") ] let prefix = "../data/Eigi/" renderActions <- mapM (\(obj,color,normal) -> loadObj (prefix++obj) (prefix++color) (prefix++normal)) objs return $ sequence_ renderActions loadObj :: String -> String -> String -> IO (IO ()) loadObj file colormap normalmap = do ilInit putStrLn $ "importing: " ++ file sceneE <- importFile file processing let scene = case sceneE of Left errorStr -> error $ "could not load model: " ++ errorStr Right s -> s putStrLn "imported." let sceneMeshes = meshes scene let objs = children $ rootNode scene let firstLevel = concatMap nodeMeshes objs let firstObj = sceneMeshes !! fromIntegral (head firstLevel) mesh2VBO firstObj (Just colormap) (Just normalmap) allGetTextureConf :: GetTextureConf allGetTextureConf = GetTextureConf True True True True True True loadImgToMemory :: String -> IO (Ptr Word8, (Int,Int,Int)) loadImgToMemory p = do img <- readImage p let ((0,0,0),size@(w,h,bpp)) = bounds img mem <- mallocBytes ((w+1)*(h+1)*(bpp+1)) pokeArray mem (elems img) return (mem,size) loadImageAndGenSetter :: String -> IO (IO ()) loadImageAndGenSetter s = if takeExtension s == ".tga" then loadImageAndGenSetterFast s else loadImageAndGenSetterDevil s loadImageAndGenSetterFast :: String -> IO (IO ()) loadImageAndGenSetterFast s = catch (do texture <- loadTgaPtr s createTexture return $ textureBinding Texture2D $= Just texture) nop nop :: IOException -> IO (IO()) nop _ = return (return ()) createTexture :: Maybe TGA -> Ptr Word8 -> IO TextureObject createTexture Nothing _ = genAndBindTexture createTexture (Just tga) ptr = do let w' = w tga let h' = h tga let bpp' = bpp tga tex <- genAndBindTexture let (format,internal) = if bpp'==24 then (BGR,RGBA8) else (BGRA,RGBA8) texImage2D Nothing NoProxy 0 internal (TextureSize2D (fromIntegral w') (fromIntegral h')) 0 (PixelData format UnsignedByte ptr) return tex {- loadImageAndGenSetterGlfw :: String -> IO (IO ()) loadImageAndGenSetterGlfw s = do tex <- genAndBindTexture content <- readFile s success <- loadMemoryTexture2D content [NoRescale] putStrLn $ "success" ++ show success return $ textureBinding Texture2D $= Just tex -} genAndBindTexture :: IO TextureObject genAndBindTexture = do [tex] <- genObjectNames 1 textureBinding Texture2D $= Just tex textureFilter Texture2D $= ((Linear',Nothing),Linear') textureWrapMode Texture2D S $= (Repeated,Repeat) textureWrapMode Texture2D T $= (Repeated,Repeat) return tex loadImageAndGenSetterDevil :: String -> IO (IO ()) loadImageAndGenSetterDevil p = do putStrLn $ "loading image: " ++ p (img,(w,h,bpp)) <- loadImgToMemory p putStrLn $ "loaded image: " ++ show (w+1,w+1,bpp+1) tex <- genAndBindTexture texImage2D Nothing NoProxy 0 RGBA8 (TextureSize2D (fromIntegral w + 1) (fromIntegral h+1)) 0 (PixelData RGBA UnsignedByte img) free img return $ textureBinding Texture2D $= Just tex mesh2VBO :: Mesh -> Maybe String -> Maybe String -> IO (IO ()) mesh2VBO mesh diffuseTexture normalMap = do let allIndices = concatMap indices $ faces mesh setColorMap <- case diffuseTexture of Nothing -> return $ return () Just p -> loadImageAndGenSetter p indexBuffer <- vboOfList ElementArrayBuffer allIndices vertexBuffer <- vboOfList ArrayBuffer $ vertices mesh normalBuffer <- vboOfList ArrayBuffer $ normals mesh coordsBuffer <- vboOfList ArrayBuffer $ textureCoords mesh tangentsBuffer <- vboOfList ArrayBuffer $ tangents mesh bitangentsBuffer <- vboOfList ArrayBuffer $ bitangents mesh let bindAllBuffers = do bindBuffer ElementArrayBuffer $= Just indexBuffer bindBuffer ArrayBuffer $= Just vertexBuffer arrayPointer VertexArray $= VertexArrayDescriptor 3 Float 0 nullPtr bindBuffer ArrayBuffer $= Just normalBuffer arrayPointer NormalArray $= VertexArrayDescriptor 3 Float 0 nullPtr bindBuffer ArrayBuffer $= Just coordsBuffer arrayPointer TextureCoordArray $= VertexArrayDescriptor 2 Float 12 nullPtr clientState VertexArray $= Enabled clientState NormalArray $= Enabled clientState TextureCoordArray $= Enabled vao <- do [vao] <- genObjectNames 1 bindVertexArrayObject $= Just vao bindAllBuffers bindVertexArrayObject $= Nothing return vao -- gl2 let renderGL2 = do bindAllBuffers setColorMap drawElements Triangles (fromIntegral $ length allIndices) UnsignedInt nullPtr let renderGL3 = do bindVertexArrayObject $= Just vao setColorMap drawElements Triangles (fromIntegral $ length allIndices) UnsignedInt nullPtr return renderGL3 reportGl :: String -> IO () reportGl str = do errorCode <- Raw.glGetError putStrLn $ "glReport: " ++ str ++ " -> " ++ show errorCode vboOfList :: Storable a => BufferTarget -> [a] -> IO BufferObject vboOfList arrayType xs = let elementSize = sizeOf $ head xs size = length xs ptrsize = toEnum $ size * elementSize in do [vboName] <- genObjectNames 1 bindBuffer arrayType $= Just vboName arr <- newListArray (0, size - 1) xs withStorableArray arr (\ptr -> bufferData arrayType $= (ptrsize, ptr, StaticDraw)) bindBuffer arrayType $= Nothing --reportErrors return vboName renderQuadCCW :: IO () renderQuadCCW = renderPrimitive Quads $ do texCoord (TexCoord2 (0::GLfloat) 0) vertex (Vertex3 (0::GLfloat) 0 0) texCoord (TexCoord2 (0::GLfloat) 1) vertex (Vertex3 (0::GLfloat) 1 0) texCoord (TexCoord2 (1::GLfloat) 1) vertex (Vertex3 (1::GLfloat) 1 0) texCoord (TexCoord2 (1::GLfloat) 0) vertex (Vertex3 (1::GLfloat) 0 0)
haraldsteinlechner/lambdaWolf
src/ModelLoader.hs
gpl-3.0
7,140
0
15
1,741
2,180
1,065
1,115
-1
-1
-- Haskell Practical 1 Code -- James Cowgill import Data.Char -- Convert string to integer s2n :: String -> Int s2n = (foldl1 f).(map digitToInt) where f a b = a * 10 + b -- Drop leading whitespace from a string dropLeadingWhitespace :: String -> String dropLeadingWhitespace = dropWhile isSpace -- Expression trees type V = String type N = Int data E = Var V | Val N | Plus E E | Mult E E instance Show E where show (Var s) = s show (Val n) = show n show (Plus a b) = "(" ++ show a ++ " + " ++ show b ++ ")" show (Mult a b) = "(" ++ show a ++ " * " ++ show b ++ ")" -- Evaluate expression tree evaluate :: E -> Int evaluate (Var a) = error ("Unknown variable `" ++ a ++ "`") evaluate (Val n) = n evaluate (Plus a b) = evaluate a + evaluate b evaluate (Mult a b) = evaluate a * evaluate b -- Simplify expressions (very basic) -- reduce will apply the simplifying rules without recursing reduce :: E -> E reduce (Plus e (Val 0)) = e reduce (Plus (Val 0) e) = e reduce (Mult e (Val 1)) = e reduce (Mult (Val 1) e) = e reduce e = e -- simplify iterates over the tree calling reduce simplify :: E -> E simplify (Mult a b) = reduce (Mult (simplify a) (simplify b)) simplify (Plus a b) = reduce (Plus (simplify a) (simplify b)) simplify e = reduce e -- Association lists (maps) type Assoc t = [(String, t)] -- Return list of names in the list names :: Assoc t -> [String] names = map fst -- Return true if first argument is in the list inAssoc :: String -> Assoc a -> Bool inAssoc n l = elem n (names l) -- Fetch item from list or raise an error if it doesn't exist fetch :: String -> Assoc a -> a fetch n [] = error ("key `" ++ n ++ "` does not exist") fetch n (x:xs) | n == fst x = snd x | otherwise = fetch n xs -- Updates / adds an item in the list update :: String -> a -> Assoc a -> Assoc a update k v [] = [(k, v)] update k v (x:xs) | k == fst x = (k, v):xs | otherwise = x:update k v xs -- Evaluation trees reprise evaluate2 :: Assoc Int -> E -> Int evaluate2 v (Var a) = fetch a v evaluate2 _ (Val n) = n evaluate2 v (Plus a b) = evaluate2 v a + evaluate2 v b evaluate2 v (Mult a b) = evaluate2 v a * evaluate2 v b -- Alternate representation data Op = Add | Mul deriving Show data ET = Vr V | Vl N | Ap ET Op ET deriving Show -- Get function which evaluates an operator opFunc :: Op -> (Int -> Int -> Int) opFunc Add = (+) opFunc Mul = (*) -- Main evaluate function evaluate3 :: Assoc Int -> ET -> Int evaluate3 v (Vr a) = fetch a v evaluate3 _ (Vl n) = n evaluate3 v (Ap a op b) = (opFunc op) (evaluate3 v a) (evaluate3 v b) -- Conversion between representations treeToNew :: E -> ET treeToNew (Var v) = Vr v treeToNew (Val n) = Vl n treeToNew (Plus a b) = Ap (treeToNew a) Add (treeToNew b) treeToNew (Mult a b) = Ap (treeToNew a) Mul (treeToNew b) treeToOld :: ET -> E treeToOld (Vr v) = Var v treeToOld (Vl n) = Val n treeToOld (Ap a Add b) = Plus (treeToOld a) (treeToOld b) treeToOld (Ap a Mul b) = Mult (treeToOld a) (treeToOld b) -- Maybe types headT :: [a] -> Maybe a headT [] = Nothing headT xs = Just (head xs) tailT :: [a] -> Maybe [a] tailT [] = Nothing tailT xs = Just (tail xs) lastT :: [a] -> Maybe a lastT [] = Nothing lastT xs = Just (last xs)
jcowgill/cs-work
syac/compilers/Prac1/Prac1.hs
gpl-3.0
3,349
1
10
877
1,478
751
727
80
1
{-# OPTIONS_GHC -Wall -O0 #-} module Main where import Vis import Linear import Control.Lens import Data.Function (on) import Data.List ( sortBy ) import System.Environment import qualified Data.Map.Strict as M import qualified Data.Tree as T import Control.Monad ( guard ) main :: IO () main = do argv <- getArgs animate (defaultOpts { optWindowName = "animate test" , optInitialCamera = Just $ Camera0 0 (-60) 15 }) $ \ time -> let quat x = normalize $ Quaternion 1 (V3 x 0 0 ) in RotQuat (quat 0.5) -- $ Trans (V3 (-10) 0 (-10)) $ case argv of [ "1" ] -> VisObjects [ plane , rule_applications_for time ex1i mx1 $ cube_points 3 ] [ "2" ] -> VisObjects [ plane , reachable time cx1 4 ] [ "3" ] -> VisObjects [ plane , rule_applications_for time ex1i mx1 $ reachable_points cx1 4 , reachable time cx1 4 ] _ -> error "huh" drawFun :: VisObject Double drawFun = VisObjects $ [ plane -- , rule_applications_for z002 m002 $ cube_points 2 -- , rule_applications_for ex1i mx1 $ square_points 3 -- , reachable cx1 -- , rule_applications_for ex1i mx1 $ reachable_points cx1 2 ] data Linear = Linear (V3 Double) (M33 Double) deriving Show apply :: Linear -> V3 Double -> V3 Double apply (Linear a m) p = a + m !* p applies :: (M.Map Char Linear) -> String -> V3 Double -> V3 Double applies int s p = foldr (\ c p -> apply (int M.! c) p) p s data Cone = Cone (V3 Double) (M.Map Char Linear) deriving Show -- (RULES a a -> a b a , b b -> a) zabba = [("aa","aba"),("bb","a")] mabba = M.fromList [('a', Linear (V3 0 0 1)(V3(V3 1 0 3)(V3 0 0 0)(V3 0 0 0))) ,('b', Linear (V3 0 1 0)(V3(V3 1 2 1)(V3 0 0 1)(V3 0 1 0))) ] z026 = [("abb","baa"),("aab","bba")] m026 = M.fromList [ ('a', Linear (V3 1 0 0) (V3 (V3 1 1 0)(V3 0 0 1) (V3 0 1 1)) ) , ('b', Linear (V3 0 1 0) (V3 (V3 1 1 0)(V3 0 0 1)(V3 0 1 1) ) ) ] c026 = Cone (V3 0 0 0) m026 z002 = [("bca","abab"),("b","cc"),("aa","acba")] m002 = M.fromList [ ('a', Linear (V3 0 0 2) (V3 (V3 1 0 1) (V3 0 1 0) (V3 0 2 0))) , ('b', Linear (V3 1 0 0) (V3 (V3 1 1 0) (V3 0 0 0)(V3 0 1 0))) , ('c', Linear (V3 0 0 0) (V3 (V3 1 0 0) (V3 0 0 1) (V3 0 0 0))) ] c002 = Cone (V3 0 0 0) m002 {- actual example from RTA 15 paper Prove termination of $R = \{f g \to f f, gf \to gg\}$. Use domain $D = \{(x_1,x_2,x_3)\in\NN^3\mid x_3\ge x_2+1\}$. {}[f](x_1,x_2,x_3) &=& (x_1+2x_2+1,0,x_3+1) \\ {}[g](x_1,x_2,x_3) &=& (x_1\phantom{+2x_2+1},x_3,x_3+1) \\[5pt] {}[fg](x)&=&(x_1+\phantom{\fbox{0}x_2+}2x_3+\fbox{1},0,x_3+2), \\ {}[ff](x)&=&(x_1+\fbox{2}x_2+\phantom{0x_2+}\fbox{2},0,x_3+2). -} ex1 = [("fg","ff"),("gf","gg")] ex1i = take 1 ex1 mx1 = M.fromList [('f',Linear(V3 1 0 1) (V3 (V3 1 2 0)(V3 0 0 0) (V3 0 0 1))) ,('g',Linear(V3 0 0 1) (V3 (V3 1 0 0)(V3 0 0 1)(V3 0 0 1))) ] cx1 = Cone (V3 0 0 1) mx1 f = mx1 M.! 'f' g = mx1 M.! 'g' Cone e _ = cx1 -- * tree (Cone base lin) dep = let work s p 0 = T.Node (s,p) [] work s p d | d > 0 = T.Node (s,p) $ do (c,f) <- M.toList lin return $ work (c:s) (apply f p) (d-1) in work "" base dep levelorder t = let lo = t : ( lo >>= T.subForest ) in take (length $ T.flatten t) lo render root = Trans (snd $ T.rootLabel root) (Sphere 0.15 Solid white) : do -- Text3d s p TimesRoman24 white : t <- levelorder root let (l,from) = T.rootLabel t (col,s) <- zip [white,greyN 0.5] $ T.subForest t let to = snd $ T.rootLabel s return $ VisObjects [ Line (Just 5) [from, to] col , Trans to $ Sphere 0.15 Solid col ] cube_points d = do x <- [ 0 :: Int,1] -- .. d ] y <- [ 0 :: Int,1 .. d ] z <- [ 0 :: Int,1 .. d ] return $ V3 (realToFrac x)(realToFrac y)(realToFrac z) square_points d = do let x = 0 y <- [ 0 :: Int,1 .. d ] z <- [ 0 :: Int,1 .. d ] return $ V3 (realToFrac x)(realToFrac y)(realToFrac z) cube d = VisObjects $ do [x,y,z] <- sequence $ replicate 3 [0,1] let p = V3 x y z [a,b,c] <- sequence $ replicate 3 [0,1] let q = V3 a b c guard $ 1 == qd p q return $ Line (Just 2) [p ,q] white reachable_points cone dep = map (snd . T.rootLabel) $ levelorder $ tree cone dep rule_applications_for time sys int ps = VisObjects $ do let candidates = do -- sortBy (compare `on` ( \(p,_)-> id $ p ^. _y )) p <- ps ; (l,r) <- sys ; return (p, (l,r)) n = length candidates let pick :: Int pick = mod (truncate time) n (i,(p,(l,r))) <- zip [0..] candidates let prepicked = i <= pick picked = i == pick line from to col = if picked then arrow 10 from to col else Line (Just 1) [from,to] col let from = applies int l p to = applies int r p col = ( if not picked then transp 0.7 else id ) $ if from ^. _x > to ^. _x then blue else red cola = ( if not picked then transp 0.7 else id ) $ if from ^. _x > to ^. _x then green else red lw = if picked then 5 else 1 return $ VisObjects [ if picked then line from to $ light cola else blank , if picked then Line (Just lw) [ p, from] blue else blank , if picked then Line (Just lw) [ p, to ] red else blank , if picked then Triangle p from to cola else blank , if prepicked then Trans p $ Sphere 0.15 Solid cola else blank ] blank = VisObjects [] transp f c = let (r,g,b,a) = rgbaOfColor c in makeColor r g b $ f * a arrow ratio from to col = let dist = to - from rat = ratio * norm dist in Trans from $ Arrow (norm dist , rat) dist col axes = Axes (1,20) reachable time cone dep = VisObjects $ reveal time $ render $ tree cone dep reveal time obs = let n = length obs t = mod (truncate time) n in take (succ t) obs plane = Plane (V3 1 0 0) (greyN 0.8) (makeColor 0.4 0.6 0.65 0.4) {- sphere = Trans (V3 0 x (-1)) $ Sphere 0.15 Wireframe (makeColor 0.2 0.3 0.8 1) ellipsoid = Trans (V3 x 0 (-1)) $ RotQuat quat $ Ellipsoid (0.2, 0.3, 0.4) Solid (makeColor 1 0.3 0.5 1) box = Trans (V3 0 0 x) $ RotQuat quat $ Box (0.2, 0.2, 0.2) Wireframe (makeColor 0 1 1 1) text k = Text2d "OLOLOLOLOLO" (100,500 - k*100*x) TimesRoman24 (makeColor 0 (0.5 + x'/2) (0.5 - x'/2) 1) where x' = realToFrac $ (x + 1)/0.4*k/5 boxText = Text3d "trololololo" (V3 0 0 (x-0.2)) TimesRoman24 (makeColor 1 0 0 1) -}
jwaldmann/visumatrix
Main.hs
gpl-3.0
6,606
0
18
1,970
2,797
1,453
1,344
155
12
-- | Simple wrapper for Nussinov78. We take at most 10 backtracking results -- -- unlimited backtracking would produce an exponential amount of backtracking -- results. The ambiguity is part of the original algorithm! module Main where import Text.Printf import System.Environment -- import BioInf.Nussinov78 import qualified BioInf.GAPlike as G main = do as <- getArgs print as case as of {- [] -> do xs <- fmap lines getContents mapM_ doNussinov78 xs -} ["gaplike"] -> do xs <- fmap lines getContents mapM_ (doGAPlike 0) xs ["gaplike",k] -> do xs <- fmap lines getContents mapM_ (doGAPlike (read k)) xs {- doNussinov78 inp = do putStrLn inp let rs = nussinov78 inp mapM_ (\(e,bt) -> putStr bt >> printf " %5d\n" e) $ take 10 rs -} doGAPlike :: Int -> String -> IO () doGAPlike k inp = do let (n,bt) = G.nussinov78 inp n `seq` printf "%s %d\n" inp n mapM_ putStrLn $ take k bt
choener/Nussinov78
Nussinov78.hs
gpl-3.0
978
0
16
255
212
107
105
17
2
module HsPredictor.Parse.CSV where -- standard import Control.Monad (replicateM) import Control.Monad.Error (fail, liftIO, throwError) import Data.List (sort) -- 3rd party import Text.ParserCombinators.Parsec (Parser, char, count, digit, eof, many, noneOf, parse, try, (<|>)) -- own import HsPredictor.Types.Types (Match (..), ThrowsError) -- | Parse one line from csv file. readMatch :: String -> ThrowsError Match readMatch input = case parse parseCsv "csv" input of Left err -> throwError $ show err Right val -> return val -- | Parse list of lines from csv file. Return sorted matches list. readMatches :: [String] -> [Match] readMatches = sort . foldr (\x acc -> case readMatch x of Left _ -> acc Right m -> m:acc) [] -- | Parser for csv file. parseCsv :: Parser Match parseCsv = do date <- parseDate homeT <- parseTeam awayT <- parseTeam (goalsH, goalsA) <- parseGoals (odd1, oddx, odd2) <- parseOdds eof return $ Match date homeT awayT goalsH goalsA odd1 oddx odd2 -- | Parser for date. parseDate :: Parser Int parseDate = do year <- replicateM 4 digit char '.' month <- replicateM 2 digit char '.' day <- replicateM 2 digit char ',' return $ read (year++month++day) -- | Parser for team. parseTeam :: Parser String parseTeam = do team <- many (noneOf ",") char ',' return team -- | Parser for goals. parseGoals :: Parser (Int, Int) parseGoals = do goalsH <- minusOne <|> many digit char ',' goalsA <- checkField goalsH (many digit) char ',' return (read goalsH :: Int, read goalsA :: Int) -- | Parser for bookie odds. parseOdds :: Parser (Double, Double, Double) parseOdds = do odd1 <- minusOne <|> odds char ',' oddx <- checkField odd1 odds char ',' odd2 <- checkField oddx odds return (read odd1 :: Double, read oddx :: Double, read odd2 :: Double) -- | Parser for "-1" minusOne :: Parser String minusOne = do sign <- char '-' one <- char '1' return [sign, one] -- | Parse one odds value. odds :: Parser String odds = do int <- many digit dot <- char '.' rest <- many digit return $ int ++ [dot] ++ rest -- | Check for "-1" field checkField :: String -> Parser String -> Parser String checkField field p = if field == "-1" then minusOne else p
jacekm-git/HsPredictor
library/HsPredictor/Parse/CSV.hs
gpl-3.0
2,529
0
12
755
799
403
396
70
2
{-# LANGUAGE FlexibleInstances #-} module Database.Design.Ampersand.Classes.ConceptStructure (ConceptStructure(..)) where import Database.Design.Ampersand.Core.AbstractSyntaxTree import Database.Design.Ampersand.Basics import Data.List import Data.Maybe import Database.Design.Ampersand.ADL1.Expression(primitives,isMp1,foldrMapExpression) import Database.Design.Ampersand.Classes.ViewPoint import Prelude hiding (Ordering(..)) fatal :: Int -> String -> a fatal = fatalMsg "Classes.ConceptStructure" {- TODO: Interface parameters (of type Declaration) are returned as Expressions by expressionsIn, to preserve the meaning of relsMentionedIn (implemented using primsMentionedIn, which calls expressionsIn). A more correct way to do this would be to not use expressionsIn, but define relsMentionedIn directly. Another improvement would be to factorize the prim constructors from the Expression data type, so expressionsIn won't need to be partial anymore. -} class ConceptStructure a where concs :: a -> [A_Concept] -- ^ the set of all concepts used in data structure a relsUsedIn :: a -> [Declaration] -- ^ the set of all declaratons used within data structure a. `used within` means that there is a relation that refers to that declaration. relsUsedIn a = [ d | d@Sgn{}<-relsMentionedIn a]++[Isn c | c<-concs a] relsMentionedIn :: a -> [Declaration] -- ^ the set of all declaratons used within data structure a. `used within` means that there is a relation that refers to that declaration. relsMentionedIn = nub . map prim2rel . primsMentionedIn primsMentionedIn :: a -> [Expression] primsMentionedIn = nub . concatMap primitives . expressionsIn expressionsIn :: a -> [Expression] -- ^The set of all expressions within data structure a -- | mp1Pops draws the population from singleton expressions. mp1Pops :: a -> [Population] mp1Pops struc = [ PCptPopu{ popcpt = cpt (head cl) , popas = map atm cl } | cl<-eqCl cpt ((filter isMp1.primsMentionedIn) struc)] where cpt (EMp1 _ c) = c cpt _ = fatal 31 "cpt error" atm (EMp1 a _) = a atm _ = fatal 31 "atm error" prim2rel :: Expression -> Declaration prim2rel e = case e of EDcD d@Sgn{} -> d EDcD{} -> fatal 23 "invalid declaration in EDcD{}" EDcI c -> Isn c EDcV sgn -> Vs sgn EMp1 _ c -> Isn c _ -> fatal 40 $ "only primitive expressions should be found here.\nHere we see: " ++ show e instance (ConceptStructure a,ConceptStructure b) => ConceptStructure (a, b) where concs (a,b) = concs a `uni` concs b expressionsIn (a,b) = expressionsIn a `uni` expressionsIn b instance ConceptStructure a => ConceptStructure (Maybe a) where concs ma = maybe [] concs ma expressionsIn ma = maybe [] expressionsIn ma instance ConceptStructure a => ConceptStructure [a] where concs = nub . concatMap concs expressionsIn = foldr ((uni) . expressionsIn) [] instance ConceptStructure A_Context where concs ctx = foldr uni [ONE] -- ONE is allways in any context. (see https://github.com/AmpersandTarski/ampersand/issues/70) [ (concs.ctxpats) ctx , (concs.ctxrs) ctx , (concs.ctxds) ctx , (concs.ctxpopus) ctx , (concs.ctxcds) ctx , (concs.ctxks) ctx , (concs.ctxvs) ctx , (concs.ctxgs) ctx , (concs.ctxifcs) ctx , (concs.ctxps) ctx , (concs.ctxsql) ctx , (concs.ctxphp) ctx ] expressionsIn ctx = foldr uni [] [ (expressionsIn.ctxpats) ctx , (expressionsIn.ctxifcs) ctx , (expressionsIn.ctxrs) ctx , (expressionsIn.ctxks) ctx , (expressionsIn.ctxvs) ctx , (expressionsIn.ctxsql) ctx , (expressionsIn.ctxphp) ctx , (expressionsIn.multrules) ctx , (expressionsIn.identityRules) ctx ] instance ConceptStructure IdentityDef where concs identity = [idCpt identity] `uni` concs [objDef | IdentityExp objDef <- identityAts identity] expressionsIn identity = expressionsIn [objDef | IdentityExp objDef <- identityAts identity] instance ConceptStructure ViewDef where concs vd = [vdcpt vd] `uni` concs [objDef | ViewExp _ objDef <- vdats vd] expressionsIn vd = expressionsIn [objDef | ViewExp _ objDef <- vdats vd] instance ConceptStructure Expression where concs (EDcI c ) = [c] concs (EEps i sgn) = nub (i:concs sgn) concs (EDcV sgn) = concs sgn concs (EMp1 _ c ) = [c] concs e = foldrMapExpression uni concs [] e expressionsIn e = [e] instance ConceptStructure A_Concept where concs c = [c] expressionsIn _ = [] instance ConceptStructure ConceptDef where concs cd = [PlainConcept { cptnm = name cd } ] expressionsIn _ = [] instance ConceptStructure Sign where concs (Sign s t) = nub [s,t] expressionsIn _ = [] instance ConceptStructure ObjectDef where concs obj = [target (objctx obj)] `uni` concs (objmsub obj) expressionsIn obj = foldr (uni) [] [ (expressionsIn.objctx) obj , (expressionsIn.objmsub) obj ] -- Note that these functions are not recursive in the case of InterfaceRefs (which is of course obvious from their types) instance ConceptStructure SubInterface where concs (Box _ _ objs) = concs objs concs InterfaceRef{} = [] expressionsIn (Box _ _ objs) = expressionsIn objs expressionsIn InterfaceRef{} = [] instance ConceptStructure Pattern where concs pat = foldr uni [] [ (concs.ptrls) pat , (concs.ptgns) pat , (concs.ptdcs) pat , (concs.ptups) pat , (concs.ptids) pat , (concs.ptxps) pat ] expressionsIn p = foldr (uni) [] [ (expressionsIn.ptrls) p , (expressionsIn.ptids) p , (expressionsIn.ptvds) p ] instance ConceptStructure Interface where concs ifc = concs (ifcObj ifc) expressionsIn ifc = foldr (uni) [] [ (expressionsIn.ifcObj) ifc , map EDcD $ ifcParams ifc -- Return param declarations as expressions ] instance ConceptStructure Declaration where concs d = concs (sign d) expressionsIn _ = fatal 148 "expressionsIn not allowed on Declaration" instance ConceptStructure Rule where concs r = concs (rrexp r) `uni` concs (rrviol r) expressionsIn r = foldr (uni) [] [ (expressionsIn.rrexp ) r , (expressionsIn.rrviol) r ] instance ConceptStructure (PairView Expression) where concs (PairView ps) = concs ps expressionsIn (PairView ps) = expressionsIn ps instance ConceptStructure Population where concs pop@PRelPopu{} = concs (popdcl pop) concs pop@PCptPopu{} = concs (popcpt pop) expressionsIn _ = [] instance ConceptStructure Purpose where concs pop@Expl{} = concs (explObj pop) expressionsIn _ = [] instance ConceptStructure ExplObj where concs (ExplConceptDef cd) = concs cd concs (ExplDeclaration d) = concs d concs (ExplRule _) = [{-beware of loops...-}] concs (ExplIdentityDef _) = [{-beware of loops...-}] concs (ExplViewDef _) = [{-beware of loops...-}] concs (ExplPattern _) = [{-beware of loops...-}] concs (ExplInterface _) = [{-beware of loops...-}] concs (ExplContext _) = [{-beware of loops...-}] expressionsIn _ = [] instance ConceptStructure (PairViewSegment Expression) where concs pvs = case pvs of PairViewText{} -> [] PairViewExp{} -> concs (pvsExp pvs) expressionsIn pvs = case pvs of PairViewText{} -> [] PairViewExp{} -> expressionsIn (pvsExp pvs) instance ConceptStructure A_Gen where concs g@Isa{} = nub [gengen g,genspc g] concs g@IsE{} = nub (genspc g: genrhs g) expressionsIn _ = fatal 160 "expressionsIn not allowed on A_Gen"
DanielSchiavini/ampersand
src/Database/Design/Ampersand/Classes/ConceptStructure.hs
gpl-3.0
8,369
0
15
2,402
2,351
1,215
1,136
159
6
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} module Graph where import GHC.TypeLits -- import Data.Array import Data.Graph (Graph) import Data.Hashable import Data.Maybe (mapMaybe) import Data.List (sortBy ) -- import Data.Permute import Data.Fin1 -- import Prelude hiding (lookup) -- | type Vertex n = Fin1 n -- | data UndirEdge n = UE { edgeV1 :: Vertex n , edgeV2 :: Vertex n } deriving (Show, Eq) instance (KnownNat n) => Hashable (UndirEdge n) where hashWithSalt salt (UE v1 v2) = hashWithSalt salt (v1,v2) -- | verticesFromEdge :: UndirEdge n -> [Vertex n] verticesFromEdge (UE x y) = [x,y] -- | isSelfish :: UndirEdge n -> Bool isSelfish (UE x y) = x == y -- | edgecmp :: UndirEdge n -> UndirEdge n -> Ordering edgecmp (UE x1 x2) (UE y1 y2) = compare (x1,x2) (y1,y2) -- | mkUndirEdge :: Vertex n -> Vertex n -> UndirEdge n mkUndirEdge x y | x <= y = UE x y | otherwise = UE y x -- | connectedVertex :: Vertex n -> UndirEdge n -> Maybe (Vertex n) connectedVertex v (UE x y) | v == x = Just y | v == y = Just x | otherwise = Nothing -- | data SortedEdges n = SE { unSE :: [UndirEdge n] } deriving (Show, Eq) instance (KnownNat n) => Hashable (SortedEdges n) where hashWithSalt salt (SE xs) = hashWithSalt salt xs -- | mkSortedEdges :: [UndirEdge n] -> SortedEdges n mkSortedEdges xs = SE (sortBy edgecmp xs) -- | newtype UndirGraph n = UG { edges :: SortedEdges n } deriving (Show, Eq) instance (KnownNat n) => Hashable (UndirGraph n) where hashWithSalt salt (UG xs) = hashWithSalt salt xs -- | mkUndirGraph :: [UndirEdge n] -> UndirGraph n mkUndirGraph es = UG (mkSortedEdges es) -- | permuteEdge :: Perm n -> UndirEdge n -> UndirEdge n permuteEdge p (UE v1 v2) = mkUndirEdge (permute p v1) (permute p v2) -- | permuteGraph :: Perm n -> UndirGraph n -> UndirGraph n permuteGraph p (UG (SE es)) = UG (mkSortedEdges (map (permuteEdge p) es)) -- | type AssocMap n = Array (Vertex n) [Vertex n] -- | mkAssocMap :: (KnownNat n) => UndirGraph n -> AssocMap n mkAssocMap (UG (SE es)) = let alst = map (\v -> (v, mapMaybe (connectedVertex v) es)) interval in array (1,order) alst -- | degree :: AssocMap n -> [ Vertex n ] -> Vertex n -> Int degree arr ptn i = length (filter (`elem` ptn) (arr ! i)) -- | assocMapToGraph :: forall n. (KnownNat n) => AssocMap n -> Graph assocMapToGraph asc = let n = intValue (order :: Fin1 n) asc' = ixmap (1,n) mkFin1Mod asc in fmap (map intValue) asc' -- | undirToDirected :: forall n. (KnownNat n) => UndirGraph n -> Graph undirToDirected = assocMapToGraph . mkAssocMap
wavewave/qft
old/lib/Graph.hs
gpl-3.0
2,833
0
15
778
1,126
589
537
60
1
-- Module por synthesizing inspections -- from tokens, keywords and operators module Language.Mulang.Analyzer.Synthesizer ( encodeUsageInspection, encodeDeclarationInspection, decodeIsInspection, decodeUsageInspection, decodeDeclarationInspection, generateInspectionEncodingRules, generateOperatorEncodingRules ) where import Language.Mulang.Analyzer.Analysis (Inspection) import Language.Mulang.Operators (Token) import Language.Mulang.Ast.Operator (Operator) import Control.Monad ((>=>)) import Text.Read (readMaybe) import Data.List (stripPrefix) type Encoder a = a -> Inspection type Decoder a = Inspection -> Maybe a type EncodingRuleGenerator a b = (a, b) -> [(Inspection, Inspection)] -- converts an operator into an inspection encodeUsageInspection :: Encoder Operator encodeUsageInspection = encodeInspection "Uses" encodeDeclarationInspection :: Encoder Operator encodeDeclarationInspection = encodeInspection "Declares" encodeInspection :: String -> Encoder Operator encodeInspection prefix = (prefix ++) . show -- extract an operator from an inspection decodeIsInspection :: Decoder Operator decodeIsInspection = decodeInspection "Is" decodeUsageInspection :: Decoder Operator decodeUsageInspection = decodeInspection "Uses" decodeDeclarationInspection :: Decoder Operator decodeDeclarationInspection = decodeInspection "Declares" decodeInspection :: String -> Decoder Operator decodeInspection prefix = stripPrefix prefix >=> readMaybe generateInspectionEncodingRules :: EncodingRuleGenerator Token Inspection generateInspectionEncodingRules = generateEncodingRules id id generateOperatorEncodingRules :: EncodingRuleGenerator Token Operator generateOperatorEncodingRules = generateEncodingRules encodeUsageInspection encodeDeclarationInspection generateEncodingRules :: Encoder a -> Encoder a -> EncodingRuleGenerator Token a generateEncodingRules usageEncoder declarationEncoder = baseMatchers >=> generateBaseEncodingRules >=> generateNegationEncodingRules where baseMatchers ("*", v) = [("=*", v)] baseMatchers (('=':xs), v) = [(('=':'=':xs), v)] baseMatchers (k, v) = [(k, v), ("=" ++ k, v)] generateBaseEncodingRules (k, v) = [("Uses:" ++ k, usageEncoder v), ("Declares:" ++ k, declarationEncoder v)] generateNegationEncodingRules :: EncodingRuleGenerator Inspection Inspection generateNegationEncodingRules (k, v) = [(k, v), ("Not:" ++ k, "Not:" ++ v)]
mumuki/mulang
src/Language/Mulang/Analyzer/Synthesizer.hs
gpl-3.0
2,504
0
11
371
569
325
244
43
3
module Paths_Wreathed_in_Iron ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,0,0], versionTags = []} bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/Users/Ian/Documents/Programs/Haskell/Wreathed_in_Iron/.cabal-sandbox/bin" libdir = "/Users/Ian/Documents/Programs/Haskell/Wreathed_in_Iron/.cabal-sandbox/lib/x86_64-osx-ghc-7.6.3/Wreathed-in-Iron-0.1.0.0" datadir = "/Users/Ian/Documents/Programs/Haskell/Wreathed_in_Iron/.cabal-sandbox/share/x86_64-osx-ghc-7.6.3/Wreathed-in-Iron-0.1.0.0" libexecdir = "/Users/Ian/Documents/Programs/Haskell/Wreathed_in_Iron/.cabal-sandbox/libexec" sysconfdir = "/Users/Ian/Documents/Programs/Haskell/Wreathed_in_Iron/.cabal-sandbox/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "Wreathed_in_Iron_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "Wreathed_in_Iron_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "Wreathed_in_Iron_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "Wreathed_in_Iron_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "Wreathed_in_Iron_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
iMurfyD/Wreathed_in_Iron
dist/build/autogen/Paths_Wreathed_in_Iron.hs
gpl-3.0
1,662
0
10
182
371
213
158
28
1
{-# LANGUAGE CPP, PackageImports #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Safe #-} #endif module Foreign.StablePtr ( -- * Stable references to Haskell values StablePtr -- abstract , newStablePtr -- :: a -> IO (StablePtr a) , deRefStablePtr -- :: StablePtr a -> IO a , freeStablePtr -- :: StablePtr a -> IO () , castStablePtrToPtr -- :: StablePtr a -> Ptr () , castPtrToStablePtr -- :: Ptr () -> StablePtr a , -- ** The C-side interface -- $cinterface ) where import "base" Foreign.StablePtr as This___ -- $cinterface -- -- The following definition is available to C programs inter-operating with -- Haskell code when including the header @HsFFI.h@. -- -- > typedef void *HsStablePtr; /* C representation of a StablePtr */ -- -- Note that no assumptions may be made about the values representing stable -- pointers. In fact, they need not even be valid memory addresses. The only -- guarantee provided is that if they are passed back to Haskell land, the -- function 'deRefStablePtr' will be able to reconstruct the -- Haskell value referred to by the stable pointer.
jwiegley/ghc-release
libraries/haskell2010/Foreign/StablePtr.hs
gpl-3.0
1,182
0
4
290
60
49
11
10
0
{-| Module : Devel.Watch Description : Watch for changes in the current working direcory. Copyright : (c) License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX Actually checks only for modified files. Added or removed files don't trigger new builds. -} {-# LANGUAGE OverloadedStrings, CPP #-} module Devel.Watch where import Control.Monad.STM import Control.Concurrent.STM.TVar import System.FSNotify import System.FSNotify.Devel import Control.Monad (forever) import Control.Concurrent (threadDelay) # if __GLASGOW_HASKELL__ < 710 import Data.Text (unpack) import Filesystem.Path.CurrentOS (toText) #endif -- | Runs in the current working directory -- Watches for file changes for the specified file extenstions -- When a change is found. It modifies isDirty to True. watch :: TVar Bool -> [FilePath] -> IO () watch isDirty pathsToWatch = do manager <- startManagerConf defaultConfig _ <- watchTree manager "." (const True) # if __GLASGOW_HASKELL__ >= 710 (\event -> do let pathMod :: Event -> FilePath pathMod (Added path _) = path pathMod (Modified path _) = path pathMod (Removed path _) = path isModified <- return (any (== pathMod event) pathsToWatch) atomically $ writeTVar isDirty isModified) #else (\event -> do pathMod <- case toText $ eventPath event of Right text -> return $ unpack text -- Gives an abs path Left text -> fail $ unpack text isModified <- return (any (== pathMod) pathsToWatch) atomically $ writeTVar isDirty isModified) #endif _ <- forever $ threadDelay maxBound stopManager manager -- | Runs in the current working directory. Watches when there's an error. -- Watches for file changes for the specified file extenstions -- When a change is found. It modifies isDirty to True. watchErrored :: TVar Bool -> IO () watchErrored isDirty = do manager <- startManagerConf defaultConfig _ <- treeExtAny manager "." "hamlet" (\_ -> atomically $ writeTVar isDirty True) _ <- treeExtAny manager "." "shamlet" (\_ -> atomically $ writeTVar isDirty True) _ <- treeExtAny manager "." "lucius" (\_ -> atomically $ writeTVar isDirty True) _ <- treeExtAny manager "." "julius" (\_ -> atomically $ writeTVar isDirty True) _ <- treeExtAny manager "." "hs" (\_ -> atomically $ writeTVar isDirty True) _ <- treeExtAny manager "." "lhs" (\_ -> atomically $ writeTVar isDirty True) _ <- treeExtAny manager "." "yaml" (\_ -> atomically $ writeTVar isDirty True) _ <- forever $ threadDelay maxBound stopManager manager checkForChange :: TVar Bool -> IO () checkForChange isDirty = do atomically $ do readTVar isDirty >>= check writeTVar isDirty False
bitemyapp/wai-devel
src/Devel/Watch.hs
gpl-3.0
2,927
0
18
729
612
307
305
41
2
{-# Language TemplateHaskell #-} module Infsabot.Base.Tests ( baseChecks ) where import Infsabot.Base.Logic import Data.Maybe import Data.Function(on) import Infsabot.Tools.Interface import Codec.Picture (PixelRGB8(PixelRGB8)) import Data.DeriveTH(derive, makeArbitrary) import Test.QuickCheck hiding (shuffle) baseChecks :: [IO Result] baseChecks = [ putStrLn "Offset Is Limited" >> doChecks 1 propOffsetIsLimited, putStrLn "Linear Offset" >> doChecks 3 propLinearOffset] propOffsetIsLimited :: Team -> Int -> [RDirection] -> (Int, Int) -> Bool propOffsetIsLimited team len dirs (x, y) = not $ fromMaybe False value where final = limitedOffset team len dirs (x, y) value :: Maybe Bool value = (\(u, v) -> u * u + v * v > len * len) . sub (x, y) <$> final propLinearOffset :: Team -> Int -> [RDirection] -> (Int, Int) -> (Int, Int) -> Bool propLinearOffset team len dirs = (==) `on` off where off xy = sub xy <$> (limitedOffset team len dirs xy :: Maybe (Int, Int)) sub :: (Int, Int) -> (Int, Int) -> (Int, Int) sub (a, b) (c, d) = (a - c, b - d) $( derive makeArbitrary ''PixelRGB8 ) $( derive makeArbitrary ''RobotAppearance ) $( derive makeArbitrary ''Team )
kavigupta/Infsabot
Infsabot/Base/Tests.hs
gpl-3.0
1,225
0
15
248
479
266
213
29
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.Healthcare.Projects.Locations.DataSets.FhirStores.Patch -- 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) -- -- Updates the configuration of the specified FHIR store. -- -- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.fhirStores.patch@. module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.FhirStores.Patch ( -- * REST Resource ProjectsLocationsDataSetsFhirStoresPatchResource -- * Creating a Request , projectsLocationsDataSetsFhirStoresPatch , ProjectsLocationsDataSetsFhirStoresPatch -- * Request Lenses , pldsfspXgafv , pldsfspUploadProtocol , pldsfspUpdateMask , pldsfspAccessToken , pldsfspUploadType , pldsfspPayload , pldsfspName , pldsfspCallback ) where import Network.Google.Healthcare.Types import Network.Google.Prelude -- | A resource alias for @healthcare.projects.locations.datasets.fhirStores.patch@ method which the -- 'ProjectsLocationsDataSetsFhirStoresPatch' request conforms to. type ProjectsLocationsDataSetsFhirStoresPatchResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] FhirStore :> Patch '[JSON] FhirStore -- | Updates the configuration of the specified FHIR store. -- -- /See:/ 'projectsLocationsDataSetsFhirStoresPatch' smart constructor. data ProjectsLocationsDataSetsFhirStoresPatch = ProjectsLocationsDataSetsFhirStoresPatch' { _pldsfspXgafv :: !(Maybe Xgafv) , _pldsfspUploadProtocol :: !(Maybe Text) , _pldsfspUpdateMask :: !(Maybe GFieldMask) , _pldsfspAccessToken :: !(Maybe Text) , _pldsfspUploadType :: !(Maybe Text) , _pldsfspPayload :: !FhirStore , _pldsfspName :: !Text , _pldsfspCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsDataSetsFhirStoresPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pldsfspXgafv' -- -- * 'pldsfspUploadProtocol' -- -- * 'pldsfspUpdateMask' -- -- * 'pldsfspAccessToken' -- -- * 'pldsfspUploadType' -- -- * 'pldsfspPayload' -- -- * 'pldsfspName' -- -- * 'pldsfspCallback' projectsLocationsDataSetsFhirStoresPatch :: FhirStore -- ^ 'pldsfspPayload' -> Text -- ^ 'pldsfspName' -> ProjectsLocationsDataSetsFhirStoresPatch projectsLocationsDataSetsFhirStoresPatch pPldsfspPayload_ pPldsfspName_ = ProjectsLocationsDataSetsFhirStoresPatch' { _pldsfspXgafv = Nothing , _pldsfspUploadProtocol = Nothing , _pldsfspUpdateMask = Nothing , _pldsfspAccessToken = Nothing , _pldsfspUploadType = Nothing , _pldsfspPayload = pPldsfspPayload_ , _pldsfspName = pPldsfspName_ , _pldsfspCallback = Nothing } -- | V1 error format. pldsfspXgafv :: Lens' ProjectsLocationsDataSetsFhirStoresPatch (Maybe Xgafv) pldsfspXgafv = lens _pldsfspXgafv (\ s a -> s{_pldsfspXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pldsfspUploadProtocol :: Lens' ProjectsLocationsDataSetsFhirStoresPatch (Maybe Text) pldsfspUploadProtocol = lens _pldsfspUploadProtocol (\ s a -> s{_pldsfspUploadProtocol = a}) -- | The update mask applies to the resource. For the \`FieldMask\` -- definition, see -- https:\/\/developers.google.com\/protocol-buffers\/docs\/reference\/google.protobuf#fieldmask pldsfspUpdateMask :: Lens' ProjectsLocationsDataSetsFhirStoresPatch (Maybe GFieldMask) pldsfspUpdateMask = lens _pldsfspUpdateMask (\ s a -> s{_pldsfspUpdateMask = a}) -- | OAuth access token. pldsfspAccessToken :: Lens' ProjectsLocationsDataSetsFhirStoresPatch (Maybe Text) pldsfspAccessToken = lens _pldsfspAccessToken (\ s a -> s{_pldsfspAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pldsfspUploadType :: Lens' ProjectsLocationsDataSetsFhirStoresPatch (Maybe Text) pldsfspUploadType = lens _pldsfspUploadType (\ s a -> s{_pldsfspUploadType = a}) -- | Multipart request metadata. pldsfspPayload :: Lens' ProjectsLocationsDataSetsFhirStoresPatch FhirStore pldsfspPayload = lens _pldsfspPayload (\ s a -> s{_pldsfspPayload = a}) -- | Output only. Resource name of the FHIR store, of the form -- \`projects\/{project_id}\/datasets\/{dataset_id}\/fhirStores\/{fhir_store_id}\`. pldsfspName :: Lens' ProjectsLocationsDataSetsFhirStoresPatch Text pldsfspName = lens _pldsfspName (\ s a -> s{_pldsfspName = a}) -- | JSONP pldsfspCallback :: Lens' ProjectsLocationsDataSetsFhirStoresPatch (Maybe Text) pldsfspCallback = lens _pldsfspCallback (\ s a -> s{_pldsfspCallback = a}) instance GoogleRequest ProjectsLocationsDataSetsFhirStoresPatch where type Rs ProjectsLocationsDataSetsFhirStoresPatch = FhirStore type Scopes ProjectsLocationsDataSetsFhirStoresPatch = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsDataSetsFhirStoresPatch'{..} = go _pldsfspName _pldsfspXgafv _pldsfspUploadProtocol _pldsfspUpdateMask _pldsfspAccessToken _pldsfspUploadType _pldsfspCallback (Just AltJSON) _pldsfspPayload healthcareService where go = buildClient (Proxy :: Proxy ProjectsLocationsDataSetsFhirStoresPatchResource) mempty
brendanhay/gogol
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/FhirStores/Patch.hs
mpl-2.0
6,609
0
17
1,377
860
502
358
132
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.Logging.Folders.Sinks.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a sink. If the sink has a unique writer_identity, then that -- service account is also deleted. -- -- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.folders.sinks.delete@. module Network.Google.Resource.Logging.Folders.Sinks.Delete ( -- * REST Resource FoldersSinksDeleteResource -- * Creating a Request , foldersSinksDelete , FoldersSinksDelete -- * Request Lenses , fsdXgafv , fsdUploadProtocol , fsdAccessToken , fsdUploadType , fsdSinkName , fsdCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.folders.sinks.delete@ method which the -- 'FoldersSinksDelete' request conforms to. type FoldersSinksDeleteResource = "v2" :> Capture "sinkName" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Deletes a sink. If the sink has a unique writer_identity, then that -- service account is also deleted. -- -- /See:/ 'foldersSinksDelete' smart constructor. data FoldersSinksDelete = FoldersSinksDelete' { _fsdXgafv :: !(Maybe Xgafv) , _fsdUploadProtocol :: !(Maybe Text) , _fsdAccessToken :: !(Maybe Text) , _fsdUploadType :: !(Maybe Text) , _fsdSinkName :: !Text , _fsdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FoldersSinksDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fsdXgafv' -- -- * 'fsdUploadProtocol' -- -- * 'fsdAccessToken' -- -- * 'fsdUploadType' -- -- * 'fsdSinkName' -- -- * 'fsdCallback' foldersSinksDelete :: Text -- ^ 'fsdSinkName' -> FoldersSinksDelete foldersSinksDelete pFsdSinkName_ = FoldersSinksDelete' { _fsdXgafv = Nothing , _fsdUploadProtocol = Nothing , _fsdAccessToken = Nothing , _fsdUploadType = Nothing , _fsdSinkName = pFsdSinkName_ , _fsdCallback = Nothing } -- | V1 error format. fsdXgafv :: Lens' FoldersSinksDelete (Maybe Xgafv) fsdXgafv = lens _fsdXgafv (\ s a -> s{_fsdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). fsdUploadProtocol :: Lens' FoldersSinksDelete (Maybe Text) fsdUploadProtocol = lens _fsdUploadProtocol (\ s a -> s{_fsdUploadProtocol = a}) -- | OAuth access token. fsdAccessToken :: Lens' FoldersSinksDelete (Maybe Text) fsdAccessToken = lens _fsdAccessToken (\ s a -> s{_fsdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). fsdUploadType :: Lens' FoldersSinksDelete (Maybe Text) fsdUploadType = lens _fsdUploadType (\ s a -> s{_fsdUploadType = a}) -- | Required. The full resource name of the sink to delete, including the -- parent resource and the sink identifier: -- \"projects\/[PROJECT_ID]\/sinks\/[SINK_ID]\" -- \"organizations\/[ORGANIZATION_ID]\/sinks\/[SINK_ID]\" -- \"billingAccounts\/[BILLING_ACCOUNT_ID]\/sinks\/[SINK_ID]\" -- \"folders\/[FOLDER_ID]\/sinks\/[SINK_ID]\" Example: -- \"projects\/my-project-id\/sinks\/my-sink-id\". fsdSinkName :: Lens' FoldersSinksDelete Text fsdSinkName = lens _fsdSinkName (\ s a -> s{_fsdSinkName = a}) -- | JSONP fsdCallback :: Lens' FoldersSinksDelete (Maybe Text) fsdCallback = lens _fsdCallback (\ s a -> s{_fsdCallback = a}) instance GoogleRequest FoldersSinksDelete where type Rs FoldersSinksDelete = Empty type Scopes FoldersSinksDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/logging.admin"] requestClient FoldersSinksDelete'{..} = go _fsdSinkName _fsdXgafv _fsdUploadProtocol _fsdAccessToken _fsdUploadType _fsdCallback (Just AltJSON) loggingService where go = buildClient (Proxy :: Proxy FoldersSinksDeleteResource) mempty
brendanhay/gogol
gogol-logging/gen/Network/Google/Resource/Logging/Folders/Sinks/Delete.hs
mpl-2.0
5,033
0
15
1,090
706
416
290
102
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.Drive.Permissions.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a permission by ID. -- -- /See:/ <https://developers.google.com/drive/ Drive API Reference> for @drive.permissions.get@. module Network.Google.Resource.Drive.Permissions.Get ( -- * REST Resource PermissionsGetResource -- * Creating a Request , permissionsGet , PermissionsGet -- * Request Lenses , pgSupportsAllDrives , pgUseDomainAdminAccess , pgFileId , pgSupportsTeamDrives , pgPermissionId ) where import Network.Google.Drive.Types import Network.Google.Prelude -- | A resource alias for @drive.permissions.get@ method which the -- 'PermissionsGet' request conforms to. type PermissionsGetResource = "drive" :> "v3" :> "files" :> Capture "fileId" Text :> "permissions" :> Capture "permissionId" Text :> QueryParam "supportsAllDrives" Bool :> QueryParam "useDomainAdminAccess" Bool :> QueryParam "supportsTeamDrives" Bool :> QueryParam "alt" AltJSON :> Get '[JSON] Permission -- | Gets a permission by ID. -- -- /See:/ 'permissionsGet' smart constructor. data PermissionsGet = PermissionsGet' { _pgSupportsAllDrives :: !Bool , _pgUseDomainAdminAccess :: !Bool , _pgFileId :: !Text , _pgSupportsTeamDrives :: !Bool , _pgPermissionId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PermissionsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgSupportsAllDrives' -- -- * 'pgUseDomainAdminAccess' -- -- * 'pgFileId' -- -- * 'pgSupportsTeamDrives' -- -- * 'pgPermissionId' permissionsGet :: Text -- ^ 'pgFileId' -> Text -- ^ 'pgPermissionId' -> PermissionsGet permissionsGet pPgFileId_ pPgPermissionId_ = PermissionsGet' { _pgSupportsAllDrives = False , _pgUseDomainAdminAccess = False , _pgFileId = pPgFileId_ , _pgSupportsTeamDrives = False , _pgPermissionId = pPgPermissionId_ } -- | Whether the requesting application supports both My Drives and shared -- drives. pgSupportsAllDrives :: Lens' PermissionsGet Bool pgSupportsAllDrives = lens _pgSupportsAllDrives (\ s a -> s{_pgSupportsAllDrives = a}) -- | Issue the request as a domain administrator; if set to true, then the -- requester will be granted access if the file ID parameter refers to a -- shared drive and the requester is an administrator of the domain to -- which the shared drive belongs. pgUseDomainAdminAccess :: Lens' PermissionsGet Bool pgUseDomainAdminAccess = lens _pgUseDomainAdminAccess (\ s a -> s{_pgUseDomainAdminAccess = a}) -- | The ID of the file. pgFileId :: Lens' PermissionsGet Text pgFileId = lens _pgFileId (\ s a -> s{_pgFileId = a}) -- | Deprecated use supportsAllDrives instead. pgSupportsTeamDrives :: Lens' PermissionsGet Bool pgSupportsTeamDrives = lens _pgSupportsTeamDrives (\ s a -> s{_pgSupportsTeamDrives = a}) -- | The ID of the permission. pgPermissionId :: Lens' PermissionsGet Text pgPermissionId = lens _pgPermissionId (\ s a -> s{_pgPermissionId = a}) instance GoogleRequest PermissionsGet where type Rs PermissionsGet = Permission type Scopes PermissionsGet = '["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive.metadata", "https://www.googleapis.com/auth/drive.metadata.readonly", "https://www.googleapis.com/auth/drive.photos.readonly", "https://www.googleapis.com/auth/drive.readonly"] requestClient PermissionsGet'{..} = go _pgFileId _pgPermissionId (Just _pgSupportsAllDrives) (Just _pgUseDomainAdminAccess) (Just _pgSupportsTeamDrives) (Just AltJSON) driveService where go = buildClient (Proxy :: Proxy PermissionsGetResource) mempty
brendanhay/gogol
gogol-drive/gen/Network/Google/Resource/Drive/Permissions/Get.hs
mpl-2.0
4,867
0
17
1,132
622
369
253
101
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.DiskTypes.AggregatedList -- 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) -- -- Retrieves an aggregated list of disk types. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.diskTypes.aggregatedList@. module Network.Google.Resource.Compute.DiskTypes.AggregatedList ( -- * REST Resource DiskTypesAggregatedListResource -- * Creating a Request , diskTypesAggregatedList , DiskTypesAggregatedList -- * Request Lenses , dtalIncludeAllScopes , dtalReturnPartialSuccess , dtalOrderBy , dtalProject , dtalFilter , dtalPageToken , dtalMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.diskTypes.aggregatedList@ method which the -- 'DiskTypesAggregatedList' request conforms to. type DiskTypesAggregatedListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "aggregated" :> "diskTypes" :> QueryParam "includeAllScopes" Bool :> QueryParam "returnPartialSuccess" Bool :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] DiskTypeAggregatedList -- | Retrieves an aggregated list of disk types. -- -- /See:/ 'diskTypesAggregatedList' smart constructor. data DiskTypesAggregatedList = DiskTypesAggregatedList' { _dtalIncludeAllScopes :: !(Maybe Bool) , _dtalReturnPartialSuccess :: !(Maybe Bool) , _dtalOrderBy :: !(Maybe Text) , _dtalProject :: !Text , _dtalFilter :: !(Maybe Text) , _dtalPageToken :: !(Maybe Text) , _dtalMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DiskTypesAggregatedList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dtalIncludeAllScopes' -- -- * 'dtalReturnPartialSuccess' -- -- * 'dtalOrderBy' -- -- * 'dtalProject' -- -- * 'dtalFilter' -- -- * 'dtalPageToken' -- -- * 'dtalMaxResults' diskTypesAggregatedList :: Text -- ^ 'dtalProject' -> DiskTypesAggregatedList diskTypesAggregatedList pDtalProject_ = DiskTypesAggregatedList' { _dtalIncludeAllScopes = Nothing , _dtalReturnPartialSuccess = Nothing , _dtalOrderBy = Nothing , _dtalProject = pDtalProject_ , _dtalFilter = Nothing , _dtalPageToken = Nothing , _dtalMaxResults = 500 } -- | Indicates whether every visible scope for each scope type (zone, region, -- global) should be included in the response. For new resource types added -- after this field, the flag has no effect as new resource types will -- always include every visible scope for each scope type in response. For -- resource types which predate this field, if this flag is omitted or -- false, only scopes of the scope types where the resource type is -- expected to be found will be included. dtalIncludeAllScopes :: Lens' DiskTypesAggregatedList (Maybe Bool) dtalIncludeAllScopes = lens _dtalIncludeAllScopes (\ s a -> s{_dtalIncludeAllScopes = a}) -- | Opt-in for partial success behavior which provides partial results in -- case of failure. The default value is false. dtalReturnPartialSuccess :: Lens' DiskTypesAggregatedList (Maybe Bool) dtalReturnPartialSuccess = lens _dtalReturnPartialSuccess (\ s a -> s{_dtalReturnPartialSuccess = a}) -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the -- \`creationTimestamp\` field in reverse chronological order (newest -- result first). Use this to sort resources like operations so that the -- newest operation is returned first. Currently, only sorting by \`name\` -- or \`creationTimestamp desc\` is supported. dtalOrderBy :: Lens' DiskTypesAggregatedList (Maybe Text) dtalOrderBy = lens _dtalOrderBy (\ s a -> s{_dtalOrderBy = a}) -- | Project ID for this request. dtalProject :: Lens' DiskTypesAggregatedList Text dtalProject = lens _dtalProject (\ s a -> s{_dtalProject = a}) -- | A filter expression that filters resources listed in the response. The -- expression must specify the field name, a comparison operator, and the -- value that you want to use for filtering. The value must be a string, a -- number, or a boolean. The comparison operator must be either \`=\`, -- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute -- Engine instances, you can exclude instances named \`example-instance\` -- by specifying \`name != example-instance\`. You can also filter nested -- fields. For example, you could specify \`scheduling.automaticRestart = -- false\` to include instances only if they are not scheduled for -- automatic restarts. You can use filtering on nested fields to filter -- based on resource labels. To filter on multiple expressions, provide -- each separate expression within parentheses. For example: \`\`\` -- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\") -- \`\`\` By default, each expression is an \`AND\` expression. However, -- you can include \`AND\` and \`OR\` expressions explicitly. For example: -- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel -- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\` dtalFilter :: Lens' DiskTypesAggregatedList (Maybe Text) dtalFilter = lens _dtalFilter (\ s a -> s{_dtalFilter = a}) -- | Specifies a page token to use. Set \`pageToken\` to the -- \`nextPageToken\` returned by a previous list request to get the next -- page of results. dtalPageToken :: Lens' DiskTypesAggregatedList (Maybe Text) dtalPageToken = lens _dtalPageToken (\ s a -> s{_dtalPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than \`maxResults\`, Compute -- Engine returns a \`nextPageToken\` that can be used to get the next page -- of results in subsequent list requests. Acceptable values are \`0\` to -- \`500\`, inclusive. (Default: \`500\`) dtalMaxResults :: Lens' DiskTypesAggregatedList Word32 dtalMaxResults = lens _dtalMaxResults (\ s a -> s{_dtalMaxResults = a}) . _Coerce instance GoogleRequest DiskTypesAggregatedList where type Rs DiskTypesAggregatedList = DiskTypeAggregatedList type Scopes DiskTypesAggregatedList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient DiskTypesAggregatedList'{..} = go _dtalProject _dtalIncludeAllScopes _dtalReturnPartialSuccess _dtalOrderBy _dtalFilter _dtalPageToken (Just _dtalMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy DiskTypesAggregatedListResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/DiskTypes/AggregatedList.hs
mpl-2.0
8,222
0
20
1,763
842
503
339
123
1
module Plugin where resource = "error"
Changaco/haskell-plugins
testsuite/pdynload/numclass/Plugin.hs
lgpl-2.1
40
0
4
7
9
6
3
2
1
{- Created : 2014 Dec 01 (Mon) 19:11:55 by Harold Carr. Last Modified : 2014 Dec 01 (Mon) 19:37:21 by Harold Carr. -} import Test.HUnit as T import Test.HUnit.Util as U -- HOMEWORK 11 ------------------------------------------------------------------------------ -- EXERCISE 6 fibs = 0 : 1 : [x + y | (x,y) <- zip fibs (tail fibs)] e6 :: [Test] e6 = U.t "e6" (take 10 fibs) [0,1,1,2,3,5,8,13,21,34] ------------------------------------------------------------------------------ -- EXERCISE 7 fib0 n = last (take n fibs) fib1 n = head (drop (n - 1) fibs) fib2 n = fibs !! n -- fib3 n = index fibs n e7 :: [Test] e7 = U.t "e7" (fib2 10) 55 ------------------------------------------------------------------------------ -- EXERCISE 8 largeFib = head (dropWhile (<= 1000) fibs) e8 :: [Test] e8 = U.t "e8" largeFib 1597 ------------------------------------------------------------------------------ -- EXERCISE 9 data Tree a = Leaf | Node (Tree a) a (Tree a) deriving (Eq, Show) repeatTree :: a -> Tree a repeatTree x = Node t x t where t = repeatTree x takeTree :: Int -> Tree a -> a takeTree _ Leaf = error "no way" takeTree 0 (Node _ x _) = x takeTree n (Node l _ _) = takeTree (n - 1) l e9 :: [Test] e9 = U.t "e9" (takeTree 100 (repeatTree 3)) 3 ------------------------------------------------------------------------------ main :: IO Counts main = T.runTestTT $ T.TestList $ e6 ++ e7 ++ e8 ++ e9 -- End of file.
haroldcarr/learn-haskell-coq-ml-etc
haskell/course/2014-10-edx-delft-fp101x-intro-to-fp-erik-meijer/hw11.hs
unlicense
1,539
16
10
360
566
274
292
36
1
module Lst where import Prelude hiding (takeWhile) import qualified Text.Show.Pretty as Pretty import Text.Parsec.Combinator import Text.Parsec.Prim hiding ((<|>)) import Control.Applicative hiding (many) import Modifications import Common -- custom lst types import Lst.Skill(SkillDefinition) import Lst.Language(LanguageDefinition) import Lst.WeaponProf(WeaponProficency) import Lst.ShieldProf(ShieldProficency) import Lst.ArmorProf(ArmorProficency) import Lst.Domain(DomainDefinition) import Lst.Deity(DeityDefinition) import Lst.Spell(SpellDefinition) import Lst.Feat(FeatDefinition) import Lst.Equipment(EquipmentDefinition) import Lst.EquipmentMod(EquipmentModDefinition) import Lst.CompanionMod(CompanionModDefinition) -- generic, catch-all import Lst.Generic(LSTDefinition) -- structure of a lst file data LST a = Source [Header] | Definition a | Comment String deriving Show -- source headers: these are found in nearly every lst file type. data Header = SourceLong String | SourceShort String | SourceWeb String | SourceDate String deriving Show parseSourceWeb :: PParser Header parseSourceWeb = SourceWeb <$> (tag "SOURCEWEB" >> restOfTag) parseSourceLong :: PParser Header parseSourceLong = SourceLong <$> (tag "SOURCELONG" >> restOfTag) parseSourceShort :: PParser Header parseSourceShort = SourceShort <$> (tag "SOURCESHORT" >> restOfTag) parseSourceDate :: PParser Header parseSourceDate = SourceDate <$> (tag "SOURCEDATE" >> restOfTag) parseHeaders :: PParser [Header] parseHeaders = many1 $ header <* tabs where -- trailing tabs, ugh header = parseSourceLong <|> parseSourceShort <|> parseSourceWeb <|> parseSourceDate -- pathological case. blame pbt_equip.lst. parseEmptyLST :: PParser a -> PParser [LST a] parseEmptyLST _ = [] <$ eof parseFullLST :: PParser a -> PParser [LST a] parseFullLST parseDefinition = do _ <- many eol many1 $ lstLine <* many eol where lstLine = Source <$> parseHeaders <|> Comment <$> parseCommentLine <|> Definition <$> parseDefinition parseLST :: Show a => PParser (LSTLine a) -> FilePath -> IO [LST (LSTLine a)] parseLST lstPParser lstName = do contents <- readContents lstName return $ parseResult fullPParser lstName contents where fullPParser = try $ parseEmptyLST lstPParser <|> parseFullLST lstPParser -- debugging only prettyPrint :: Show a => PParser (LSTLine a) -> FilePath -> IO String prettyPrint = showAll . parseLST where showAll = ((Pretty.ppShow <$>) .) parseLSTToString :: String -> FilePath -> IO String parseLSTToString "LANGUAGE" = prettyPrint (parseLSTLine :: PParser (LSTLine LanguageDefinition)) parseLSTToString "ARMORPROF" = prettyPrint (parseLSTLine :: PParser (LSTLine ArmorProficency)) parseLSTToString "SHIELDPROF" = prettyPrint (parseLSTLine :: PParser (LSTLine ShieldProficency)) parseLSTToString "WEAPONPROF" = prettyPrint (parseLSTLine :: PParser (LSTLine WeaponProficency)) parseLSTToString "SKILL" = prettyPrint (parseLSTLine :: PParser (LSTLine SkillDefinition)) parseLSTToString "DOMAIN" = prettyPrint (parseLSTLine :: PParser (LSTLine DomainDefinition)) parseLSTToString "DEITY" = prettyPrint (parseLSTLine :: PParser (LSTLine DeityDefinition)) parseLSTToString "SPELL" = prettyPrint (parseLSTLine :: PParser (LSTLine SpellDefinition)) parseLSTToString "FEAT" = prettyPrint (parseLSTLine :: PParser (LSTLine FeatDefinition)) parseLSTToString "EQUIPMENT" = prettyPrint (parseLSTLine :: PParser (LSTLine EquipmentDefinition)) parseLSTToString "EQUIPMOD" = prettyPrint (parseLSTLine :: PParser (LSTLine EquipmentModDefinition)) parseLSTToString "COMPANIONMOD" = prettyPrint (parseLSTLine :: PParser (LSTLine CompanionModDefinition)) parseLSTToString _ = prettyPrint (parseLSTLine :: PParser (LSTLine LSTDefinition))
gamelost/pcgen-rules
src/Lst.hs
apache-2.0
3,852
0
12
582
1,026
546
480
74
1
import System.FilePath (replaceExtension) import System.Directory (doesFileExist, renameDirectory, renameFile)
EricYT/Haskell
src/real_haskell/chapter-8/useful.hs
apache-2.0
111
0
5
8
27
16
11
2
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module YesodDsl.Generator.EsqueletoInstances (esqueletoInstances) where import YesodDsl.AST import qualified Data.Text as T import Text.Shakespeare.Text hiding (toText) import Data.List import YesodDsl.Generator.Esqueleto import Control.Monad.Reader (runReader, liftM) maxInstances :: Module -> Int maxInstances m = safeMaximum $ map sqFieldNumber $ filter isSelectQuery [ hp | r <- modRoutes m, h <- routeHandlers r, hp <- handlerStmts h] where isSelectQuery (Select _) = True isSelectQuery _ = False sqFieldNumber (Select sq) = length $ sqFields sq sqFieldNumber _ = 0 safeMaximum [] = 0 safeMaximum xs = maximum xs genInstance :: Int -> String genInstance fnum = T.unpack $(codegenFile "codegen/sqlselect-instance.cg") where nums = [1..fnum] ifield n = "i" ++ show n ofield n = "o" ++ show n sqlSelectTypeLhs n = "SqlSelect " ++ ifield n ++ " " ++ ofield n sqlSelectCols n = "sqlSelectCols esc " ++ ifield n pairs xs = intercalate ", " $ pairs' xs pairs' :: [String] -> [String] pairs' (x1:x2:xs) = ("(" ++ x1 ++ "," ++ x2 ++ ")"):pairs' xs pairs' (x:_) = [x] pairs' _ = [] esqueletoInstances :: Module -> String esqueletoInstances m = concatMap genInstance [17.. (maxInstances m)]
tlaitinen/yesod-dsl
YesodDsl/Generator/EsqueletoInstances.hs
bsd-2-clause
1,608
0
12
516
459
239
220
35
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Lib.JtagRW ( UsbBlasterState , withUSBBlaster , virAddrWrite, virAddrRead, virAddrOff , virWrite, vdrWrite, vdrWriteRead , toBits, fromBits , flush , readInput , printState ) where import Protolude hiding (get) import qualified Data.ByteString as B import Control.Monad.Trans.State import Control.Lens import LibFtdi (DeviceHandle, ftdiDeInit, ftdiInit, ftdiReadData, ftdiUSBClose, ftdiUSBOpen, ftdiUSBReset, ftdiWriteData, withFtdi) jtagTCK, jtagTMS, jtagTDI, jtagLED, jtagRD :: Word8 --jtagOFF = 0x00 jtagTCK = 0x01 jtagTMS = 0x02 --jtagnCE = 0x04 --jtagnCS = 0x08 jtagTDI = 0x10 jtagLED = 0x20 jtagRD = 0x40 --jtagSHM = 0x80 irAddrVir, irAddrVdr :: Word16 irAddrVir = 0x0E irAddrVdr = 0x0C jtagM0D0R, jtagM0D1R, jtagM1D0R, jtagM1D1R :: [Word8] -- Bit-mode - Two byte codes jtagM0D0R = [ jtagLED .|. jtagRD , jtagLED .|. jtagTCK ] jtagM0D1R = [ jtagLED .|. jtagTDI .|. jtagRD , jtagLED .|. jtagTDI .|. jtagTCK ] jtagM1D0R = [ jtagLED .|. jtagTMS .|. jtagRD , jtagLED .|. jtagTMS .|. jtagTCK ] jtagM1D1R = [ jtagLED .|. jtagTMS .|. jtagTDI .|. jtagRD , jtagLED .|. jtagTMS .|. jtagTDI .|. jtagTCK ] jtagM0D0, jtagM0D1, jtagM1D0, jtagM1D1 :: [Word8] jtagM0D0 = [ jtagLED , jtagLED .|. jtagTCK ] jtagM0D1 = [ jtagLED .|. jtagTDI , jtagLED .|. jtagTDI .|. jtagTCK ] jtagM1D0 = [ jtagLED .|. jtagTMS , jtagLED .|. jtagTMS .|. jtagTCK ] jtagM1D1 = [ jtagLED .|. jtagTMS .|. jtagTDI , jtagLED .|. jtagTMS .|. jtagTDI .|. jtagTCK ] fdtiChunkSize :: Int fdtiChunkSize = 63 -- TAP controller Reset tapResetSeq :: [Word8] tapResetSeq = jtagM1D0 ++ jtagM1D0 ++ jtagM1D0 ++ jtagM1D0 ++ jtagM1D0 -- TAP controller Reset to Idle tapIdleSeq :: [Word8] tapIdleSeq = jtagM0D0 -- TAP controller Idle to Shift_DR tapShiftVDRSeq :: [Word8] tapShiftVDRSeq = jtagM1D0 ++ jtagM0D0 ++ jtagM0D0 -- TAP controller Idle to Shift_IR tapShiftVIRSeq :: [Word8] tapShiftVIRSeq = jtagM1D0 ++ jtagM1D0 ++ jtagM0D0 ++ jtagM0D0 -- TAP controller Exit1 to Idle tapEndSeq :: [Word8] tapEndSeq = jtagM1D0 ++ jtagM0D0 -- tapSelectVIRSeq :: [Word8] -- tapSelectVIRSeq = jtagM0D0 ++ jtagM0D1 ++ jtagM0D1 ++ jtagM0D1 ++ jtagM0D0 ++ -- jtagM0D0 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM1D0 -- -- tapSelectVDRSeq :: [Word8] -- jtagSELECT_VDR = jtagM0D0 ++ jtagM0D0 ++ jtagM0D1 ++ jtagM0D1 ++ jtagM0D0 ++ -- jtagM0D0 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM1D0 -- -- tapNodeShiftInstSeq :: [Word8] -- tapNodeShiftInstSeq = jtagM0D1 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM1D1 -- -- tapNodeUpdateInstSeq :: [Word8] -- tapNodeUpdateInstSeq = jtagM0D0 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM0D0 ++ jtagM1D1 -- -- tapNodeDataSeq :: [Word8] -- tapNodeDataSeq = jtagM0D0 ++ jtagM0D1 ++ jtagM0D1 ++ jtagM0D0 ++ jtagM0D0 ++ -- jtagM0D1 ++ jtagM1D1 revSplitMsb::[Bool] -> Maybe (Bool, [Bool]) revSplitMsb [] = Nothing revSplitMsb (x:xs) = Just (x, reverse xs) mkBytesJtag :: [Word8] -> [Word8] -> [Word8] -> [Word8] -> Maybe (Bool, [Bool]) -> [Word8] mkBytesJtag v0 v1 vm0 vm1 msbBits = case msbBits of Nothing -> [] Just (msb, bits) -> join (fmap (\v -> if v then v1 else v0) bits) ++ if msb then vm1 else vm0 mkJtagWrite:: [Bool] -> [Word8] mkJtagWrite bits = mkBytesJtag jtagM0D0 jtagM0D1 jtagM1D0 jtagM1D1 $ revSplitMsb bits mkJtagWriteRead:: [Bool] -> [Word8] mkJtagWriteRead bits = mkBytesJtag jtagM0D0R jtagM0D1R jtagM1D0R jtagM1D1R $ revSplitMsb bits lsbToBool :: [Word8] -> [Bool] lsbToBool b = fmap (\v -> v .&. 1 /= 0) b -- @todo add Reader data UsbBlasterState = UsbBlasterState { _usblD :: DeviceHandle , _usblOut :: [Word8] , _usblInReq :: Int -- size and callback? array? , _usblRetries :: Int , _usblTimeout :: Int , _usblVirAddrBase :: Word16 , _usblIrAddrLen :: Int , _usblVirAddrLen :: Int } makeLenses ''UsbBlasterState -- @todo better I/F - store all flushed input in state flush :: (StateT UsbBlasterState) IO (Maybe [Bool]) flush = do s <- get _ <- liftIO $ ftdiWriteData (s^.usblD) (B.pack $ s^.usblOut) i <- liftIO $ if s^.usblInReq > 0 then ftdiReadWithTimeout (s^.usblD) "" (s^.usblInReq) (s^.usblRetries) (s^.usblTimeout) else pure $ Just "" usblOut .= [] usblInReq .= 0 return $ lsbToBool . B.unpack <$> i addOutput :: [Word8] -> (StateT UsbBlasterState) IO (Maybe [Bool]) addOutput o = do s <- get if length (s^.usblOut) + length o >= fdtiChunkSize then do f <- flush usblOut .= o return f else do usblOut <>= o return Nothing -- @todo need either for errors readInput :: Int -> (StateT UsbBlasterState) IO (Maybe [Bool]) readInput sz = do s <- get if s^.usblInReq + sz >= fdtiChunkSize then do f <- flush usblInReq .= sz return f else do usblInReq += sz return Nothing withUSBBlaster :: Word16 -> Int -> Int ->(StateT UsbBlasterState) IO (Maybe B.ByteString) -> IO (Maybe [Char]) withUSBBlaster ad irl virl f = do dh <- ftdiInit case dh of Left err -> return $ Just $ "Error:" ++ show err Right _ -> withFtdi ( \d -> do ftdiUSBOpen d (0x09fb, 0x6001) ftdiUSBReset d _ <- tapReset d _ <- runStateT f (UsbBlasterState d [] 0 5 1000 ad irl virl) ftdiUSBClose d ftdiDeInit d return Nothing ) -- @todo cleanup - monad loop ftdiReadWithTimeout :: DeviceHandle -> B.ByteString -> Int -> Int -> Int -> IO (Maybe B.ByteString) ftdiReadWithTimeout d acc left iter delay = if iter == 0 then do pure Nothing else do rd <- ftdiReadData d left case rd of Nothing -> do threadDelay delay ftdiReadWithTimeout d acc left (iter - 1) delay Just r -> let newacc = acc `B.append` r newleft = left - B.length r in if newleft == 0 then pure $ Just newacc else do threadDelay delay ftdiReadWithTimeout d newacc newleft (iter - 1) delay tapReset::DeviceHandle -> IO Int tapReset d = ftdiWriteData d $ B.pack $ tapResetSeq ++ tapIdleSeq toBits :: (Eq a, Num a, Bits a) => Int -> a -> [Bool] toBits 0 _ = [] toBits 1 v = [v .&. 1 /= 0] toBits s v = fmap (\b -> v .&. shift 1 b /= 0) [s - 1, s-2..0] pwr2::[Int] pwr2 = 1 : fmap (2*) pwr2 fromBits::[Bool] -> Int fromBits [] = 0 fromBits x = foldr addPwr 0 $ zip (reverse x) pwr2 where addPwr (b,n) a = if b then a + n else a -- @todo ignored returns, errors irWrite:: [Bool] -> (StateT UsbBlasterState) IO (Maybe B.ByteString) irWrite b = do _ <- addOutput tapShiftVIRSeq _ <- addOutput $ mkJtagWrite b _ <- addOutput tapEndSeq pure $ Just "@TODO fix me" virWrite:: Word8 -> (StateT UsbBlasterState) IO (Maybe B.ByteString) virWrite addr = do -- @todo addr checks? s <- get _ <- irWrite $ toBits (s^.usblIrAddrLen) irAddrVir _ <- addOutput tapShiftVDRSeq -- @todo name!? _ <- addOutput $ mkJtagWrite $ toBits (s^.usblVirAddrLen) $ (s^.usblVirAddrBase) + fromIntegral addr _ <- addOutput tapEndSeq pure $ Just "@TODO fix me" vdrWrite:: [Bool] -> (StateT UsbBlasterState) IO (Maybe B.ByteString) vdrWrite b = do s <- get _ <- irWrite $ toBits (s^.usblIrAddrLen) irAddrVdr _ <- addOutput tapShiftVDRSeq _ <- addOutput $ mkJtagWrite b _ <- addOutput tapEndSeq pure $ Just "@TODO fix me" vdrWriteRead:: [Bool] -> (StateT UsbBlasterState) IO (Maybe B.ByteString) vdrWriteRead b = do s <- get _ <- irWrite $ toBits (s^.usblIrAddrLen) irAddrVdr _ <- addOutput tapShiftVDRSeq _ <- addOutput $ mkJtagWriteRead b _ <- flush -- @todo fix for large input? _ <- readInput $ length b _ <- addOutput tapEndSeq pure $ Just "@TODO fix me" printState :: UsbBlasterState -> IO() printState s = putStrLn $ show (s^.usblOut) ++ ", " ++ show (s^.usblInReq) ++ ", " ++ show (s^.usblInReq) virAddrWrite, virAddrRead, virAddrOff :: Word8 virAddrWrite = 0x02 virAddrRead = 0x01 virAddrOff = 0x00
tau-tao/FPGAIPFilter
src/Lib/JtagRW.hs
bsd-3-clause
8,981
0
19
2,776
2,568
1,354
1,214
207
4
{-# LANGUAGE OverloadedStrings, CPP #-} #if defined(RELOCATE) {-# LANGUAGE TemplateHaskell #-} #endif -- | This module provides some functions to generate HTML reports for -- a Module and its inferred annotations. This module handles the -- extraction of source code (from tarballs/zip files) and mapping -- Functions to their associated source code using various heuristics. -- -- FIXME: The drilldowns for functions may be overwritten by functions -- of the same name... this probably won't be a problem in practice -- since there would be linker errors of that happens. module Foreign.Inference.Report ( -- * Types InterfaceReport, -- * Functions compileDetailedReport, compileSummaryReport, writeHTMLReport, writeHTMLSummary ) where import GHC.Conc ( getNumCapabilities ) import Control.Concurrent.ParallelIO.Local import Data.ByteString.Lazy.Char8 ( ByteString ) import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as M import System.Directory ( createDirectoryIfMissing ) import System.FilePath import Text.Blaze.Html.Renderer.Utf8 ( renderHtml ) import Codec.Archive import LLVM.Analysis import Foreign.Inference.Interface import Foreign.Inference.Report.FunctionText import Foreign.Inference.Report.Html import Foreign.Inference.Report.Types #if defined(RELOCATE) import Data.FileEmbed import qualified Data.ByteString as BS staticFiles :: [(FilePath, BS.ByteString)] staticFiles = $(embedDir "static") -- | Install a file from the project share directory to the target -- report directory (top-level). installStaticFiles :: FilePath -> IO () installStaticFiles dst = do let install (name, content) = BS.writeFile (dst </> name) content mapM_ install staticFiles #else import System.Directory ( copyFile, getDirectoryContents ) import Paths_foreign_inference installStaticFiles :: FilePath -> IO () installStaticFiles dst = do src <- getDataDir files <- getDirectoryContents (src </> "static") let doCopy f = do case f == "." || f == ".." of True -> return () False -> copyFile (src </> "static" </> f) (dst </> f) mapM_ doCopy files #endif -- | Write the given report into the given directory. An index.html file -- will be placed in the directory and subdirectories within that will -- contain the actual content. -- -- An error will be thrown if the given path exists and is not a -- directory. The directory will be created if it does not exist. writeHTMLReport :: InterfaceReport -> FilePath -> IO () writeHTMLReport r dir = do let indexFile = dir </> "index.html" indexPage = htmlIndexPage r [LinkDrilldowns] -- Create the directory tree for the report createDirectoryIfMissing True dir createDirectoryIfMissing True (dir </> "functions") -- Write out an index page LBS.writeFile indexFile (renderHtml indexPage) -- Write out the individual function listings. Since highlighting -- each function is completely independent we run them in parallel -- with as many processors as are available. caps <- getNumCapabilities let bodyPairs = M.toList (reportFunctionBodies r) actions = map (writeFunctionBodyPage r dir) bodyPairs withPool caps $ \p -> parallel_ p actions -- Copy over static resources (like css and js) installStaticFiles dir -- | This is like 'writeHTMLReport', except it only writes out the -- top-level overview HTML page. The per-function breakdowns are not -- generated. writeHTMLSummary :: InterfaceReport -> FilePath -> IO () writeHTMLSummary r dir = do let indexFile = dir </> "index.html" indexPage = htmlIndexPage r [] -- Create the directory tree for the report createDirectoryIfMissing True dir -- Write out an index page LBS.writeFile indexFile (renderHtml indexPage) -- Copy over static resources (like css and js) installStaticFiles dir writeFunctionBodyPage :: InterfaceReport -> FilePath -> (Function, (FilePath, Int, ByteString)) -> IO () writeFunctionBodyPage r dir (f, (srcFile, startLine, body)) = do let funcName = identifierAsString (functionName f) filename = dir </> "functions" </> funcName <.> "html" functionPage = htmlFunctionPage r f srcFile startLine body LBS.writeFile filename (renderHtml functionPage) -- | Given a Module, the properties that have been inferred about it, -- and an archive of its source, make a best-effort to construct an -- informative report of the results. compileDetailedReport :: Module -> ArchiveIndex -> [ModuleSummary] -> DependencySummary -> InterfaceReport compileDetailedReport m a = InterfaceReport m bodies a where fs = moduleDefinedFunctions m bodies = foldr bodyExtractor M.empty fs bodyExtractor f acc = case getFunctionText a f of Nothing -> acc Just b -> M.insert f b acc compileSummaryReport :: Module -> [ModuleSummary] -> DependencySummary -> InterfaceReport compileSummaryReport = InterfaceSummaryReport
travitch/foreign-inference
src/Foreign/Inference/Report.hs
bsd-3-clause
4,994
0
12
937
789
436
353
70
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} module Juno.Consensus.Handle.RequestVoteResponse (handle) where import Control.Lens import Control.Monad.Reader import Control.Monad.State import Control.Monad.Writer.Strict import Data.Map as Map import Data.Set as Set import Juno.Consensus.Handle.Types import Juno.Runtime.Sender (sendAllAppendEntries) import Juno.Runtime.Timer (resetHeartbeatTimer, resetElectionTimerLeader, resetElectionTimer) import Juno.Util.Util import Juno.Types.Log import qualified Juno.Types as JT data RequestVoteResponseEnv = RequestVoteResponseEnv { _nodeRole :: Role , _term :: Term , _lastLogIndex :: LogIndex , _cYesVotes :: Set.Set RequestVoteResponse , _quorumSize :: Int } makeLenses ''RequestVoteResponseEnv data RequestVoteResponseOut = BecomeLeader { _newYesVotes :: Set.Set RequestVoteResponse } | UpdateYesVotes { _newYesVotes :: Set.Set RequestVoteResponse } | DeletePotentialVote { _voteNodeId :: NodeID } | RevertToFollower | NoAction handleRequestVoteResponse :: (MonadReader RequestVoteResponseEnv m, MonadWriter [String] m) => RequestVoteResponse -> m RequestVoteResponseOut handleRequestVoteResponse rvr@RequestVoteResponse{..} = do tell ["got a requestVoteResponse RPC for " ++ show _rvrTerm ++ ": " ++ show _voteGranted] r <- view nodeRole ct <- view term curLog <- view lastLogIndex if r == Candidate && ct == _rvrTerm then if _voteGranted then Set.insert rvr <$> view cYesVotes >>= checkElection else return $ DeletePotentialVote _rvrNodeId else if ct > _rvrTerm && _rvrCurLogIndex > curLog && r == Candidate then do tell ["Log is too out of date to ever become leader, revert to last good state: " ++ show (ct,curLog) ++ " vs " ++ show (_rvrTerm, _rvrCurLogIndex)] return RevertToFollower else tell ["Taking no action on RVR"] >> return NoAction -- count the yes votes and become leader if you have reached a quorum checkElection :: (MonadReader RequestVoteResponseEnv m, MonadWriter [String] m) => Set.Set RequestVoteResponse -> m RequestVoteResponseOut checkElection votes = do let nyes = Set.size votes qsize <- view quorumSize tell ["yes votes: " ++ show nyes ++ " quorum size: " ++ show qsize] if nyes >= qsize then tell ["becoming leader"] >> return (BecomeLeader votes) else return $ UpdateYesVotes votes handle :: Monad m => RequestVoteResponse -> JT.Raft m () handle m = do r <- ask s <- get es <- use JT.logEntries (o,l) <- runReaderT (runWriterT (handleRequestVoteResponse m)) (RequestVoteResponseEnv (JT._nodeRole s) (JT._term s) (maxIndex es) (JT._cYesVotes s) (JT._quorumSize r)) mapM_ debug l case o of BecomeLeader vs -> do JT.cYesVotes .= vs becomeLeader UpdateYesVotes vs -> JT.cYesVotes .= vs DeletePotentialVote n -> JT.cPotentialVotes %= Set.delete n NoAction -> return () RevertToFollower -> revertToLastQuorumState -- THREAD: SERVER MAIN. updates state becomeLeader :: Monad m => JT.Raft m () becomeLeader = do setRole Leader setCurrentLeader . Just =<< view (JT.cfg.JT.nodeId) ni <- entryCount <$> use JT.logEntries setLNextIndex =<< Map.fromSet (const ni) <$> view (JT.cfg.JT.otherNodes) (JT.lMatchIndex .=) =<< Map.fromSet (const startIndex) <$> view (JT.cfg.JT.otherNodes) JT.lConvinced .= Set.empty sendAllAppendEntries resetHeartbeatTimer resetElectionTimerLeader revertToLastQuorumState :: Monad m => JT.Raft m () revertToLastQuorumState = do es <- use JT.logEntries setRole Follower setCurrentLeader Nothing JT.ignoreLeader .= False setTerm (lastLogTerm es) JT.votedFor .= Nothing JT.cYesVotes .= Set.empty JT.cPotentialVotes .= Set.empty resetElectionTimer
haroldcarr/juno
src/Juno/Consensus/Handle/RequestVoteResponse.hs
bsd-3-clause
3,994
3
17
869
1,108
558
550
100
5
{-# LANGUAGE FlexibleInstances , MultiParamTypeClasses , TypeFamilies , Rank2Types , BangPatterns #-} -- | -- Module : Data.Vector -- Copyright : (c) Roman Leshchinskiy 2008-2010 -- License : BSD-style -- -- Maintainer : Roman Leshchinskiy <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- A library for boxed vectors (that is, polymorphic arrays capable of -- holding any Haskell value). The vectors come in two flavours: -- -- * mutable -- -- * immutable -- -- and support a rich interface of both list-like operations, and bulk -- array operations. -- -- For unboxed arrays, use "Data.Vector.Unboxed" -- module Data.Vector ( -- * Boxed vectors Vector, MVector, -- * Accessors -- ** Length information length, null, -- ** Indexing (!), (!?), head, last, unsafeIndex, unsafeHead, unsafeLast, -- ** Monadic indexing indexM, headM, lastM, unsafeIndexM, unsafeHeadM, unsafeLastM, -- ** Extracting subvectors (slicing) slice, init, tail, take, drop, splitAt, unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop, -- * Construction -- ** Initialisation empty, singleton, replicate, generate, iterateN, -- ** Monadic initialisation replicateM, generateM, create, -- ** Unfolding unfoldr, unfoldrN, constructN, constructrN, -- ** Enumeration enumFromN, enumFromStepN, enumFromTo, enumFromThenTo, -- ** Concatenation cons, snoc, (++), concat, -- ** Restricting memory usage force, -- * Modifying vectors -- ** Bulk updates (//), update, update_, unsafeUpd, unsafeUpdate, unsafeUpdate_, -- ** Accumulations accum, accumulate, accumulate_, unsafeAccum, unsafeAccumulate, unsafeAccumulate_, -- ** Permutations reverse, backpermute, unsafeBackpermute, -- ** Safe destructive updates modify, -- * Elementwise operations -- ** Indexing indexed, -- ** Mapping map, imap, concatMap, -- ** Monadic mapping mapM, mapM_, forM, forM_, -- ** Zipping zipWith, zipWith3, zipWith4, zipWith5, zipWith6, izipWith, izipWith3, izipWith4, izipWith5, izipWith6, zip, zip3, zip4, zip5, zip6, -- ** Monadic zipping zipWithM, zipWithM_, -- ** Unzipping unzip, unzip3, unzip4, unzip5, unzip6, -- * Working with predicates -- ** Filtering filter, ifilter, filterM, takeWhile, dropWhile, -- ** Partitioning partition, unstablePartition, span, break, -- ** Searching elem, notElem, find, findIndex, findIndices, elemIndex, elemIndices, -- * Folding foldl, foldl1, foldl', foldl1', foldr, foldr1, foldr', foldr1', ifoldl, ifoldl', ifoldr, ifoldr', -- ** Specialised folds all, any, and, or, sum, product, maximum, maximumBy, minimum, minimumBy, minIndex, minIndexBy, maxIndex, maxIndexBy, -- ** Monadic folds foldM, foldM', fold1M, fold1M', foldM_, foldM'_, fold1M_, fold1M'_, -- ** Monadic sequencing sequence, sequence_, -- * Prefix sums (scans) prescanl, prescanl', postscanl, postscanl', scanl, scanl', scanl1, scanl1', prescanr, prescanr', postscanr, postscanr', scanr, scanr', scanr1, scanr1', -- * Conversions -- ** Lists toList, fromList, fromListN, -- ** Other vector types G.convert, -- ** Mutable vectors freeze, thaw, copy, unsafeFreeze, unsafeThaw, unsafeCopy ) where import qualified Data.Vector.Generic as G import Data.Vector.Mutable ( MVector(..) ) import Data.Primitive.Array import qualified Data.Vector.Fusion.Bundle as Bundle import Control.DeepSeq ( NFData, rnf ) import Control.Monad ( MonadPlus(..), liftM, ap ) import Control.Monad.ST ( ST ) import Control.Monad.Primitive import Prelude hiding ( length, null, replicate, (++), concat, head, last, init, tail, take, drop, splitAt, reverse, map, concatMap, zipWith, zipWith3, zip, zip3, unzip, unzip3, filter, takeWhile, dropWhile, span, break, elem, notElem, foldl, foldl1, foldr, foldr1, all, any, and, or, sum, product, minimum, maximum, scanl, scanl1, scanr, scanr1, enumFromTo, enumFromThenTo, mapM, mapM_, sequence, sequence_ ) import qualified Prelude import Data.Typeable ( Typeable ) import Data.Data ( Data(..) ) import Text.Read ( Read(..), readListPrecDefault ) import Data.Monoid ( Monoid(..) ) import qualified Control.Applicative as Applicative import qualified Data.Foldable as Foldable import qualified Data.Traversable as Traversable -- | Boxed vectors, supporting efficient slicing. data Vector a = Vector {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !(Array a) deriving ( Typeable ) instance NFData a => NFData (Vector a) where rnf (Vector i n arr) = force i where force !ix | ix < n = rnf (indexArray arr ix) `seq` force (ix+1) | otherwise = () instance Show a => Show (Vector a) where showsPrec = G.showsPrec instance Read a => Read (Vector a) where readPrec = G.readPrec readListPrec = readListPrecDefault instance Data a => Data (Vector a) where gfoldl = G.gfoldl toConstr _ = error "toConstr" gunfold _ _ = error "gunfold" dataTypeOf _ = G.mkType "Data.Vector.Vector" dataCast1 = G.dataCast type instance G.Mutable Vector = MVector instance G.Vector Vector a where {-# INLINE basicUnsafeFreeze #-} basicUnsafeFreeze (MVector i n marr) = Vector i n `liftM` unsafeFreezeArray marr {-# INLINE basicUnsafeThaw #-} basicUnsafeThaw (Vector i n arr) = MVector i n `liftM` unsafeThawArray arr {-# INLINE basicLength #-} basicLength (Vector _ n _) = n {-# INLINE basicUnsafeSlice #-} basicUnsafeSlice j n (Vector i _ arr) = Vector (i+j) n arr {-# INLINE basicUnsafeIndexM #-} basicUnsafeIndexM (Vector i _ arr) j = indexArrayM arr (i+j) {-# INLINE basicUnsafeCopy #-} basicUnsafeCopy (MVector i n dst) (Vector j _ src) = copyArray dst i src j n -- See http://trac.haskell.org/vector/ticket/12 instance Eq a => Eq (Vector a) where {-# INLINE (==) #-} xs == ys = Bundle.eq (G.stream xs) (G.stream ys) {-# INLINE (/=) #-} xs /= ys = not (Bundle.eq (G.stream xs) (G.stream ys)) -- See http://trac.haskell.org/vector/ticket/12 instance Ord a => Ord (Vector a) where {-# INLINE compare #-} compare xs ys = Bundle.cmp (G.stream xs) (G.stream ys) {-# INLINE (<) #-} xs < ys = Bundle.cmp (G.stream xs) (G.stream ys) == LT {-# INLINE (<=) #-} xs <= ys = Bundle.cmp (G.stream xs) (G.stream ys) /= GT {-# INLINE (>) #-} xs > ys = Bundle.cmp (G.stream xs) (G.stream ys) == GT {-# INLINE (>=) #-} xs >= ys = Bundle.cmp (G.stream xs) (G.stream ys) /= LT instance Monoid (Vector a) where {-# INLINE mempty #-} mempty = empty {-# INLINE mappend #-} mappend = (++) {-# INLINE mconcat #-} mconcat = concat instance Functor Vector where {-# INLINE fmap #-} fmap = map instance Monad Vector where {-# INLINE return #-} return = singleton {-# INLINE (>>=) #-} (>>=) = flip concatMap instance MonadPlus Vector where {-# INLINE mzero #-} mzero = empty {-# INLINE mplus #-} mplus = (++) instance Applicative.Applicative Vector where {-# INLINE pure #-} pure = singleton {-# INLINE (<*>) #-} (<*>) = ap instance Applicative.Alternative Vector where {-# INLINE empty #-} empty = empty {-# INLINE (<|>) #-} (<|>) = (++) instance Foldable.Foldable Vector where {-# INLINE foldr #-} foldr = foldr {-# INLINE foldl #-} foldl = foldl {-# INLINE foldr1 #-} foldr1 = foldr1 {-# INLINE foldl1 #-} foldl1 = foldl1 instance Traversable.Traversable Vector where {-# INLINE traverse #-} traverse f xs = fromList Applicative.<$> Traversable.traverse f (toList xs) {-# INLINE mapM #-} mapM = mapM {-# INLINE sequence #-} sequence = sequence -- Length information -- ------------------ -- | /O(1)/ Yield the length of the vector. length :: Vector a -> Int {-# INLINE length #-} length = G.length -- | /O(1)/ Test whether a vector if empty null :: Vector a -> Bool {-# INLINE null #-} null = G.null -- Indexing -- -------- -- | O(1) Indexing (!) :: Vector a -> Int -> a {-# INLINE (!) #-} (!) = (G.!) -- | O(1) Safe indexing (!?) :: Vector a -> Int -> Maybe a {-# INLINE (!?) #-} (!?) = (G.!?) -- | /O(1)/ First element head :: Vector a -> a {-# INLINE head #-} head = G.head -- | /O(1)/ Last element last :: Vector a -> a {-# INLINE last #-} last = G.last -- | /O(1)/ Unsafe indexing without bounds checking unsafeIndex :: Vector a -> Int -> a {-# INLINE unsafeIndex #-} unsafeIndex = G.unsafeIndex -- | /O(1)/ First element without checking if the vector is empty unsafeHead :: Vector a -> a {-# INLINE unsafeHead #-} unsafeHead = G.unsafeHead -- | /O(1)/ Last element without checking if the vector is empty unsafeLast :: Vector a -> a {-# INLINE unsafeLast #-} unsafeLast = G.unsafeLast -- Monadic indexing -- ---------------- -- | /O(1)/ Indexing in a monad. -- -- The monad allows operations to be strict in the vector when necessary. -- Suppose vector copying is implemented like this: -- -- > copy mv v = ... write mv i (v ! i) ... -- -- For lazy vectors, @v ! i@ would not be evaluated which means that @mv@ -- would unnecessarily retain a reference to @v@ in each element written. -- -- With 'indexM', copying can be implemented like this instead: -- -- > copy mv v = ... do -- > x <- indexM v i -- > write mv i x -- -- Here, no references to @v@ are retained because indexing (but /not/ the -- elements) is evaluated eagerly. -- indexM :: Monad m => Vector a -> Int -> m a {-# INLINE indexM #-} indexM = G.indexM -- | /O(1)/ First element of a vector in a monad. See 'indexM' for an -- explanation of why this is useful. headM :: Monad m => Vector a -> m a {-# INLINE headM #-} headM = G.headM -- | /O(1)/ Last element of a vector in a monad. See 'indexM' for an -- explanation of why this is useful. lastM :: Monad m => Vector a -> m a {-# INLINE lastM #-} lastM = G.lastM -- | /O(1)/ Indexing in a monad without bounds checks. See 'indexM' for an -- explanation of why this is useful. unsafeIndexM :: Monad m => Vector a -> Int -> m a {-# INLINE unsafeIndexM #-} unsafeIndexM = G.unsafeIndexM -- | /O(1)/ First element in a monad without checking for empty vectors. -- See 'indexM' for an explanation of why this is useful. unsafeHeadM :: Monad m => Vector a -> m a {-# INLINE unsafeHeadM #-} unsafeHeadM = G.unsafeHeadM -- | /O(1)/ Last element in a monad without checking for empty vectors. -- See 'indexM' for an explanation of why this is useful. unsafeLastM :: Monad m => Vector a -> m a {-# INLINE unsafeLastM #-} unsafeLastM = G.unsafeLastM -- Extracting subvectors (slicing) -- ------------------------------- -- | /O(1)/ Yield a slice of the vector without copying it. The vector must -- contain at least @i+n@ elements. slice :: Int -- ^ @i@ starting index -> Int -- ^ @n@ length -> Vector a -> Vector a {-# INLINE slice #-} slice = G.slice -- | /O(1)/ Yield all but the last element without copying. The vector may not -- be empty. init :: Vector a -> Vector a {-# INLINE init #-} init = G.init -- | /O(1)/ Yield all but the first element without copying. The vector may not -- be empty. tail :: Vector a -> Vector a {-# INLINE tail #-} tail = G.tail -- | /O(1)/ Yield at the first @n@ elements without copying. The vector may -- contain less than @n@ elements in which case it is returned unchanged. take :: Int -> Vector a -> Vector a {-# INLINE take #-} take = G.take -- | /O(1)/ Yield all but the first @n@ elements without copying. The vector may -- contain less than @n@ elements in which case an empty vector is returned. drop :: Int -> Vector a -> Vector a {-# INLINE drop #-} drop = G.drop -- | /O(1)/ Yield the first @n@ elements paired with the remainder without copying. -- -- Note that @'splitAt' n v@ is equivalent to @('take' n v, 'drop' n v)@ -- but slightly more efficient. {-# INLINE splitAt #-} splitAt :: Int -> Vector a -> (Vector a, Vector a) splitAt = G.splitAt -- | /O(1)/ Yield a slice of the vector without copying. The vector must -- contain at least @i+n@ elements but this is not checked. unsafeSlice :: Int -- ^ @i@ starting index -> Int -- ^ @n@ length -> Vector a -> Vector a {-# INLINE unsafeSlice #-} unsafeSlice = G.unsafeSlice -- | /O(1)/ Yield all but the last element without copying. The vector may not -- be empty but this is not checked. unsafeInit :: Vector a -> Vector a {-# INLINE unsafeInit #-} unsafeInit = G.unsafeInit -- | /O(1)/ Yield all but the first element without copying. The vector may not -- be empty but this is not checked. unsafeTail :: Vector a -> Vector a {-# INLINE unsafeTail #-} unsafeTail = G.unsafeTail -- | /O(1)/ Yield the first @n@ elements without copying. The vector must -- contain at least @n@ elements but this is not checked. unsafeTake :: Int -> Vector a -> Vector a {-# INLINE unsafeTake #-} unsafeTake = G.unsafeTake -- | /O(1)/ Yield all but the first @n@ elements without copying. The vector -- must contain at least @n@ elements but this is not checked. unsafeDrop :: Int -> Vector a -> Vector a {-# INLINE unsafeDrop #-} unsafeDrop = G.unsafeDrop -- Initialisation -- -------------- -- | /O(1)/ Empty vector empty :: Vector a {-# INLINE empty #-} empty = G.empty -- | /O(1)/ Vector with exactly one element singleton :: a -> Vector a {-# INLINE singleton #-} singleton = G.singleton -- | /O(n)/ Vector of the given length with the same value in each position replicate :: Int -> a -> Vector a {-# INLINE replicate #-} replicate = G.replicate -- | /O(n)/ Construct a vector of the given length by applying the function to -- each index generate :: Int -> (Int -> a) -> Vector a {-# INLINE generate #-} generate = G.generate -- | /O(n)/ Apply function n times to value. Zeroth element is original value. iterateN :: Int -> (a -> a) -> a -> Vector a {-# INLINE iterateN #-} iterateN = G.iterateN -- Unfolding -- --------- -- | /O(n)/ Construct a vector by repeatedly applying the generator function -- to a seed. The generator function yields 'Just' the next element and the -- new seed or 'Nothing' if there are no more elements. -- -- > unfoldr (\n -> if n == 0 then Nothing else Just (n,n-1)) 10 -- > = <10,9,8,7,6,5,4,3,2,1> unfoldr :: (b -> Maybe (a, b)) -> b -> Vector a {-# INLINE unfoldr #-} unfoldr = G.unfoldr -- | /O(n)/ Construct a vector with at most @n@ by repeatedly applying the -- generator function to the a seed. The generator function yields 'Just' the -- next element and the new seed or 'Nothing' if there are no more elements. -- -- > unfoldrN 3 (\n -> Just (n,n-1)) 10 = <10,9,8> unfoldrN :: Int -> (b -> Maybe (a, b)) -> b -> Vector a {-# INLINE unfoldrN #-} unfoldrN = G.unfoldrN -- | /O(n)/ Construct a vector with @n@ elements by repeatedly applying the -- generator function to the already constructed part of the vector. -- -- > constructN 3 f = let a = f <> ; b = f <a> ; c = f <a,b> in f <a,b,c> -- constructN :: Int -> (Vector a -> a) -> Vector a {-# INLINE constructN #-} constructN = G.constructN -- | /O(n)/ Construct a vector with @n@ elements from right to left by -- repeatedly applying the generator function to the already constructed part -- of the vector. -- -- > constructrN 3 f = let a = f <> ; b = f<a> ; c = f <b,a> in f <c,b,a> -- constructrN :: Int -> (Vector a -> a) -> Vector a {-# INLINE constructrN #-} constructrN = G.constructrN -- Enumeration -- ----------- -- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+1@ -- etc. This operation is usually more efficient than 'enumFromTo'. -- -- > enumFromN 5 3 = <5,6,7> enumFromN :: Num a => a -> Int -> Vector a {-# INLINE enumFromN #-} enumFromN = G.enumFromN -- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+y@, -- @x+y+y@ etc. This operations is usually more efficient than 'enumFromThenTo'. -- -- > enumFromStepN 1 0.1 5 = <1,1.1,1.2,1.3,1.4> enumFromStepN :: Num a => a -> a -> Int -> Vector a {-# INLINE enumFromStepN #-} enumFromStepN = G.enumFromStepN -- | /O(n)/ Enumerate values from @x@ to @y@. -- -- /WARNING:/ This operation can be very inefficient. If at all possible, use -- 'enumFromN' instead. enumFromTo :: Enum a => a -> a -> Vector a {-# INLINE enumFromTo #-} enumFromTo = G.enumFromTo -- | /O(n)/ Enumerate values from @x@ to @y@ with a specific step @z@. -- -- /WARNING:/ This operation can be very inefficient. If at all possible, use -- 'enumFromStepN' instead. enumFromThenTo :: Enum a => a -> a -> a -> Vector a {-# INLINE enumFromThenTo #-} enumFromThenTo = G.enumFromThenTo -- Concatenation -- ------------- -- | /O(n)/ Prepend an element cons :: a -> Vector a -> Vector a {-# INLINE cons #-} cons = G.cons -- | /O(n)/ Append an element snoc :: Vector a -> a -> Vector a {-# INLINE snoc #-} snoc = G.snoc infixr 5 ++ -- | /O(m+n)/ Concatenate two vectors (++) :: Vector a -> Vector a -> Vector a {-# INLINE (++) #-} (++) = (G.++) -- | /O(n)/ Concatenate all vectors in the list concat :: [Vector a] -> Vector a {-# INLINE concat #-} concat = G.concat -- Monadic initialisation -- ---------------------- -- | /O(n)/ Execute the monadic action the given number of times and store the -- results in a vector. replicateM :: Monad m => Int -> m a -> m (Vector a) {-# INLINE replicateM #-} replicateM = G.replicateM -- | /O(n)/ Construct a vector of the given length by applying the monadic -- action to each index generateM :: Monad m => Int -> (Int -> m a) -> m (Vector a) {-# INLINE generateM #-} generateM = G.generateM -- | Execute the monadic action and freeze the resulting vector. -- -- @ -- create (do { v \<- new 2; write v 0 \'a\'; write v 1 \'b\'; return v }) = \<'a','b'\> -- @ create :: (forall s. ST s (MVector s a)) -> Vector a {-# INLINE create #-} -- NOTE: eta-expanded due to http://hackage.haskell.org/trac/ghc/ticket/4120 create p = G.create p -- Restricting memory usage -- ------------------------ -- | /O(n)/ Yield the argument but force it not to retain any extra memory, -- possibly by copying it. -- -- This is especially useful when dealing with slices. For example: -- -- > force (slice 0 2 <huge vector>) -- -- Here, the slice retains a reference to the huge vector. Forcing it creates -- a copy of just the elements that belong to the slice and allows the huge -- vector to be garbage collected. force :: Vector a -> Vector a {-# INLINE force #-} force = G.force -- Bulk updates -- ------------ -- | /O(m+n)/ For each pair @(i,a)@ from the list, replace the vector -- element at position @i@ by @a@. -- -- > <5,9,2,7> // [(2,1),(0,3),(2,8)] = <3,9,8,7> -- (//) :: Vector a -- ^ initial vector (of length @m@) -> [(Int, a)] -- ^ list of index/value pairs (of length @n@) -> Vector a {-# INLINE (//) #-} (//) = (G.//) -- | /O(m+n)/ For each pair @(i,a)@ from the vector of index/value pairs, -- replace the vector element at position @i@ by @a@. -- -- > update <5,9,2,7> <(2,1),(0,3),(2,8)> = <3,9,8,7> -- update :: Vector a -- ^ initial vector (of length @m@) -> Vector (Int, a) -- ^ vector of index/value pairs (of length @n@) -> Vector a {-# INLINE update #-} update = G.update -- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the -- corresponding value @a@ from the value vector, replace the element of the -- initial vector at position @i@ by @a@. -- -- > update_ <5,9,2,7> <2,0,2> <1,3,8> = <3,9,8,7> -- -- The function 'update' provides the same functionality and is usually more -- convenient. -- -- @ -- update_ xs is ys = 'update' xs ('zip' is ys) -- @ update_ :: Vector a -- ^ initial vector (of length @m@) -> Vector Int -- ^ index vector (of length @n1@) -> Vector a -- ^ value vector (of length @n2@) -> Vector a {-# INLINE update_ #-} update_ = G.update_ -- | Same as ('//') but without bounds checking. unsafeUpd :: Vector a -> [(Int, a)] -> Vector a {-# INLINE unsafeUpd #-} unsafeUpd = G.unsafeUpd -- | Same as 'update' but without bounds checking. unsafeUpdate :: Vector a -> Vector (Int, a) -> Vector a {-# INLINE unsafeUpdate #-} unsafeUpdate = G.unsafeUpdate -- | Same as 'update_' but without bounds checking. unsafeUpdate_ :: Vector a -> Vector Int -> Vector a -> Vector a {-# INLINE unsafeUpdate_ #-} unsafeUpdate_ = G.unsafeUpdate_ -- Accumulations -- ------------- -- | /O(m+n)/ For each pair @(i,b)@ from the list, replace the vector element -- @a@ at position @i@ by @f a b@. -- -- > accum (+) <5,9,2> [(2,4),(1,6),(0,3),(1,7)] = <5+3, 9+6+7, 2+4> accum :: (a -> b -> a) -- ^ accumulating function @f@ -> Vector a -- ^ initial vector (of length @m@) -> [(Int,b)] -- ^ list of index/value pairs (of length @n@) -> Vector a {-# INLINE accum #-} accum = G.accum -- | /O(m+n)/ For each pair @(i,b)@ from the vector of pairs, replace the vector -- element @a@ at position @i@ by @f a b@. -- -- > accumulate (+) <5,9,2> <(2,4),(1,6),(0,3),(1,7)> = <5+3, 9+6+7, 2+4> accumulate :: (a -> b -> a) -- ^ accumulating function @f@ -> Vector a -- ^ initial vector (of length @m@) -> Vector (Int,b) -- ^ vector of index/value pairs (of length @n@) -> Vector a {-# INLINE accumulate #-} accumulate = G.accumulate -- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the -- corresponding value @b@ from the the value vector, -- replace the element of the initial vector at -- position @i@ by @f a b@. -- -- > accumulate_ (+) <5,9,2> <2,1,0,1> <4,6,3,7> = <5+3, 9+6+7, 2+4> -- -- The function 'accumulate' provides the same functionality and is usually more -- convenient. -- -- @ -- accumulate_ f as is bs = 'accumulate' f as ('zip' is bs) -- @ accumulate_ :: (a -> b -> a) -- ^ accumulating function @f@ -> Vector a -- ^ initial vector (of length @m@) -> Vector Int -- ^ index vector (of length @n1@) -> Vector b -- ^ value vector (of length @n2@) -> Vector a {-# INLINE accumulate_ #-} accumulate_ = G.accumulate_ -- | Same as 'accum' but without bounds checking. unsafeAccum :: (a -> b -> a) -> Vector a -> [(Int,b)] -> Vector a {-# INLINE unsafeAccum #-} unsafeAccum = G.unsafeAccum -- | Same as 'accumulate' but without bounds checking. unsafeAccumulate :: (a -> b -> a) -> Vector a -> Vector (Int,b) -> Vector a {-# INLINE unsafeAccumulate #-} unsafeAccumulate = G.unsafeAccumulate -- | Same as 'accumulate_' but without bounds checking. unsafeAccumulate_ :: (a -> b -> a) -> Vector a -> Vector Int -> Vector b -> Vector a {-# INLINE unsafeAccumulate_ #-} unsafeAccumulate_ = G.unsafeAccumulate_ -- Permutations -- ------------ -- | /O(n)/ Reverse a vector reverse :: Vector a -> Vector a {-# INLINE reverse #-} reverse = G.reverse -- | /O(n)/ Yield the vector obtained by replacing each element @i@ of the -- index vector by @xs'!'i@. This is equivalent to @'map' (xs'!') is@ but is -- often much more efficient. -- -- > backpermute <a,b,c,d> <0,3,2,3,1,0> = <a,d,c,d,b,a> backpermute :: Vector a -> Vector Int -> Vector a {-# INLINE backpermute #-} backpermute = G.backpermute -- | Same as 'backpermute' but without bounds checking. unsafeBackpermute :: Vector a -> Vector Int -> Vector a {-# INLINE unsafeBackpermute #-} unsafeBackpermute = G.unsafeBackpermute -- Safe destructive updates -- ------------------------ -- | Apply a destructive operation to a vector. The operation will be -- performed in place if it is safe to do so and will modify a copy of the -- vector otherwise. -- -- @ -- modify (\\v -> write v 0 \'x\') ('replicate' 3 \'a\') = \<\'x\',\'a\',\'a\'\> -- @ modify :: (forall s. MVector s a -> ST s ()) -> Vector a -> Vector a {-# INLINE modify #-} modify p = G.modify p -- Indexing -- -------- -- | /O(n)/ Pair each element in a vector with its index indexed :: Vector a -> Vector (Int,a) {-# INLINE indexed #-} indexed = G.indexed -- Mapping -- ------- -- | /O(n)/ Map a function over a vector map :: (a -> b) -> Vector a -> Vector b {-# INLINE map #-} map = G.map -- | /O(n)/ Apply a function to every element of a vector and its index imap :: (Int -> a -> b) -> Vector a -> Vector b {-# INLINE imap #-} imap = G.imap -- | Map a function over a vector and concatenate the results. concatMap :: (a -> Vector b) -> Vector a -> Vector b {-# INLINE concatMap #-} concatMap = G.concatMap -- Monadic mapping -- --------------- -- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a -- vector of results mapM :: Monad m => (a -> m b) -> Vector a -> m (Vector b) {-# INLINE mapM #-} mapM = G.mapM -- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the -- results mapM_ :: Monad m => (a -> m b) -> Vector a -> m () {-# INLINE mapM_ #-} mapM_ = G.mapM_ -- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a -- vector of results. Equvalent to @flip 'mapM'@. forM :: Monad m => Vector a -> (a -> m b) -> m (Vector b) {-# INLINE forM #-} forM = G.forM -- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the -- results. Equivalent to @flip 'mapM_'@. forM_ :: Monad m => Vector a -> (a -> m b) -> m () {-# INLINE forM_ #-} forM_ = G.forM_ -- Zipping -- ------- -- | /O(min(m,n))/ Zip two vectors with the given function. zipWith :: (a -> b -> c) -> Vector a -> Vector b -> Vector c {-# INLINE zipWith #-} zipWith = G.zipWith -- | Zip three vectors with the given function. zipWith3 :: (a -> b -> c -> d) -> Vector a -> Vector b -> Vector c -> Vector d {-# INLINE zipWith3 #-} zipWith3 = G.zipWith3 zipWith4 :: (a -> b -> c -> d -> e) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e {-# INLINE zipWith4 #-} zipWith4 = G.zipWith4 zipWith5 :: (a -> b -> c -> d -> e -> f) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector f {-# INLINE zipWith5 #-} zipWith5 = G.zipWith5 zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector f -> Vector g {-# INLINE zipWith6 #-} zipWith6 = G.zipWith6 -- | /O(min(m,n))/ Zip two vectors with a function that also takes the -- elements' indices. izipWith :: (Int -> a -> b -> c) -> Vector a -> Vector b -> Vector c {-# INLINE izipWith #-} izipWith = G.izipWith -- | Zip three vectors and their indices with the given function. izipWith3 :: (Int -> a -> b -> c -> d) -> Vector a -> Vector b -> Vector c -> Vector d {-# INLINE izipWith3 #-} izipWith3 = G.izipWith3 izipWith4 :: (Int -> a -> b -> c -> d -> e) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e {-# INLINE izipWith4 #-} izipWith4 = G.izipWith4 izipWith5 :: (Int -> a -> b -> c -> d -> e -> f) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector f {-# INLINE izipWith5 #-} izipWith5 = G.izipWith5 izipWith6 :: (Int -> a -> b -> c -> d -> e -> f -> g) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector f -> Vector g {-# INLINE izipWith6 #-} izipWith6 = G.izipWith6 -- | Elementwise pairing of array elements. zip :: Vector a -> Vector b -> Vector (a, b) {-# INLINE zip #-} zip = G.zip -- | zip together three vectors into a vector of triples zip3 :: Vector a -> Vector b -> Vector c -> Vector (a, b, c) {-# INLINE zip3 #-} zip3 = G.zip3 zip4 :: Vector a -> Vector b -> Vector c -> Vector d -> Vector (a, b, c, d) {-# INLINE zip4 #-} zip4 = G.zip4 zip5 :: Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector (a, b, c, d, e) {-# INLINE zip5 #-} zip5 = G.zip5 zip6 :: Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector f -> Vector (a, b, c, d, e, f) {-# INLINE zip6 #-} zip6 = G.zip6 -- Unzipping -- --------- -- | /O(min(m,n))/ Unzip a vector of pairs. unzip :: Vector (a, b) -> (Vector a, Vector b) {-# INLINE unzip #-} unzip = G.unzip unzip3 :: Vector (a, b, c) -> (Vector a, Vector b, Vector c) {-# INLINE unzip3 #-} unzip3 = G.unzip3 unzip4 :: Vector (a, b, c, d) -> (Vector a, Vector b, Vector c, Vector d) {-# INLINE unzip4 #-} unzip4 = G.unzip4 unzip5 :: Vector (a, b, c, d, e) -> (Vector a, Vector b, Vector c, Vector d, Vector e) {-# INLINE unzip5 #-} unzip5 = G.unzip5 unzip6 :: Vector (a, b, c, d, e, f) -> (Vector a, Vector b, Vector c, Vector d, Vector e, Vector f) {-# INLINE unzip6 #-} unzip6 = G.unzip6 -- Monadic zipping -- --------------- -- | /O(min(m,n))/ Zip the two vectors with the monadic action and yield a -- vector of results zipWithM :: Monad m => (a -> b -> m c) -> Vector a -> Vector b -> m (Vector c) {-# INLINE zipWithM #-} zipWithM = G.zipWithM -- | /O(min(m,n))/ Zip the two vectors with the monadic action and ignore the -- results zipWithM_ :: Monad m => (a -> b -> m c) -> Vector a -> Vector b -> m () {-# INLINE zipWithM_ #-} zipWithM_ = G.zipWithM_ -- Filtering -- --------- -- | /O(n)/ Drop elements that do not satisfy the predicate filter :: (a -> Bool) -> Vector a -> Vector a {-# INLINE filter #-} filter = G.filter -- | /O(n)/ Drop elements that do not satisfy the predicate which is applied to -- values and their indices ifilter :: (Int -> a -> Bool) -> Vector a -> Vector a {-# INLINE ifilter #-} ifilter = G.ifilter -- | /O(n)/ Drop elements that do not satisfy the monadic predicate filterM :: Monad m => (a -> m Bool) -> Vector a -> m (Vector a) {-# INLINE filterM #-} filterM = G.filterM -- | /O(n)/ Yield the longest prefix of elements satisfying the predicate -- without copying. takeWhile :: (a -> Bool) -> Vector a -> Vector a {-# INLINE takeWhile #-} takeWhile = G.takeWhile -- | /O(n)/ Drop the longest prefix of elements that satisfy the predicate -- without copying. dropWhile :: (a -> Bool) -> Vector a -> Vector a {-# INLINE dropWhile #-} dropWhile = G.dropWhile -- Parititioning -- ------------- -- | /O(n)/ Split the vector in two parts, the first one containing those -- elements that satisfy the predicate and the second one those that don't. The -- relative order of the elements is preserved at the cost of a sometimes -- reduced performance compared to 'unstablePartition'. partition :: (a -> Bool) -> Vector a -> (Vector a, Vector a) {-# INLINE partition #-} partition = G.partition -- | /O(n)/ Split the vector in two parts, the first one containing those -- elements that satisfy the predicate and the second one those that don't. -- The order of the elements is not preserved but the operation is often -- faster than 'partition'. unstablePartition :: (a -> Bool) -> Vector a -> (Vector a, Vector a) {-# INLINE unstablePartition #-} unstablePartition = G.unstablePartition -- | /O(n)/ Split the vector into the longest prefix of elements that satisfy -- the predicate and the rest without copying. span :: (a -> Bool) -> Vector a -> (Vector a, Vector a) {-# INLINE span #-} span = G.span -- | /O(n)/ Split the vector into the longest prefix of elements that do not -- satisfy the predicate and the rest without copying. break :: (a -> Bool) -> Vector a -> (Vector a, Vector a) {-# INLINE break #-} break = G.break -- Searching -- --------- infix 4 `elem` -- | /O(n)/ Check if the vector contains an element elem :: Eq a => a -> Vector a -> Bool {-# INLINE elem #-} elem = G.elem infix 4 `notElem` -- | /O(n)/ Check if the vector does not contain an element (inverse of 'elem') notElem :: Eq a => a -> Vector a -> Bool {-# INLINE notElem #-} notElem = G.notElem -- | /O(n)/ Yield 'Just' the first element matching the predicate or 'Nothing' -- if no such element exists. find :: (a -> Bool) -> Vector a -> Maybe a {-# INLINE find #-} find = G.find -- | /O(n)/ Yield 'Just' the index of the first element matching the predicate -- or 'Nothing' if no such element exists. findIndex :: (a -> Bool) -> Vector a -> Maybe Int {-# INLINE findIndex #-} findIndex = G.findIndex -- | /O(n)/ Yield the indices of elements satisfying the predicate in ascending -- order. findIndices :: (a -> Bool) -> Vector a -> Vector Int {-# INLINE findIndices #-} findIndices = G.findIndices -- | /O(n)/ Yield 'Just' the index of the first occurence of the given element or -- 'Nothing' if the vector does not contain the element. This is a specialised -- version of 'findIndex'. elemIndex :: Eq a => a -> Vector a -> Maybe Int {-# INLINE elemIndex #-} elemIndex = G.elemIndex -- | /O(n)/ Yield the indices of all occurences of the given element in -- ascending order. This is a specialised version of 'findIndices'. elemIndices :: Eq a => a -> Vector a -> Vector Int {-# INLINE elemIndices #-} elemIndices = G.elemIndices -- Folding -- ------- -- | /O(n)/ Left fold foldl :: (a -> b -> a) -> a -> Vector b -> a {-# INLINE foldl #-} foldl = G.foldl -- | /O(n)/ Left fold on non-empty vectors foldl1 :: (a -> a -> a) -> Vector a -> a {-# INLINE foldl1 #-} foldl1 = G.foldl1 -- | /O(n)/ Left fold with strict accumulator foldl' :: (a -> b -> a) -> a -> Vector b -> a {-# INLINE foldl' #-} foldl' = G.foldl' -- | /O(n)/ Left fold on non-empty vectors with strict accumulator foldl1' :: (a -> a -> a) -> Vector a -> a {-# INLINE foldl1' #-} foldl1' = G.foldl1' -- | /O(n)/ Right fold foldr :: (a -> b -> b) -> b -> Vector a -> b {-# INLINE foldr #-} foldr = G.foldr -- | /O(n)/ Right fold on non-empty vectors foldr1 :: (a -> a -> a) -> Vector a -> a {-# INLINE foldr1 #-} foldr1 = G.foldr1 -- | /O(n)/ Right fold with a strict accumulator foldr' :: (a -> b -> b) -> b -> Vector a -> b {-# INLINE foldr' #-} foldr' = G.foldr' -- | /O(n)/ Right fold on non-empty vectors with strict accumulator foldr1' :: (a -> a -> a) -> Vector a -> a {-# INLINE foldr1' #-} foldr1' = G.foldr1' -- | /O(n)/ Left fold (function applied to each element and its index) ifoldl :: (a -> Int -> b -> a) -> a -> Vector b -> a {-# INLINE ifoldl #-} ifoldl = G.ifoldl -- | /O(n)/ Left fold with strict accumulator (function applied to each element -- and its index) ifoldl' :: (a -> Int -> b -> a) -> a -> Vector b -> a {-# INLINE ifoldl' #-} ifoldl' = G.ifoldl' -- | /O(n)/ Right fold (function applied to each element and its index) ifoldr :: (Int -> a -> b -> b) -> b -> Vector a -> b {-# INLINE ifoldr #-} ifoldr = G.ifoldr -- | /O(n)/ Right fold with strict accumulator (function applied to each -- element and its index) ifoldr' :: (Int -> a -> b -> b) -> b -> Vector a -> b {-# INLINE ifoldr' #-} ifoldr' = G.ifoldr' -- Specialised folds -- ----------------- -- | /O(n)/ Check if all elements satisfy the predicate. all :: (a -> Bool) -> Vector a -> Bool {-# INLINE all #-} all = G.all -- | /O(n)/ Check if any element satisfies the predicate. any :: (a -> Bool) -> Vector a -> Bool {-# INLINE any #-} any = G.any -- | /O(n)/ Check if all elements are 'True' and :: Vector Bool -> Bool {-# INLINE and #-} and = G.and -- | /O(n)/ Check if any element is 'True' or :: Vector Bool -> Bool {-# INLINE or #-} or = G.or -- | /O(n)/ Compute the sum of the elements sum :: Num a => Vector a -> a {-# INLINE sum #-} sum = G.sum -- | /O(n)/ Compute the produce of the elements product :: Num a => Vector a -> a {-# INLINE product #-} product = G.product -- | /O(n)/ Yield the maximum element of the vector. The vector may not be -- empty. maximum :: Ord a => Vector a -> a {-# INLINE maximum #-} maximum = G.maximum -- | /O(n)/ Yield the maximum element of the vector according to the given -- comparison function. The vector may not be empty. maximumBy :: (a -> a -> Ordering) -> Vector a -> a {-# INLINE maximumBy #-} maximumBy = G.maximumBy -- | /O(n)/ Yield the minimum element of the vector. The vector may not be -- empty. minimum :: Ord a => Vector a -> a {-# INLINE minimum #-} minimum = G.minimum -- | /O(n)/ Yield the minimum element of the vector according to the given -- comparison function. The vector may not be empty. minimumBy :: (a -> a -> Ordering) -> Vector a -> a {-# INLINE minimumBy #-} minimumBy = G.minimumBy -- | /O(n)/ Yield the index of the maximum element of the vector. The vector -- may not be empty. maxIndex :: Ord a => Vector a -> Int {-# INLINE maxIndex #-} maxIndex = G.maxIndex -- | /O(n)/ Yield the index of the maximum element of the vector according to -- the given comparison function. The vector may not be empty. maxIndexBy :: (a -> a -> Ordering) -> Vector a -> Int {-# INLINE maxIndexBy #-} maxIndexBy = G.maxIndexBy -- | /O(n)/ Yield the index of the minimum element of the vector. The vector -- may not be empty. minIndex :: Ord a => Vector a -> Int {-# INLINE minIndex #-} minIndex = G.minIndex -- | /O(n)/ Yield the index of the minimum element of the vector according to -- the given comparison function. The vector may not be empty. minIndexBy :: (a -> a -> Ordering) -> Vector a -> Int {-# INLINE minIndexBy #-} minIndexBy = G.minIndexBy -- Monadic folds -- ------------- -- | /O(n)/ Monadic fold foldM :: Monad m => (a -> b -> m a) -> a -> Vector b -> m a {-# INLINE foldM #-} foldM = G.foldM -- | /O(n)/ Monadic fold over non-empty vectors fold1M :: Monad m => (a -> a -> m a) -> Vector a -> m a {-# INLINE fold1M #-} fold1M = G.fold1M -- | /O(n)/ Monadic fold with strict accumulator foldM' :: Monad m => (a -> b -> m a) -> a -> Vector b -> m a {-# INLINE foldM' #-} foldM' = G.foldM' -- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator fold1M' :: Monad m => (a -> a -> m a) -> Vector a -> m a {-# INLINE fold1M' #-} fold1M' = G.fold1M' -- | /O(n)/ Monadic fold that discards the result foldM_ :: Monad m => (a -> b -> m a) -> a -> Vector b -> m () {-# INLINE foldM_ #-} foldM_ = G.foldM_ -- | /O(n)/ Monadic fold over non-empty vectors that discards the result fold1M_ :: Monad m => (a -> a -> m a) -> Vector a -> m () {-# INLINE fold1M_ #-} fold1M_ = G.fold1M_ -- | /O(n)/ Monadic fold with strict accumulator that discards the result foldM'_ :: Monad m => (a -> b -> m a) -> a -> Vector b -> m () {-# INLINE foldM'_ #-} foldM'_ = G.foldM'_ -- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator -- that discards the result fold1M'_ :: Monad m => (a -> a -> m a) -> Vector a -> m () {-# INLINE fold1M'_ #-} fold1M'_ = G.fold1M'_ -- Monadic sequencing -- ------------------ -- | Evaluate each action and collect the results sequence :: Monad m => Vector (m a) -> m (Vector a) {-# INLINE sequence #-} sequence = G.sequence -- | Evaluate each action and discard the results sequence_ :: Monad m => Vector (m a) -> m () {-# INLINE sequence_ #-} sequence_ = G.sequence_ -- Prefix sums (scans) -- ------------------- -- | /O(n)/ Prescan -- -- @ -- prescanl f z = 'init' . 'scanl' f z -- @ -- -- Example: @prescanl (+) 0 \<1,2,3,4\> = \<0,1,3,6\>@ -- prescanl :: (a -> b -> a) -> a -> Vector b -> Vector a {-# INLINE prescanl #-} prescanl = G.prescanl -- | /O(n)/ Prescan with strict accumulator prescanl' :: (a -> b -> a) -> a -> Vector b -> Vector a {-# INLINE prescanl' #-} prescanl' = G.prescanl' -- | /O(n)/ Scan -- -- @ -- postscanl f z = 'tail' . 'scanl' f z -- @ -- -- Example: @postscanl (+) 0 \<1,2,3,4\> = \<1,3,6,10\>@ -- postscanl :: (a -> b -> a) -> a -> Vector b -> Vector a {-# INLINE postscanl #-} postscanl = G.postscanl -- | /O(n)/ Scan with strict accumulator postscanl' :: (a -> b -> a) -> a -> Vector b -> Vector a {-# INLINE postscanl' #-} postscanl' = G.postscanl' -- | /O(n)/ Haskell-style scan -- -- > scanl f z <x1,...,xn> = <y1,...,y(n+1)> -- > where y1 = z -- > yi = f y(i-1) x(i-1) -- -- Example: @scanl (+) 0 \<1,2,3,4\> = \<0,1,3,6,10\>@ -- scanl :: (a -> b -> a) -> a -> Vector b -> Vector a {-# INLINE scanl #-} scanl = G.scanl -- | /O(n)/ Haskell-style scan with strict accumulator scanl' :: (a -> b -> a) -> a -> Vector b -> Vector a {-# INLINE scanl' #-} scanl' = G.scanl' -- | /O(n)/ Scan over a non-empty vector -- -- > scanl f <x1,...,xn> = <y1,...,yn> -- > where y1 = x1 -- > yi = f y(i-1) xi -- scanl1 :: (a -> a -> a) -> Vector a -> Vector a {-# INLINE scanl1 #-} scanl1 = G.scanl1 -- | /O(n)/ Scan over a non-empty vector with a strict accumulator scanl1' :: (a -> a -> a) -> Vector a -> Vector a {-# INLINE scanl1' #-} scanl1' = G.scanl1' -- | /O(n)/ Right-to-left prescan -- -- @ -- prescanr f z = 'reverse' . 'prescanl' (flip f) z . 'reverse' -- @ -- prescanr :: (a -> b -> b) -> b -> Vector a -> Vector b {-# INLINE prescanr #-} prescanr = G.prescanr -- | /O(n)/ Right-to-left prescan with strict accumulator prescanr' :: (a -> b -> b) -> b -> Vector a -> Vector b {-# INLINE prescanr' #-} prescanr' = G.prescanr' -- | /O(n)/ Right-to-left scan postscanr :: (a -> b -> b) -> b -> Vector a -> Vector b {-# INLINE postscanr #-} postscanr = G.postscanr -- | /O(n)/ Right-to-left scan with strict accumulator postscanr' :: (a -> b -> b) -> b -> Vector a -> Vector b {-# INLINE postscanr' #-} postscanr' = G.postscanr' -- | /O(n)/ Right-to-left Haskell-style scan scanr :: (a -> b -> b) -> b -> Vector a -> Vector b {-# INLINE scanr #-} scanr = G.scanr -- | /O(n)/ Right-to-left Haskell-style scan with strict accumulator scanr' :: (a -> b -> b) -> b -> Vector a -> Vector b {-# INLINE scanr' #-} scanr' = G.scanr' -- | /O(n)/ Right-to-left scan over a non-empty vector scanr1 :: (a -> a -> a) -> Vector a -> Vector a {-# INLINE scanr1 #-} scanr1 = G.scanr1 -- | /O(n)/ Right-to-left scan over a non-empty vector with a strict -- accumulator scanr1' :: (a -> a -> a) -> Vector a -> Vector a {-# INLINE scanr1' #-} scanr1' = G.scanr1' -- Conversions - Lists -- ------------------------ -- | /O(n)/ Convert a vector to a list toList :: Vector a -> [a] {-# INLINE toList #-} toList = G.toList -- | /O(n)/ Convert a list to a vector fromList :: [a] -> Vector a {-# INLINE fromList #-} fromList = G.fromList -- | /O(n)/ Convert the first @n@ elements of a list to a vector -- -- @ -- fromListN n xs = 'fromList' ('take' n xs) -- @ fromListN :: Int -> [a] -> Vector a {-# INLINE fromListN #-} fromListN = G.fromListN -- Conversions - Mutable vectors -- ----------------------------- -- | /O(1)/ Unsafe convert a mutable vector to an immutable one without -- copying. The mutable vector may not be used after this operation. unsafeFreeze :: PrimMonad m => MVector (PrimState m) a -> m (Vector a) {-# INLINE unsafeFreeze #-} unsafeFreeze = G.unsafeFreeze -- | /O(1)/ Unsafely convert an immutable vector to a mutable one without -- copying. The immutable vector may not be used after this operation. unsafeThaw :: PrimMonad m => Vector a -> m (MVector (PrimState m) a) {-# INLINE unsafeThaw #-} unsafeThaw = G.unsafeThaw -- | /O(n)/ Yield a mutable copy of the immutable vector. thaw :: PrimMonad m => Vector a -> m (MVector (PrimState m) a) {-# INLINE thaw #-} thaw = G.thaw -- | /O(n)/ Yield an immutable copy of the mutable vector. freeze :: PrimMonad m => MVector (PrimState m) a -> m (Vector a) {-# INLINE freeze #-} freeze = G.freeze -- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must -- have the same length. This is not checked. unsafeCopy :: PrimMonad m => MVector (PrimState m) a -> Vector a -> m () {-# INLINE unsafeCopy #-} unsafeCopy = G.unsafeCopy -- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must -- have the same length. copy :: PrimMonad m => MVector (PrimState m) a -> Vector a -> m () {-# INLINE copy #-} copy = G.copy
rleshchinskiy/vector
Data/Vector.hs
bsd-3-clause
43,687
0
13
9,514
9,119
5,127
3,992
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module Benchmarks.RegExp where import Data.Data import Data.Typeable (<==>) :: Bool -> Bool -> Bool a <==> b = a == b -- --------------------- data Nat = Zer | Suc Nat deriving (Eq, Show, Data, Typeable) sub :: Nat -> Nat -> Nat sub x y = case y of Zer -> x Suc y' -> case x of Zer -> Zer Suc x' -> sub x' y' data Sym = N0 | N1 Sym deriving (Eq, Show, Data, Typeable) data RE = Sym Sym | Or RE RE | Seq RE RE | And RE RE | Star RE | Empty deriving (Eq, Show, Data, Typeable) accepts :: RE -> [Sym] -> Bool accepts re ss = case re of Sym n -> case ss of [] -> False (n':ss') -> n == n' && null ss' Or re1 re2 -> accepts re1 ss || accepts re2 ss Seq re1 re2 -> seqSplit re1 re2 [] ss And re1 re2 -> accepts re1 ss && accepts re2 ss Star re' -> case ss of [] -> True (s:ss') -> seqSplit re' re (s:[]) ss' -- accepts Empty ss || accepts (Seq re' re) ss Empty -> null ss seqSplit :: RE -> RE -> [Sym] -> [Sym] -> Bool seqSplit re1 re2 ss2 ss = seqSplit'' re1 re2 ss2 ss || seqSplit' re1 re2 ss2 ss seqSplit'' :: RE -> RE -> [Sym] -> [Sym] -> Bool seqSplit'' re1 re2 ss2 ss = accepts re1 ss2 && accepts re2 ss seqSplit' :: RE -> RE -> [Sym] -> [Sym] -> Bool seqSplit' re1 re2 ss2 ss = case ss of [] -> False (n:ss') -> seqSplit re1 re2 (ss2 ++ [n]) ss' rep :: Nat -> RE -> RE rep n re = case n of Zer -> Empty Suc n' -> Seq re (rep n' re) repMax :: Nat -> RE -> RE repMax n re = case n of Zer -> Empty Suc n' -> Or (rep n re) (repMax n' re) repInt' :: Nat -> Nat -> RE -> RE repInt' n k re = case k of Zer -> rep n re Suc k' -> Or (rep n re) (repInt' (Suc n) k' re) repInt :: Nat -> Nat -> RE -> RE repInt n k re = repInt' n (sub k n) re -- Properties prop_regex :: (Nat, Nat, RE, RE, [Sym]) -> Bool prop_regex (n, k, p, q, s) = r where r = (accepts (repInt n k (And p q)) s) <==> (accepts (And (repInt n k p) (repInt n k q)) s) --(accepts (And (repInt n k p) (repInt n k q)) s) <==> (accepts (repInt n k (And p q)) s)^M a_sol = (Zer, Suc (Suc Zer), Sym N0, Seq (Sym N0) (Sym N0), [N0, N0])
UoYCS-plasma/LazySmallCheck2012
suite/performance/Benchmarks/RegExp.hs
bsd-3-clause
2,184
0
14
632
1,069
552
517
72
8
{- (c) The AQUA Project, Glasgow University, 1993-1998 \section[SimplUtils]{The simplifier utilities} -} {-# LANGUAGE CPP #-} module SimplUtils ( -- Rebuilding mkLam, mkCase, prepareAlts, tryEtaExpandRhs, -- Inlining, preInlineUnconditionally, postInlineUnconditionally, activeUnfolding, activeRule, getUnfoldingInRuleMatch, simplEnvForGHCi, updModeForStableUnfoldings, updModeForRules, -- The continuation type SimplCont(..), DupFlag(..), isSimplified, contIsDupable, contResultType, contHoleType, contIsTrivial, contArgs, countArgs, mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg, interestingCallContext, -- ArgInfo ArgInfo(..), ArgSpec(..), mkArgInfo, addValArgTo, addCastTo, addTyArgTo, argInfoExpr, argInfoAppArgs, pushSimplifiedArgs, abstractFloats ) where #include "HsVersions.h" import SimplEnv import CoreMonad ( SimplifierMode(..), Tick(..) ) import DynFlags import CoreSyn import qualified CoreSubst import PprCore import CoreFVs import CoreUtils import CoreArity import CoreUnfold import Name import Id import Var import Demand import SimplMonad import Type hiding( substTy ) import Coercion hiding( substCo ) import DataCon ( dataConWorkId ) import VarEnv import VarSet import BasicTypes import Util import MonadUtils import Outputable import Pair import PrelRules import Literal import Control.Monad ( when ) {- ************************************************************************ * * The SimplCont and DupFlag types * * ************************************************************************ A SimplCont allows the simplifier to traverse the expression in a zipper-like fashion. The SimplCont represents the rest of the expression, "above" the point of interest. You can also think of a SimplCont as an "evaluation context", using that term in the way it is used for operational semantics. This is the way I usually think of it, For example you'll often see a syntax for evaluation context looking like C ::= [] | C e | case C of alts | C `cast` co That's the kind of thing we are doing here, and I use that syntax in the comments. Key points: * A SimplCont describes a *strict* context (just like evaluation contexts do). E.g. Just [] is not a SimplCont * A SimplCont describes a context that *does not* bind any variables. E.g. \x. [] is not a SimplCont -} data SimplCont = Stop -- An empty context, or <hole> OutType -- Type of the <hole> CallCtxt -- Tells if there is something interesting about -- the context, and hence the inliner -- should be a bit keener (see interestingCallContext) -- Specifically: -- This is an argument of a function that has RULES -- Inlining the call might allow the rule to fire -- Never ValAppCxt (use ApplyToVal instead) -- or CaseCtxt (use Select instead) | CastIt -- <hole> `cast` co OutCoercion -- The coercion simplified -- Invariant: never an identity coercion SimplCont | ApplyToVal { -- <hole> arg sc_dup :: DupFlag, -- See Note [DupFlag invariants] sc_arg :: InExpr, -- The argument, sc_env :: StaticEnv, -- and its static env sc_cont :: SimplCont } | ApplyToTy { -- <hole> ty sc_arg_ty :: OutType, -- Argument type sc_hole_ty :: OutType, -- Type of the function, presumably (forall a. blah) -- See Note [The hole type in ApplyToTy] sc_cont :: SimplCont } | Select { -- case <hole> of alts sc_dup :: DupFlag, -- See Note [DupFlag invariants] sc_bndr :: InId, -- case binder sc_alts :: [InAlt], -- Alternatives sc_env :: StaticEnv, -- and their static environment sc_cont :: SimplCont } -- The two strict forms have no DupFlag, because we never duplicate them | StrictBind -- (\x* \xs. e) <hole> InId [InBndr] -- let x* = <hole> in e InExpr StaticEnv -- is a special case SimplCont | StrictArg -- f e1 ..en <hole> ArgInfo -- Specifies f, e1..en, Whether f has rules, etc -- plus strictness flags for *further* args CallCtxt -- Whether *this* argument position is interesting SimplCont | TickIt (Tickish Id) -- Tick tickish <hole> SimplCont data DupFlag = NoDup -- Unsimplified, might be big | Simplified -- Simplified | OkToDup -- Simplified and small isSimplified :: DupFlag -> Bool isSimplified NoDup = False isSimplified _ = True -- Invariant: the subst-env is empty perhapsSubstTy :: DupFlag -> StaticEnv -> Type -> Type perhapsSubstTy dup env ty | isSimplified dup = ty | otherwise = substTy env ty {- Note [DupFlag invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~ In both (ApplyToVal dup _ env k) and (Select dup _ _ env k) the following invariants hold (a) if dup = OkToDup, then continuation k is also ok-to-dup (b) if dup = OkToDup or Simplified, the subst-env is empty (and and hence no need to re-simplify) -} instance Outputable DupFlag where ppr OkToDup = text "ok" ppr NoDup = text "nodup" ppr Simplified = text "simpl" instance Outputable SimplCont where ppr (Stop ty interesting) = text "Stop" <> brackets (ppr interesting) <+> ppr ty ppr (CastIt co cont ) = (text "CastIt" <+> ppr co) $$ ppr cont ppr (TickIt t cont) = (text "TickIt" <+> ppr t) $$ ppr cont ppr (ApplyToTy { sc_arg_ty = ty, sc_cont = cont }) = (text "ApplyToTy" <+> pprParendType ty) $$ ppr cont ppr (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_cont = cont }) = (text "ApplyToVal" <+> ppr dup <+> pprParendExpr arg) $$ ppr cont ppr (StrictBind b _ _ _ cont) = (text "StrictBind" <+> ppr b) $$ ppr cont ppr (StrictArg ai _ cont) = (text "StrictArg" <+> ppr (ai_fun ai)) $$ ppr cont ppr (Select { sc_dup = dup, sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = cont }) = (text "Select" <+> ppr dup <+> ppr bndr) $$ ifPprDebug (nest 2 $ vcat [ppr (seTvSubst se), ppr alts]) $$ ppr cont {- Note [The hole type in ApplyToTy] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The sc_hole_ty field of ApplyToTy records the type of the "hole" in the continuation. It is absolutely necessary to compute contHoleType, but it is not used for anything else (and hence may not be evaluated). Why is it necessary for contHoleType? Consider the continuation ApplyToType Int (Stop Int) corresponding to (<hole> @Int) :: Int What is the type of <hole>? It could be (forall a. Int) or (forall a. a), and there is no way to know which, so we must record it. In a chain of applications (f @t1 @t2 @t3) we'll lazily compute exprType for (f @t1) and (f @t1 @t2), which is potentially non-linear; but it probably doesn't matter because we'll never compute them all. ************************************************************************ * * ArgInfo and ArgSpec * * ************************************************************************ -} data ArgInfo = ArgInfo { ai_fun :: OutId, -- The function ai_args :: [ArgSpec], -- ...applied to these args (which are in *reverse* order) ai_type :: OutType, -- Type of (f a1 ... an) ai_rules :: [CoreRule], -- Rules for this function ai_encl :: Bool, -- Flag saying whether this function -- or an enclosing one has rules (recursively) -- True => be keener to inline in all args ai_strs :: [Bool], -- Strictness of remaining arguments -- Usually infinite, but if it is finite it guarantees -- that the function diverges after being given -- that number of args ai_discs :: [Int] -- Discounts for remaining arguments; non-zero => be keener to inline -- Always infinite } data ArgSpec = ValArg OutExpr -- Apply to this (coercion or value); c.f. ApplyToVal | TyArg { as_arg_ty :: OutType -- Apply to this type; c.f. ApplyToTy , as_hole_ty :: OutType } -- Type of the function (presumably forall a. blah) | CastBy OutCoercion -- Cast by this; c.f. CastIt instance Outputable ArgSpec where ppr (ValArg e) = text "ValArg" <+> ppr e ppr (TyArg { as_arg_ty = ty }) = text "TyArg" <+> ppr ty ppr (CastBy c) = text "CastBy" <+> ppr c addValArgTo :: ArgInfo -> OutExpr -> ArgInfo addValArgTo ai arg = ai { ai_args = ValArg arg : ai_args ai , ai_type = applyTypeToArg (ai_type ai) arg } addTyArgTo :: ArgInfo -> OutType -> ArgInfo addTyArgTo ai arg_ty = ai { ai_args = arg_spec : ai_args ai , ai_type = piResultTy poly_fun_ty arg_ty } where poly_fun_ty = ai_type ai arg_spec = TyArg { as_arg_ty = arg_ty, as_hole_ty = poly_fun_ty } addCastTo :: ArgInfo -> OutCoercion -> ArgInfo addCastTo ai co = ai { ai_args = CastBy co : ai_args ai , ai_type = pSnd (coercionKind co) } argInfoAppArgs :: [ArgSpec] -> [OutExpr] argInfoAppArgs [] = [] argInfoAppArgs (CastBy {} : _) = [] -- Stop at a cast argInfoAppArgs (ValArg e : as) = e : argInfoAppArgs as argInfoAppArgs (TyArg { as_arg_ty = ty } : as) = Type ty : argInfoAppArgs as pushSimplifiedArgs :: SimplEnv -> [ArgSpec] -> SimplCont -> SimplCont pushSimplifiedArgs _env [] k = k pushSimplifiedArgs env (arg : args) k = case arg of TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } -> ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = rest } ValArg e -> ApplyToVal { sc_arg = e, sc_env = env, sc_dup = Simplified, sc_cont = rest } CastBy c -> CastIt c rest where rest = pushSimplifiedArgs env args k -- The env has an empty SubstEnv argInfoExpr :: OutId -> [ArgSpec] -> OutExpr -- NB: the [ArgSpec] is reversed so that the first arg -- in the list is the last one in the application argInfoExpr fun rev_args = go rev_args where go [] = Var fun go (ValArg a : as) = go as `App` a go (TyArg { as_arg_ty = ty } : as) = go as `App` Type ty go (CastBy co : as) = mkCast (go as) co {- ************************************************************************ * * Functions on SimplCont * * ************************************************************************ -} mkBoringStop :: OutType -> SimplCont mkBoringStop ty = Stop ty BoringCtxt mkRhsStop :: OutType -> SimplCont -- See Note [RHS of lets] in CoreUnfold mkRhsStop ty = Stop ty RhsCtxt mkLazyArgStop :: OutType -> CallCtxt -> SimplCont mkLazyArgStop ty cci = Stop ty cci ------------------- contIsRhsOrArg :: SimplCont -> Bool contIsRhsOrArg (Stop {}) = True contIsRhsOrArg (StrictBind {}) = True contIsRhsOrArg (StrictArg {}) = True contIsRhsOrArg _ = False contIsRhs :: SimplCont -> Bool contIsRhs (Stop _ RhsCtxt) = True contIsRhs _ = False ------------------- contIsDupable :: SimplCont -> Bool contIsDupable (Stop {}) = True contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k contIsDupable (ApplyToVal { sc_dup = OkToDup }) = True -- See Note [DupFlag invariants] contIsDupable (Select { sc_dup = OkToDup }) = True -- ...ditto... contIsDupable (CastIt _ k) = contIsDupable k contIsDupable _ = False ------------------- contIsTrivial :: SimplCont -> Bool contIsTrivial (Stop {}) = True contIsTrivial (ApplyToTy { sc_cont = k }) = contIsTrivial k contIsTrivial (ApplyToVal { sc_arg = Coercion _, sc_cont = k }) = contIsTrivial k contIsTrivial (CastIt _ k) = contIsTrivial k contIsTrivial _ = False ------------------- contResultType :: SimplCont -> OutType contResultType (Stop ty _) = ty contResultType (CastIt _ k) = contResultType k contResultType (StrictBind _ _ _ _ k) = contResultType k contResultType (StrictArg _ _ k) = contResultType k contResultType (Select { sc_cont = k }) = contResultType k contResultType (ApplyToTy { sc_cont = k }) = contResultType k contResultType (ApplyToVal { sc_cont = k }) = contResultType k contResultType (TickIt _ k) = contResultType k contHoleType :: SimplCont -> OutType contHoleType (Stop ty _) = ty contHoleType (TickIt _ k) = contHoleType k contHoleType (CastIt co _) = pFst (coercionKind co) contHoleType (StrictBind b _ _ se _) = substTy se (idType b) contHoleType (StrictArg ai _ _) = funArgTy (ai_type ai) contHoleType (ApplyToTy { sc_hole_ty = ty }) = ty -- See Note [The hole type in ApplyToTy] contHoleType (ApplyToVal { sc_arg = e, sc_env = se, sc_dup = dup, sc_cont = k }) = mkFunTy (perhapsSubstTy dup se (exprType e)) (contHoleType k) contHoleType (Select { sc_dup = d, sc_bndr = b, sc_env = se }) = perhapsSubstTy d se (idType b) ------------------- countArgs :: SimplCont -> Int -- Count all arguments, including types, coercions, and other values countArgs (ApplyToTy { sc_cont = cont }) = 1 + countArgs cont countArgs (ApplyToVal { sc_cont = cont }) = 1 + countArgs cont countArgs _ = 0 contArgs :: SimplCont -> (Bool, [ArgSummary], SimplCont) -- Summarises value args, discards type args and coercions -- The returned continuation of the call is only used to -- answer questions like "are you interesting?" contArgs cont | lone cont = (True, [], cont) | otherwise = go [] cont where lone (ApplyToTy {}) = False -- See Note [Lone variables] in CoreUnfold lone (ApplyToVal {}) = False lone (CastIt {}) = False lone _ = True go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k }) = go (is_interesting arg se : args) k go args (ApplyToTy { sc_cont = k }) = go args k go args (CastIt _ k) = go args k go args k = (False, reverse args, k) is_interesting arg se = interestingArg se arg -- Do *not* use short-cutting substitution here -- because we want to get as much IdInfo as possible ------------------- mkArgInfo :: Id -> [CoreRule] -- Rules for function -> Int -- Number of value args -> SimplCont -- Context of the call -> ArgInfo mkArgInfo fun rules n_val_args call_cont | n_val_args < idArity fun -- Note [Unsaturated functions] = ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty , ai_rules = rules, ai_encl = False , ai_strs = vanilla_stricts , ai_discs = vanilla_discounts } | otherwise = ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty , ai_rules = rules , ai_encl = interestingArgContext rules call_cont , ai_strs = add_type_str fun_ty arg_stricts , ai_discs = arg_discounts } where fun_ty = idType fun vanilla_discounts, arg_discounts :: [Int] vanilla_discounts = repeat 0 arg_discounts = case idUnfolding fun of CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}} -> discounts ++ vanilla_discounts _ -> vanilla_discounts vanilla_stricts, arg_stricts :: [Bool] vanilla_stricts = repeat False arg_stricts = case splitStrictSig (idStrictness fun) of (demands, result_info) | not (demands `lengthExceeds` n_val_args) -> -- Enough args, use the strictness given. -- For bottoming functions we used to pretend that the arg -- is lazy, so that we don't treat the arg as an -- interesting context. This avoids substituting -- top-level bindings for (say) strings into -- calls to error. But now we are more careful about -- inlining lone variables, so its ok (see SimplUtils.analyseCont) if isBotRes result_info then map isStrictDmd demands -- Finite => result is bottom else map isStrictDmd demands ++ vanilla_stricts | otherwise -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun) <+> ppr n_val_args <+> ppr demands ) vanilla_stricts -- Not enough args, or no strictness add_type_str :: Type -> [Bool] -> [Bool] -- If the function arg types are strict, record that in the 'strictness bits' -- No need to instantiate because unboxed types (which dominate the strict -- types) can't instantiate type variables. -- add_type_str is done repeatedly (for each call); might be better -- once-for-all in the function -- But beware primops/datacons with no strictness add_type_str _ [] = [] add_type_str fun_ty strs -- Look through foralls | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions = add_type_str fun_ty' strs add_type_str fun_ty (str:strs) -- Add strict-type info | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty = (str || isStrictType arg_ty) : add_type_str fun_ty' strs add_type_str _ strs = strs {- Note [Unsaturated functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (test eyeball/inline4) x = a:as y = f x where f has arity 2. Then we do not want to inline 'x', because it'll just be floated out again. Even if f has lots of discounts on its first argument -- it must be saturated for these to kick in -} {- ************************************************************************ * * Interesting arguments * * ************************************************************************ Note [Interesting call context] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to avoid inlining an expression where there can't possibly be any gain, such as in an argument position. Hence, if the continuation is interesting (eg. a case scrutinee, application etc.) then we inline, otherwise we don't. Previously some_benefit used to return True only if the variable was applied to some value arguments. This didn't work: let x = _coerce_ (T Int) Int (I# 3) in case _coerce_ Int (T Int) x of I# y -> .... we want to inline x, but can't see that it's a constructor in a case scrutinee position, and some_benefit is False. Another example: dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t) .... case dMonadST _@_ x0 of (a,b,c) -> .... we'd really like to inline dMonadST here, but we *don't* want to inline if the case expression is just case x of y { DEFAULT -> ... } since we can just eliminate this case instead (x is in WHNF). Similar applies when x is bound to a lambda expression. Hence contIsInteresting looks for case expressions with just a single default case. -} interestingCallContext :: SimplCont -> CallCtxt -- See Note [Interesting call context] interestingCallContext cont = interesting cont where interesting (Select {}) = CaseCtxt interesting (ApplyToVal {}) = ValAppCtxt -- Can happen if we have (f Int |> co) y -- If f has an INLINE prag we need to give it some -- motivation to inline. See Note [Cast then apply] -- in CoreUnfold interesting (StrictArg _ cci _) = cci interesting (StrictBind {}) = BoringCtxt interesting (Stop _ cci) = cci interesting (TickIt _ k) = interesting k interesting (ApplyToTy { sc_cont = k }) = interesting k interesting (CastIt _ k) = interesting k -- If this call is the arg of a strict function, the context -- is a bit interesting. If we inline here, we may get useful -- evaluation information to avoid repeated evals: e.g. -- x + (y * z) -- Here the contIsInteresting makes the '*' keener to inline, -- which in turn exposes a constructor which makes the '+' inline. -- Assuming that +,* aren't small enough to inline regardless. -- -- It's also very important to inline in a strict context for things -- like -- foldr k z (f x) -- Here, the context of (f x) is strict, and if f's unfolding is -- a build it's *great* to inline it here. So we must ensure that -- the context for (f x) is not totally uninteresting. interestingArgContext :: [CoreRule] -> SimplCont -> Bool -- If the argument has form (f x y), where x,y are boring, -- and f is marked INLINE, then we don't want to inline f. -- But if the context of the argument is -- g (f x y) -- where g has rules, then we *do* want to inline f, in case it -- exposes a rule that might fire. Similarly, if the context is -- h (g (f x x)) -- where h has rules, then we do want to inline f; hence the -- call_cont argument to interestingArgContext -- -- The ai-rules flag makes this happen; if it's -- set, the inliner gets just enough keener to inline f -- regardless of how boring f's arguments are, if it's marked INLINE -- -- The alternative would be to *always* inline an INLINE function, -- regardless of how boring its context is; but that seems overkill -- For example, it'd mean that wrapper functions were always inlined -- -- The call_cont passed to interestingArgContext is the context of -- the call itself, e.g. g <hole> in the example above interestingArgContext rules call_cont = notNull rules || enclosing_fn_has_rules where enclosing_fn_has_rules = go call_cont go (Select {}) = False go (ApplyToVal {}) = False -- Shouldn't really happen go (ApplyToTy {}) = False -- Ditto go (StrictArg _ cci _) = interesting cci go (StrictBind {}) = False -- ?? go (CastIt _ c) = go c go (Stop _ cci) = interesting cci go (TickIt _ c) = go c interesting RuleArgCtxt = True interesting _ = False {- Note [Interesting arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An argument is interesting if it deserves a discount for unfoldings with a discount in that argument position. The idea is to avoid unfolding a function that is applied only to variables that have no unfolding (i.e. they are probably lambda bound): f x y z There is little point in inlining f here. Generally, *values* (like (C a b) and (\x.e)) deserve discounts. But we must look through lets, eg (let x = e in C a b), because the let will float, exposing the value, if we inline. That makes it different to exprIsHNF. Before 2009 we said it was interesting if the argument had *any* structure at all; i.e. (hasSomeUnfolding v). But does too much inlining; see Trac #3016. But we don't regard (f x y) as interesting, unless f is unsaturated. If it's saturated and f hasn't inlined, then it's probably not going to now! Note [Conlike is interesting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f d = ...((*) d x y)... ... f (df d')... where df is con-like. Then we'd really like to inline 'f' so that the rule for (*) (df d) can fire. To do this a) we give a discount for being an argument of a class-op (eg (*) d) b) we say that a con-like argument (eg (df d)) is interesting -} interestingArg :: SimplEnv -> CoreExpr -> ArgSummary -- See Note [Interesting arguments] interestingArg env e = go env 0 e where -- n is # value args to which the expression is applied go env n (Var v) | SimplEnv { seIdSubst = ids, seInScope = in_scope } <- env = case lookupVarEnv ids v of Nothing -> go_var n (refineFromInScope in_scope v) Just (DoneId v') -> go_var n (refineFromInScope in_scope v') Just (DoneEx e) -> go (zapSubstEnv env) n e Just (ContEx tvs cvs ids e) -> go (setSubstEnv env tvs cvs ids) n e go _ _ (Lit {}) = ValueArg go _ _ (Type _) = TrivArg go _ _ (Coercion _) = TrivArg go env n (App fn (Type _)) = go env n fn go env n (App fn _) = go env (n+1) fn go env n (Tick _ a) = go env n a go env n (Cast e _) = go env n e go env n (Lam v e) | isTyVar v = go env n e | n>0 = NonTrivArg -- (\x.b) e is NonTriv | otherwise = ValueArg go _ _ (Case {}) = NonTrivArg go env n (Let b e) = case go env' n e of ValueArg -> ValueArg _ -> NonTrivArg where env' = env `addNewInScopeIds` bindersOf b go_var n v | isConLikeId v = ValueArg -- Experimenting with 'conlike' rather that -- data constructors here | idArity v > n = ValueArg -- Catches (eg) primops with arity but no unfolding | n > 0 = NonTrivArg -- Saturated or unknown call | conlike_unfolding = ValueArg -- n==0; look for an interesting unfolding -- See Note [Conlike is interesting] | otherwise = TrivArg -- n==0, no useful unfolding where conlike_unfolding = isConLikeUnfolding (idUnfolding v) {- ************************************************************************ * * SimplifierMode * * ************************************************************************ The SimplifierMode controls several switches; see its definition in CoreMonad sm_rules :: Bool -- Whether RULES are enabled sm_inline :: Bool -- Whether inlining is enabled sm_case_case :: Bool -- Whether case-of-case is enabled sm_eta_expand :: Bool -- Whether eta-expansion is enabled -} simplEnvForGHCi :: DynFlags -> SimplEnv simplEnvForGHCi dflags = mkSimplEnv $ SimplMode { sm_names = ["GHCi"] , sm_phase = InitialPhase , sm_rules = rules_on , sm_inline = False , sm_eta_expand = eta_expand_on , sm_case_case = True } where rules_on = gopt Opt_EnableRewriteRules dflags eta_expand_on = gopt Opt_DoLambdaEtaExpansion dflags -- Do not do any inlining, in case we expose some unboxed -- tuple stuff that confuses the bytecode interpreter updModeForStableUnfoldings :: Activation -> SimplifierMode -> SimplifierMode -- See Note [Simplifying inside stable unfoldings] updModeForStableUnfoldings inline_rule_act current_mode = current_mode { sm_phase = phaseFromActivation inline_rule_act , sm_inline = True , sm_eta_expand = False } -- sm_eta_expand: see Note [No eta expansion in stable unfoldings] -- For sm_rules, just inherit; sm_rules might be "off" -- because of -fno-enable-rewrite-rules where phaseFromActivation (ActiveAfter _ n) = Phase n phaseFromActivation _ = InitialPhase updModeForRules :: SimplifierMode -> SimplifierMode -- See Note [Simplifying rules] updModeForRules current_mode = current_mode { sm_phase = InitialPhase , sm_inline = False , sm_rules = False , sm_eta_expand = False } {- Note [Simplifying rules] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When simplifying a rule, refrain from any inlining or applying of other RULES. Doing anything to the LHS is plain confusing, because it means that what the rule matches is not what the user wrote. c.f. Trac #10595, and #10528. Moreover, inlining (or applying rules) on rule LHSs risks introducing Ticks into the LHS, which makes matching trickier. Trac #10665, #10745. Doing this to either side confounds tools like HERMIT, which seek to reason about and apply the RULES as originally written. See Trac #10829. Note [No eta expansion in stable unfoldings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we have a stable unfolding f :: Ord a => a -> IO () -- Unfolding template -- = /\a \(d:Ord a) (x:a). bla we do not want to eta-expand to f :: Ord a => a -> IO () -- Unfolding template -- = (/\a \(d:Ord a) (x:a) (eta:State#). bla eta) |> co because not specialisation of the overloading doesn't work properly (see Note [Specialisation shape] in Specialise), Trac #9509. So we disable eta-expansion in stable unfoldings. Note [Inlining in gentle mode] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Something is inlined if (i) the sm_inline flag is on, AND (ii) the thing has an INLINE pragma, AND (iii) the thing is inlinable in the earliest phase. Example of why (iii) is important: {-# INLINE [~1] g #-} g = ... {-# INLINE f #-} f x = g (g x) If we were to inline g into f's inlining, then an importing module would never be able to do f e --> g (g e) ---> RULE fires because the stable unfolding for f has had g inlined into it. On the other hand, it is bad not to do ANY inlining into an stable unfolding, because then recursive knots in instance declarations don't get unravelled. However, *sometimes* SimplGently must do no call-site inlining at all (hence sm_inline = False). Before full laziness we must be careful not to inline wrappers, because doing so inhibits floating e.g. ...(case f x of ...)... ==> ...(case (case x of I# x# -> fw x#) of ...)... ==> ...(case x of I# x# -> case fw x# of ...)... and now the redex (f x) isn't floatable any more. The no-inlining thing is also important for Template Haskell. You might be compiling in one-shot mode with -O2; but when TH compiles a splice before running it, we don't want to use -O2. Indeed, we don't want to inline anything, because the byte-code interpreter might get confused about unboxed tuples and suchlike. Note [Simplifying inside stable unfoldings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We must take care with simplification inside stable unfoldings (which come from INLINE pragmas). First, consider the following example let f = \pq -> BIG in let g = \y -> f y y {-# INLINE g #-} in ...g...g...g...g...g... Now, if that's the ONLY occurrence of f, it might be inlined inside g, and thence copied multiple times when g is inlined. HENCE we treat any occurrence in a stable unfolding as a multiple occurrence, not a single one; see OccurAnal.addRuleUsage. Second, we do want *do* to some modest rules/inlining stuff in stable unfoldings, partly to eliminate senseless crap, and partly to break the recursive knots generated by instance declarations. However, suppose we have {-# INLINE <act> f #-} f = <rhs> meaning "inline f in phases p where activation <act>(p) holds". Then what inlinings/rules can we apply to the copy of <rhs> captured in f's stable unfolding? Our model is that literally <rhs> is substituted for f when it is inlined. So our conservative plan (implemented by updModeForStableUnfoldings) is this: ------------------------------------------------------------- When simplifying the RHS of an stable unfolding, set the phase to the phase in which the stable unfolding first becomes active ------------------------------------------------------------- That ensures that a) Rules/inlinings that *cease* being active before p will not apply to the stable unfolding, consistent with it being inlined in its *original* form in phase p. b) Rules/inlinings that only become active *after* p will not apply to the stable unfolding, again to be consistent with inlining the *original* rhs in phase p. For example, {-# INLINE f #-} f x = ...g... {-# NOINLINE [1] g #-} g y = ... {-# RULE h g = ... #-} Here we must not inline g into f's RHS, even when we get to phase 0, because when f is later inlined into some other module we want the rule for h to fire. Similarly, consider {-# INLINE f #-} f x = ...g... g y = ... and suppose that there are auto-generated specialisations and a strictness wrapper for g. The specialisations get activation AlwaysActive, and the strictness wrapper get activation (ActiveAfter 0). So the strictness wrepper fails the test and won't be inlined into f's stable unfolding. That means f can inline, expose the specialised call to g, so the specialisation rules can fire. A note about wrappers ~~~~~~~~~~~~~~~~~~~~~ It's also important not to inline a worker back into a wrapper. A wrapper looks like wraper = inline_me (\x -> ...worker... ) Normally, the inline_me prevents the worker getting inlined into the wrapper (initially, the worker's only call site!). But, if the wrapper is sure to be called, the strictness analyser will mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf continuation. -} activeUnfolding :: SimplEnv -> Id -> Bool activeUnfolding env | not (sm_inline mode) = active_unfolding_minimal | otherwise = case sm_phase mode of InitialPhase -> active_unfolding_gentle Phase n -> active_unfolding n where mode = getMode env getUnfoldingInRuleMatch :: SimplEnv -> InScopeEnv -- When matching in RULE, we want to "look through" an unfolding -- (to see a constructor) if *rules* are on, even if *inlinings* -- are not. A notable example is DFuns, which really we want to -- match in rules like (op dfun) in gentle mode. Another example -- is 'otherwise' which we want exprIsConApp_maybe to be able to -- see very early on getUnfoldingInRuleMatch env = (in_scope, id_unf) where in_scope = seInScope env mode = getMode env id_unf id | unf_is_active id = idUnfolding id | otherwise = NoUnfolding unf_is_active id | not (sm_rules mode) = active_unfolding_minimal id | otherwise = isActive (sm_phase mode) (idInlineActivation id) active_unfolding_minimal :: Id -> Bool -- Compuslory unfoldings only -- Ignore SimplGently, because we want to inline regardless; -- the Id has no top-level binding at all -- -- NB: we used to have a second exception, for data con wrappers. -- On the grounds that we use gentle mode for rule LHSs, and -- they match better when data con wrappers are inlined. -- But that only really applies to the trivial wrappers (like (:)), -- and they are now constructed as Compulsory unfoldings (in MkId) -- so they'll happen anyway. active_unfolding_minimal id = isCompulsoryUnfolding (realIdUnfolding id) active_unfolding :: PhaseNum -> Id -> Bool active_unfolding n id = isActiveIn n (idInlineActivation id) active_unfolding_gentle :: Id -> Bool -- Anything that is early-active -- See Note [Gentle mode] active_unfolding_gentle id = isInlinePragma prag && isEarlyActive (inlinePragmaActivation prag) -- NB: wrappers are not early-active where prag = idInlinePragma id ---------------------- activeRule :: SimplEnv -> Activation -> Bool -- Nothing => No rules at all activeRule env | not (sm_rules mode) = \_ -> False -- Rewriting is off | otherwise = isActive (sm_phase mode) where mode = getMode env {- ************************************************************************ * * preInlineUnconditionally * * ************************************************************************ preInlineUnconditionally ~~~~~~~~~~~~~~~~~~~~~~~~ @preInlineUnconditionally@ examines a bndr to see if it is used just once in a completely safe way, so that it is safe to discard the binding inline its RHS at the (unique) usage site, REGARDLESS of how big the RHS might be. If this is the case we don't simplify the RHS first, but just inline it un-simplified. This is much better than first simplifying a perhaps-huge RHS and then inlining and re-simplifying it. Indeed, it can be at least quadratically better. Consider x1 = e1 x2 = e2[x1] x3 = e3[x2] ...etc... xN = eN[xN-1] We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc. This can happen with cascades of functions too: f1 = \x1.e1 f2 = \xs.e2[f1] f3 = \xs.e3[f3] ...etc... THE MAIN INVARIANT is this: ---- preInlineUnconditionally invariant ----- IF preInlineUnconditionally chooses to inline x = <rhs> THEN doing the inlining should not change the occurrence info for the free vars of <rhs> ---------------------------------------------- For example, it's tempting to look at trivial binding like x = y and inline it unconditionally. But suppose x is used many times, but this is the unique occurrence of y. Then inlining x would change y's occurrence info, which breaks the invariant. It matters: y might have a BIG rhs, which will now be dup'd at every occurrenc of x. Even RHSs labelled InlineMe aren't caught here, because there might be no benefit from inlining at the call site. [Sept 01] Don't unconditionally inline a top-level thing, because that can simply make a static thing into something built dynamically. E.g. x = (a,b) main = \s -> h x [Remember that we treat \s as a one-shot lambda.] No point in inlining x unless there is something interesting about the call site. But watch out: if you aren't careful, some useful foldr/build fusion can be lost (most notably in spectral/hartel/parstof) because the foldr didn't see the build. Doing the dynamic allocation isn't a big deal, in fact, but losing the fusion can be. But the right thing here seems to be to do a callSiteInline based on the fact that there is something interesting about the call site (it's strict). Hmm. That seems a bit fragile. Conclusion: inline top level things gaily until Phase 0 (the last phase), at which point don't. Note [pre/postInlineUnconditionally in gentle mode] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even in gentle mode we want to do preInlineUnconditionally. The reason is that too little clean-up happens if you don't inline use-once things. Also a bit of inlining is *good* for full laziness; it can expose constant sub-expressions. Example in spectral/mandel/Mandel.hs, where the mandelset function gets a useful let-float if you inline windowToViewport However, as usual for Gentle mode, do not inline things that are inactive in the intial stages. See Note [Gentle mode]. Note [Stable unfoldings and preInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Surprisingly, do not pre-inline-unconditionally Ids with INLINE pragmas! Example {-# INLINE f #-} f :: Eq a => a -> a f x = ... fInt :: Int -> Int fInt = f Int dEqInt ...fInt...fInt...fInt... Here f occurs just once, in the RHS of fInt. But if we inline it there we'll lose the opportunity to inline at each of fInt's call sites. The INLINE pragma will only inline when the application is saturated for exactly this reason; and we don't want PreInlineUnconditionally to second-guess it. A live example is Trac #3736. c.f. Note [Stable unfoldings and postInlineUnconditionally] Note [Top-level bottoming Ids] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Don't inline top-level Ids that are bottoming, even if they are used just once, because FloatOut has gone to some trouble to extract them out. Inlining them won't make the program run faster! Note [Do not inline CoVars unconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Coercion variables appear inside coercions, and the RHS of a let-binding is a term (not a coercion) so we can't necessarily inline the latter in the former. -} preInlineUnconditionally :: DynFlags -> SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool -- Precondition: rhs satisfies the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn -- Reason: we don't want to inline single uses, or discard dead bindings, -- for unlifted, side-effect-ful bindings preInlineUnconditionally dflags env top_lvl bndr rhs | not active = False | isStableUnfolding (idUnfolding bndr) = False -- Note [Stable unfoldings and preInlineUnconditionally] | isTopLevel top_lvl && isBottomingId bndr = False -- Note [Top-level bottoming Ids] | not (gopt Opt_SimplPreInlining dflags) = False | isCoVar bndr = False -- Note [Do not inline CoVars unconditionally] | otherwise = case idOccInfo bndr of IAmDead -> True -- Happens in ((\x.1) v) OneOcc in_lam True int_cxt -> try_once in_lam int_cxt _ -> False where mode = getMode env active = isActive (sm_phase mode) act -- See Note [pre/postInlineUnconditionally in gentle mode] act = idInlineActivation bndr try_once in_lam int_cxt -- There's one textual occurrence | not in_lam = isNotTopLevel top_lvl || early_phase | otherwise = int_cxt && canInlineInLam rhs -- Be very careful before inlining inside a lambda, because (a) we must not -- invalidate occurrence information, and (b) we want to avoid pushing a -- single allocation (here) into multiple allocations (inside lambda). -- Inlining a *function* with a single *saturated* call would be ok, mind you. -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok) -- where -- is_cheap = exprIsCheap rhs -- ok = is_cheap && int_cxt -- int_cxt The context isn't totally boring -- E.g. let f = \ab.BIG in \y. map f xs -- Don't want to substitute for f, because then we allocate -- its closure every time the \y is called -- But: let f = \ab.BIG in \y. map (f y) xs -- Now we do want to substitute for f, even though it's not -- saturated, because we're going to allocate a closure for -- (f y) every time round the loop anyhow. -- canInlineInLam => free vars of rhs are (Once in_lam) or Many, -- so substituting rhs inside a lambda doesn't change the occ info. -- Sadly, not quite the same as exprIsHNF. canInlineInLam (Lit _) = True canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e canInlineInLam _ = False -- not ticks. Counting ticks cannot be duplicated, and non-counting -- ticks around a Lam will disappear anyway. early_phase = case sm_phase mode of Phase 0 -> False _ -> True -- If we don't have this early_phase test, consider -- x = length [1,2,3] -- The full laziness pass carefully floats all the cons cells to -- top level, and preInlineUnconditionally floats them all back in. -- Result is (a) static allocation replaced by dynamic allocation -- (b) many simplifier iterations because this tickles -- a related problem; only one inlining per pass -- -- On the other hand, I have seen cases where top-level fusion is -- lost if we don't inline top level thing (e.g. string constants) -- Hence the test for phase zero (which is the phase for all the final -- simplifications). Until phase zero we take no special notice of -- top level things, but then we become more leery about inlining -- them. {- ************************************************************************ * * postInlineUnconditionally * * ************************************************************************ postInlineUnconditionally ~~~~~~~~~~~~~~~~~~~~~~~~~ @postInlineUnconditionally@ decides whether to unconditionally inline a thing based on the form of its RHS; in particular if it has a trivial RHS. If so, we can inline and discard the binding altogether. NB: a loop breaker has must_keep_binding = True and non-loop-breakers only have *forward* references. Hence, it's safe to discard the binding NOTE: This isn't our last opportunity to inline. We're at the binding site right now, and we'll get another opportunity when we get to the ocurrence(s) Note that we do this unconditional inlining only for trival RHSs. Don't inline even WHNFs inside lambdas; doing so may simply increase allocation when the function is called. This isn't the last chance; see NOTE above. NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why? Because we don't even want to inline them into the RHS of constructor arguments. See NOTE above NB: At one time even NOINLINE was ignored here: if the rhs is trivial it's best to inline it anyway. We often get a=E; b=a from desugaring, with both a and b marked NOINLINE. But that seems incompatible with our new view that inlining is like a RULE, so I'm sticking to the 'active' story for now. -} postInlineUnconditionally :: DynFlags -> SimplEnv -> TopLevelFlag -> OutId -- The binder (an InId would be fine too) -- (*not* a CoVar) -> OccInfo -- From the InId -> OutExpr -> Unfolding -> Bool -- Precondition: rhs satisfies the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn -- Reason: we don't want to inline single uses, or discard dead bindings, -- for unlifted, side-effect-ful bindings postInlineUnconditionally dflags env top_lvl bndr occ_info rhs unfolding | not active = False | isWeakLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline -- because it might be referred to "earlier" | isExportedId bndr = False | isStableUnfolding unfolding = False -- Note [Stable unfoldings and postInlineUnconditionally] | isTopLevel top_lvl = False -- Note [Top level and postInlineUnconditionally] | exprIsTrivial rhs = True | otherwise = case occ_info of -- The point of examining occ_info here is that for *non-values* -- that occur outside a lambda, the call-site inliner won't have -- a chance (because it doesn't know that the thing -- only occurs once). The pre-inliner won't have gotten -- it either, if the thing occurs in more than one branch -- So the main target is things like -- let x = f y in -- case v of -- True -> case x of ... -- False -> case x of ... -- This is very important in practice; e.g. wheel-seive1 doubles -- in allocation if you miss this out OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue -> smallEnoughToInline dflags unfolding -- Small enough to dup -- ToDo: consider discount on smallEnoughToInline if int_cxt is true -- -- NB: Do NOT inline arbitrarily big things, even if one_br is True -- Reason: doing so risks exponential behaviour. We simplify a big -- expression, inline it, and simplify it again. But if the -- very same thing happens in the big expression, we get -- exponential cost! -- PRINCIPLE: when we've already simplified an expression once, -- make sure that we only inline it if it's reasonably small. && (not in_lam || -- Outside a lambda, we want to be reasonably aggressive -- about inlining into multiple branches of case -- e.g. let x = <non-value> -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } -- Inlining can be a big win if C3 is the hot-spot, even if -- the uses in C1, C2 are not 'interesting' -- An example that gets worse if you add int_cxt here is 'clausify' (isCheapUnfolding unfolding && int_cxt)) -- isCheap => acceptable work duplication; in_lam may be true -- int_cxt to prevent us inlining inside a lambda without some -- good reason. See the notes on int_cxt in preInlineUnconditionally IAmDead -> True -- This happens; for example, the case_bndr during case of -- known constructor: case (a,b) of x { (p,q) -> ... } -- Here x isn't mentioned in the RHS, so we don't want to -- create the (dead) let-binding let x = (a,b) in ... _ -> False -- Here's an example that we don't handle well: -- let f = if b then Left (\x.BIG) else Right (\y.BIG) -- in \y. ....case f of {...} .... -- Here f is used just once, and duplicating the case work is fine (exprIsCheap). -- But -- - We can't preInlineUnconditionally because that woud invalidate -- the occ info for b. -- - We can't postInlineUnconditionally because the RHS is big, and -- that risks exponential behaviour -- - We can't call-site inline, because the rhs is big -- Alas! where active = isActive (sm_phase (getMode env)) (idInlineActivation bndr) -- See Note [pre/postInlineUnconditionally in gentle mode] {- Note [Top level and postInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't do postInlineUnconditionally for top-level things (even for ones that are trivial): * Doing so will inline top-level error expressions that have been carefully floated out by FloatOut. More generally, it might replace static allocation with dynamic. * Even for trivial expressions there's a problem. Consider {-# RULE "foo" forall (xs::[T]). reverse xs = ruggle xs #-} blah xs = reverse xs ruggle = sort In one simplifier pass we might fire the rule, getting blah xs = ruggle xs but in *that* simplifier pass we must not do postInlineUnconditionally on 'ruggle' because then we'll have an unbound occurrence of 'ruggle' If the rhs is trivial it'll be inlined by callSiteInline, and then the binding will be dead and discarded by the next use of OccurAnal * There is less point, because the main goal is to get rid of local bindings used in multiple case branches. * The inliner should inline trivial things at call sites anyway. Note [Stable unfoldings and postInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Do not do postInlineUnconditionally if the Id has an stable unfolding, otherwise we lose the unfolding. Example -- f has stable unfolding with rhs (e |> co) -- where 'e' is big f = e |> co Then there's a danger we'll optimise to f' = e f = f' |> co and now postInlineUnconditionally, losing the stable unfolding on f. Now f' won't inline because 'e' is too big. c.f. Note [Stable unfoldings and preInlineUnconditionally] ************************************************************************ * * Rebuilding a lambda * * ************************************************************************ -} mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplCont -> SimplM OutExpr -- mkLam tries three things -- a) eta reduction, if that gives a trivial expression -- b) eta expansion [only if there are some value lambdas] mkLam _env [] body _cont = return body mkLam env bndrs body cont = do { dflags <- getDynFlags ; mkLam' dflags bndrs body } where mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr mkLam' dflags bndrs (Cast body co) | not (any bad bndrs) -- Note [Casts and lambdas] = do { lam <- mkLam' dflags bndrs body ; return (mkCast lam (mkPiCos Representational bndrs co)) } where co_vars = tyCoVarsOfCo co bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars mkLam' dflags bndrs body@(Lam {}) = mkLam' dflags (bndrs ++ bndrs1) body1 where (bndrs1, body1) = collectBinders body mkLam' dflags bndrs (Tick t expr) | tickishFloatable t = mkTick t <$> mkLam' dflags bndrs expr mkLam' dflags bndrs body | gopt Opt_DoEtaReduction dflags , Just etad_lam <- tryEtaReduce bndrs body = do { tick (EtaReduction (head bndrs)) ; return etad_lam } | not (contIsRhs cont) -- See Note [Eta-expanding lambdas] , sm_eta_expand (getMode env) , any isRuntimeVar bndrs , let body_arity = exprEtaExpandArity dflags body , body_arity > 0 = do { tick (EtaExpansion (head bndrs)) ; let res = mkLams bndrs (etaExpand body_arity body) ; traceSmpl "eta expand" (vcat [text "before" <+> ppr (mkLams bndrs body) , text "after" <+> ppr res]) ; return res } | otherwise = return (mkLams bndrs body) {- Note [Eta expanding lambdas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In general we *do* want to eta-expand lambdas. Consider f (\x -> case x of (a,b) -> \s -> blah) where 's' is a state token, and hence can be eta expanded. This showed up in the code for GHc.IO.Handle.Text.hPutChar, a rather important function! The eta-expansion will never happen unless we do it now. (Well, it's possible that CorePrep will do it, but CorePrep only has a half-baked eta-expander that can't deal with casts. So it's much better to do it here.) However, when the lambda is let-bound, as the RHS of a let, we have a better eta-expander (in the form of tryEtaExpandRhs), so we don't bother to try expansion in mkLam in that case; hence the contIsRhs guard. NB: We check the SimplEnv (sm_eta_expand), not DynFlags. See Note [No eta expansion in stable unfoldings] Note [Casts and lambdas] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider (\x. (\y. e) `cast` g1) `cast` g2 There is a danger here that the two lambdas look separated, and the full laziness pass might float an expression to between the two. So this equation in mkLam' floats the g1 out, thus: (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1) where x:tx. In general, this floats casts outside lambdas, where (I hope) they might meet and cancel with some other cast: \x. e `cast` co ===> (\x. e) `cast` (tx -> co) /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co) /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co) (if not (g `in` co)) Notice that it works regardless of 'e'. Originally it worked only if 'e' was itself a lambda, but in some cases that resulted in fruitless iteration in the simplifier. A good example was when compiling Text.ParserCombinators.ReadPrec, where we had a definition like (\x. Get `cast` g) where Get is a constructor with nonzero arity. Then mkLam eta-expanded the Get, and the next iteration eta-reduced it, and then eta-expanded it again. Note also the side condition for the case of coercion binders. It does not make sense to transform /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g) because the latter is not well-kinded. ************************************************************************ * * Eta expansion * * ************************************************************************ -} tryEtaExpandRhs :: SimplEnv -> OutId -> OutExpr -> SimplM (Arity, OutExpr) -- See Note [Eta-expanding at let bindings] tryEtaExpandRhs env bndr rhs = do { dflags <- getDynFlags ; (new_arity, new_rhs) <- try_expand dflags ; WARN( new_arity < old_id_arity, (text "Arity decrease:" <+> (ppr bndr <+> ppr old_id_arity <+> ppr old_arity <+> ppr new_arity) $$ ppr new_rhs) ) -- Note [Arity decrease] in Simplify return (new_arity, new_rhs) } where try_expand dflags | exprIsTrivial rhs = return (exprArity rhs, rhs) | sm_eta_expand (getMode env) -- Provided eta-expansion is on , let new_arity1 = findRhsArity dflags bndr rhs old_arity new_arity2 = idCallArity bndr new_arity = max new_arity1 new_arity2 , new_arity > old_arity -- And the current manifest arity isn't enough = do { tick (EtaExpansion bndr) ; return (new_arity, etaExpand new_arity rhs) } | otherwise = return (old_arity, rhs) old_arity = exprArity rhs -- See Note [Do not expand eta-expand PAPs] old_id_arity = idArity bndr {- Note [Eta-expanding at let bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now eta expand at let-bindings, which is where the payoff comes. The most significant thing is that we can do a simple arity analysis (in CoreArity.findRhsArity), which we can't do for free-floating lambdas One useful consequence of not eta-expanding lambdas is this example: genMap :: C a => ... {-# INLINE genMap #-} genMap f xs = ... myMap :: D a => ... {-# INLINE myMap #-} myMap = genMap Notice that 'genMap' should only inline if applied to two arguments. In the stable unfolding for myMap we'll have the unfolding (\d -> genMap Int (..d..)) We do not want to eta-expand to (\d f xs -> genMap Int (..d..) f xs) because then 'genMap' will inline, and it really shouldn't: at least as far as the programmer is concerned, it's not applied to two arguments! Note [Do not eta-expand PAPs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to have old_arity = manifestArity rhs, which meant that we would eta-expand even PAPs. But this gives no particular advantage, and can lead to a massive blow-up in code size, exhibited by Trac #9020. Suppose we have a PAP foo :: IO () foo = returnIO () Then we can eta-expand do foo = (\eta. (returnIO () |> sym g) eta) |> g where g :: IO () ~ State# RealWorld -> (# State# RealWorld, () #) But there is really no point in doing this, and it generates masses of coercions and whatnot that eventually disappear again. For T9020, GHC allocated 6.6G beore, and 0.8G afterwards; and residency dropped from 1.8G to 45M. But note that this won't eta-expand, say f = \g -> map g Does it matter not eta-expanding such functions? I'm not sure. Perhaps strictness analysis will have less to bite on? ************************************************************************ * * \subsection{Floating lets out of big lambdas} * * ************************************************************************ Note [Floating and type abstraction] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: x = /\a. C e1 e2 We'd like to float this to y1 = /\a. e1 y2 = /\a. e2 x = /\a. C (y1 a) (y2 a) for the usual reasons: we want to inline x rather vigorously. You may think that this kind of thing is rare. But in some programs it is common. For example, if you do closure conversion you might get: data a :-> b = forall e. (e -> a -> b) :$ e f_cc :: forall a. a :-> a f_cc = /\a. (\e. id a) :$ () Now we really want to inline that f_cc thing so that the construction of the closure goes away. So I have elaborated simplLazyBind to understand right-hand sides that look like /\ a1..an. body and treat them specially. The real work is done in SimplUtils.abstractFloats, but there is quite a bit of plumbing in simplLazyBind as well. The same transformation is good when there are lets in the body: /\abc -> let(rec) x = e in b ==> let(rec) x' = /\abc -> let x = x' a b c in e in /\abc -> let x = x' a b c in b This is good because it can turn things like: let f = /\a -> letrec g = ... g ... in g into letrec g' = /\a -> ... g' a ... in let f = /\ a -> g' a which is better. In effect, it means that big lambdas don't impede let-floating. This optimisation is CRUCIAL in eliminating the junk introduced by desugaring mutually recursive definitions. Don't eliminate it lightly! [May 1999] If we do this transformation *regardless* then we can end up with some pretty silly stuff. For example, let st = /\ s -> let { x1=r1 ; x2=r2 } in ... in .. becomes let y1 = /\s -> r1 y2 = /\s -> r2 st = /\s -> ...[y1 s/x1, y2 s/x2] in .. Unless the "..." is a WHNF there is really no point in doing this. Indeed it can make things worse. Suppose x1 is used strictly, and is of the form x1* = case f y of { (a,b) -> e } If we abstract this wrt the tyvar we then can't do the case inline as we would normally do. That's why the whole transformation is part of the same process that floats let-bindings and constructor arguments out of RHSs. In particular, it is guarded by the doFloatFromRhs call in simplLazyBind. Note [Which type variables to abstract over] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Abstract only over the type variables free in the rhs wrt which the new binding is abstracted. Note that * The naive approach of abstracting wrt the tyvars free in the Id's /type/ fails. Consider: /\ a b -> let t :: (a,b) = (e1, e2) x :: a = fst t in ... Here, b isn't free in x's type, but we must nevertheless abstract wrt b as well, because t's type mentions b. Since t is floated too, we'd end up with the bogus: poly_t = /\ a b -> (e1, e2) poly_x = /\ a -> fst (poly_t a *b*) * We must do closeOverKinds. Example (Trac #10934): f = /\k (f:k->*) (a:k). let t = AccFailure @ (f a) in ... Here we want to float 't', but we must remember to abstract over 'k' as well, even though it is not explicitly mentioned in the RHS, otherwise we get t = /\ (f:k->*) (a:k). AccFailure @ (f a) which is obviously bogus. -} abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr) abstractFloats main_tvs body_env body = ASSERT( notNull body_floats ) do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats ; return (float_binds, CoreSubst.substExpr (text "abstract_floats1") subst body) } where main_tv_set = mkVarSet main_tvs body_floats = getFloatBinds body_env empty_subst = CoreSubst.mkEmptySubst (seInScope body_env) abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind) abstract subst (NonRec id rhs) = do { (poly_id, poly_app) <- mk_poly tvs_here id ; let poly_rhs = mkLams tvs_here rhs' subst' = CoreSubst.extendIdSubst subst id poly_app ; return (subst', (NonRec poly_id poly_rhs)) } where rhs' = CoreSubst.substExpr (text "abstract_floats2") subst rhs -- tvs_here: see Note [Which type variables to abstract over] tvs_here = toposortTyVars $ filter (`elemVarSet` main_tv_set) $ closeOverKindsList $ exprSomeFreeVarsList isTyVar rhs' abstract subst (Rec prs) = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps) poly_rhss = [mkLams tvs_here (CoreSubst.substExpr (text "abstract_floats3") subst' rhs) | rhs <- rhss] ; return (subst', Rec (poly_ids `zip` poly_rhss)) } where (ids,rhss) = unzip prs -- For a recursive group, it's a bit of a pain to work out the minimal -- set of tyvars over which to abstract: -- /\ a b c. let x = ...a... in -- letrec { p = ...x...q... -- q = .....p...b... } in -- ... -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'. -- Since it's a pain, we just use the whole set, which is always safe -- -- If you ever want to be more selective, remember this bizarre case too: -- x::a = x -- Here, we must abstract 'x' over 'a'. tvs_here = toposortTyVars main_tvs mk_poly tvs_here var = do { uniq <- getUniqueM ; let poly_name = setNameUnique (idName var) uniq -- Keep same name poly_ty = mkInvForAllTys tvs_here (idType var) -- But new type of course poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.hs mkLocalIdOrCoVar poly_name poly_ty ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) } -- In the olden days, it was crucial to copy the occInfo of the original var, -- because we were looking at occurrence-analysed but as yet unsimplified code! -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking -- at already simplified code, so it doesn't matter -- -- It's even right to retain single-occurrence or dead-var info: -- Suppose we started with /\a -> let x = E in B -- where x occurs once in B. Then we transform to: -- let x' = /\a -> E in /\a -> let x* = x' a in B -- where x* has an INLINE prag on it. Now, once x* is inlined, -- the occurrences of x' will be just the occurrences originally -- pinned on x. {- Note [Abstract over coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the type variable a. Rather than sort this mess out, we simply bale out and abstract wrt all the type variables if any of them are coercion variables. Historical note: if you use let-bindings instead of a substitution, beware of this: -- Suppose we start with: -- -- x = /\ a -> let g = G in E -- -- Then we'll float to get -- -- x = let poly_g = /\ a -> G -- in /\ a -> let g = poly_g a in E -- -- But now the occurrence analyser will see just one occurrence -- of poly_g, not inside a lambda, so the simplifier will -- PreInlineUnconditionally poly_g back into g! Badk to square 1! -- (I used to think that the "don't inline lone occurrences" stuff -- would stop this happening, but since it's the *only* occurrence, -- PreInlineUnconditionally kicks in first!) -- -- Solution: put an INLINE note on g's RHS, so that poly_g seems -- to appear many times. (NB: mkInlineMe eliminates -- such notes on trivial RHSs, so do it manually.) ************************************************************************ * * prepareAlts * * ************************************************************************ prepareAlts tries these things: 1. Eliminate alternatives that cannot match, including the DEFAULT alternative. 2. If the DEFAULT alternative can match only one possible constructor, then make that constructor explicit. e.g. case e of x { DEFAULT -> rhs } ===> case e of x { (a,b) -> rhs } where the type is a single constructor type. This gives better code when rhs also scrutinises x or e. 3. Returns a list of the constructors that cannot holds in the DEFAULT alternative (if there is one) Here "cannot match" includes knowledge from GADTs It's a good idea to do this stuff before simplifying the alternatives, to avoid simplifying alternatives we know can't happen, and to come up with the list of constructors that are handled, to put into the IdInfo of the case binder, for use when simplifying the alternatives. Eliminating the default alternative in (1) isn't so obvious, but it can happen: data Colour = Red | Green | Blue f x = case x of Red -> .. Green -> .. DEFAULT -> h x h y = case y of Blue -> .. DEFAULT -> [ case y of ... ] If we inline h into f, the default case of the inlined h can't happen. If we don't notice this, we may end up filtering out *all* the cases of the inner case y, which give us nowhere to go! -} prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt]) -- The returned alternatives can be empty, none are possible prepareAlts scrut case_bndr' alts | Just (tc, tys) <- splitTyConApp_maybe (varType case_bndr') -- Case binder is needed just for its type. Note that as an -- OutId, it has maximum information; this is important. -- Test simpl013 is an example = do { us <- getUniquesM ; let (idcs1, alts1) = filterAlts tc tys imposs_cons alts (yes2, alts2) = refineDefaultAlt us tc tys idcs1 alts1 (yes3, idcs3, alts3) = combineIdenticalAlts idcs1 alts2 -- "idcs" stands for "impossible default data constructors" -- i.e. the constructors that can't match the default case ; when yes2 $ tick (FillInCaseDefault case_bndr') ; when yes3 $ tick (AltMerge case_bndr') ; return (idcs3, alts3) } | otherwise -- Not a data type, so nothing interesting happens = return ([], alts) where imposs_cons = case scrut of Var v -> otherCons (idUnfolding v) _ -> [] {- ************************************************************************ * * mkCase * * ************************************************************************ mkCase tries these things 1. Merge Nested Cases case e of b { ==> case e of b { p1 -> rhs1 p1 -> rhs1 ... ... pm -> rhsm pm -> rhsm _ -> case b of b' { pn -> let b'=b in rhsn pn -> rhsn ... ... po -> let b'=b in rhso po -> rhso _ -> let b'=b in rhsd _ -> rhsd } which merges two cases in one case when -- the default alternative of the outer case scrutises the same variable as the outer case. This transformation is called Case Merging. It avoids that the same variable is scrutinised multiple times. 2. Eliminate Identity Case case e of ===> e True -> True; False -> False and similar friends. 3. Scrutinee Constant Folding case x op# k# of _ { ===> case x of _ { a1# -> e1 (a1# inv_op# k#) -> e1 a2# -> e2 (a2# inv_op# k#) -> e2 ... ... DEFAULT -> ed DEFAULT -> ed where (x op# k#) inv_op# k# == x And similarly for commuted arguments and for some unary operations. The purpose of this transformation is not only to avoid an arithmetic operation at runtime but to allow other transformations to apply in cascade. Example with the "Merge Nested Cases" optimization (from #12877): main = case t of t0 0## -> ... DEFAULT -> case t0 `minusWord#` 1## of t1 0## -> ... DEFAUT -> case t1 `minusWord#` 1## of t2 0## -> ... DEFAULT -> case t2 `minusWord#` 1## of _ 0## -> ... DEFAULT -> ... becomes: main = case t of _ 0## -> ... 1## -> ... 2## -> ... 3## -> ... DEFAULT -> ... -} mkCase, mkCase1, mkCase2, mkCase3 :: DynFlags -> OutExpr -> OutId -> OutType -> [OutAlt] -- Alternatives in standard (increasing) order -> SimplM OutExpr -------------------------------------------------- -- 1. Merge Nested Cases -------------------------------------------------- mkCase dflags scrut outer_bndr alts_ty ((DEFAULT, _, deflt_rhs) : outer_alts) | gopt Opt_CaseMerge dflags , (ticks, Case (Var inner_scrut_var) inner_bndr _ inner_alts) <- stripTicksTop tickishFloatable deflt_rhs , inner_scrut_var == outer_bndr = do { tick (CaseMerge outer_bndr) ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args ) (con, args, wrap_rhs rhs) -- Simplifier's no-shadowing invariant should ensure -- that outer_bndr is not shadowed by the inner patterns wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs -- The let is OK even for unboxed binders, wrapped_alts | isDeadBinder inner_bndr = inner_alts | otherwise = map wrap_alt inner_alts merged_alts = mergeAlts outer_alts wrapped_alts -- NB: mergeAlts gives priority to the left -- case x of -- A -> e1 -- DEFAULT -> case x of -- A -> e2 -- B -> e3 -- When we merge, we must ensure that e1 takes -- precedence over e2 as the value for A! ; fmap (mkTicks ticks) $ mkCase1 dflags scrut outer_bndr alts_ty merged_alts } -- Warning: don't call mkCase recursively! -- Firstly, there's no point, because inner alts have already had -- mkCase applied to them, so they won't have a case in their default -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr -- in munge_rhs may put a case into the DEFAULT branch! mkCase dflags scrut bndr alts_ty alts = mkCase1 dflags scrut bndr alts_ty alts -------------------------------------------------- -- 2. Eliminate Identity Case -------------------------------------------------- mkCase1 _dflags scrut case_bndr _ alts@((_,_,rhs1) : _) -- Identity case | all identity_alt alts = do { tick (CaseIdentity case_bndr) ; return (mkTicks ticks $ re_cast scrut rhs1) } where ticks = concatMap (stripTicksT tickishFloatable . thdOf3) (tail alts) identity_alt (con, args, rhs) = check_eq rhs con args check_eq (Cast rhs co) con args = not (any (`elemVarSet` tyCoVarsOfCo co) args) && check_eq rhs con args -- See Note [RHS casts] check_eq (Lit lit) (LitAlt lit') _ = lit == lit' check_eq (Var v) _ _ | v == case_bndr = True check_eq (Var v) (DataAlt con) [] = v == dataConWorkId con -- Optimisation only check_eq (Tick t e) alt args = tickishFloatable t && check_eq e alt args check_eq rhs (DataAlt con) args = cheapEqExpr' tickishFloatable rhs $ mkConApp con (arg_tys ++ varsToCoreExprs args) check_eq _ _ _ = False arg_tys = map Type (tyConAppArgs (idType case_bndr)) -- Note [RHS casts] -- ~~~~~~~~~~~~~~~~ -- We've seen this: -- case e of x { _ -> x `cast` c } -- And we definitely want to eliminate this case, to give -- e `cast` c -- So we throw away the cast from the RHS, and reconstruct -- it at the other end. All the RHS casts must be the same -- if (all identity_alt alts) holds. -- -- Don't worry about nested casts, because the simplifier combines them re_cast scrut (Cast rhs co) = Cast (re_cast scrut rhs) co re_cast scrut _ = scrut mkCase1 dflags scrut bndr alts_ty alts = mkCase2 dflags scrut bndr alts_ty alts -------------------------------------------------- -- 2. Scrutinee Constant Folding -------------------------------------------------- mkCase2 dflags scrut bndr alts_ty alts | gopt Opt_CaseFolding dflags , Just (scrut',f) <- caseRules scrut = mkCase3 dflags scrut' bndr alts_ty (map (mapAlt f) alts) | otherwise = mkCase3 dflags scrut bndr alts_ty alts where -- We need to keep the correct association between the scrutinee and its -- binder if the latter isn't dead. Hence we wrap rhs of alternatives with -- "let bndr = ... in": -- -- case v + 10 of y =====> case v of y -- 20 -> e1 10 -> let y = 20 in e1 -- DEFAULT -> e2 DEFAULT -> let y = v + 10 in e2 -- -- Other transformations give: =====> case v of y' -- 10 -> let y = 20 in e1 -- DEFAULT -> let y = y' + 10 in e2 -- wrap_rhs l rhs | isDeadBinder bndr = rhs | otherwise = Let (NonRec bndr l) rhs mapAlt f alt@(c,bs,e) = case c of DEFAULT -> (c, bs, wrap_rhs scrut e) LitAlt l | isLitValue l -> (LitAlt (mapLitValue f l), bs, wrap_rhs (Lit l) e) _ -> pprPanic "Unexpected alternative (mkCase2)" (ppr alt) -------------------------------------------------- -- Catch-all -------------------------------------------------- mkCase3 _dflags scrut bndr alts_ty alts = return (Case scrut bndr alts_ty alts) {- Note [Dead binders] ~~~~~~~~~~~~~~~~~~~~ Note that dead-ness is maintained by the simplifier, so that it is accurate after simplification as well as before. Note [Cascading case merge] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Case merging should cascade in one sweep, because it happens bottom-up case e of a { DEFAULT -> case a of b DEFAULT -> case b of c { DEFAULT -> e A -> ea B -> eb C -> ec ==> case e of a { DEFAULT -> case a of b DEFAULT -> let c = b in e A -> let c = b in ea B -> eb C -> ec ==> case e of a { DEFAULT -> let b = a in let c = b in e A -> let b = a in let c = b in ea B -> let b = a in eb C -> ec However here's a tricky case that we still don't catch, and I don't see how to catch it in one pass: case x of c1 { I# a1 -> case a1 of c2 -> 0 -> ... DEFAULT -> case x of c3 { I# a2 -> case a2 of ... After occurrence analysis (and its binder-swap) we get this case x of c1 { I# a1 -> let x = c1 in -- Binder-swap addition case a1 of c2 -> 0 -> ... DEFAULT -> case x of c3 { I# a2 -> case a2 of ... When we simplify the inner case x, we'll see that x=c1=I# a1. So we'll bind a2 to a1, and get case x of c1 { I# a1 -> case a1 of c2 -> 0 -> ... DEFAULT -> case a1 of ... This is corect, but we can't do a case merge in this sweep because c2 /= a1. Reason: the binding c1=I# a1 went inwards without getting changed to c1=I# c2. I don't think this is worth fixing, even if I knew how. It'll all come out in the next pass anyway. -}
olsner/ghc
compiler/simplCore/SimplUtils.hs
bsd-3-clause
82,750
0
18
25,480
8,625
4,608
4,017
-1
-1
module Control.Semigroup where class Semigroup s where (<>) :: s -> s -> s
tonymorris/lens-proposal
src/Control/Semigroup.hs
bsd-3-clause
90
0
8
29
30
17
13
6
0
-- Copyright (c) 2016 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. {-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-} module IR.Common.Transfer( Transfer(..) ) where import Data.Hashable import Data.Hashable.Extras import Data.Position.DWARFPosition import IR.Common.Names import IR.Common.Rename import IR.Common.RenameType import Prelude.Extras import Text.Format import Text.XML.Expat.Pickle hiding (Node) import Text.XML.Expat.Tree(NodeG) -- | Transfers. These represent methods of leaving a basic block. -- All basic blocks end in a transfer. data Transfer exp = -- | A direct jump Goto { -- | The jump target. gotoLabel :: !Label, -- | The position in source from which this arises. gotoPos :: DWARFPosition Globalname Typename } -- | A (integer) case expression | Case { -- | The value being decided upon. Must be an integer value. caseVal :: exp, -- | The cases. There must be at least one case. caseCases :: [(Integer, Label)], -- | The default case. caseDefault :: !Label, -- | The position in source from which this arises. casePos :: DWARFPosition Globalname Typename } -- | A return | Ret { -- | The return value, if one exists. retVal :: Maybe exp, -- | The position in source from which this arises. retPos :: DWARFPosition Globalname Typename } -- | An unreachable instruction, usually following a call with no -- return | Unreachable { unreachablePos :: DWARFPosition Globalname Typename } instance Eq1 Transfer where Goto { gotoLabel = label1 } ==# Goto { gotoLabel = label2 } = label1 == label2 Case { caseVal = val1, caseCases = cases1, caseDefault = def1 } ==# Case { caseVal = val2, caseCases = cases2, caseDefault = def2 } = val1 == val2 && cases1 == cases2 && def1 == def2 Ret { retVal = ret1 } ==# Ret { retVal = ret2 } = ret1 == ret2 Unreachable _ ==# Unreachable _ = True _ ==# _ = False instance Eq exp => Eq (Transfer exp) where (==) = (==#) instance Ord1 Transfer where compare1 Goto { gotoLabel = label1 } Goto { gotoLabel = label2 } = compare label1 label2 compare1 Goto {} _ = LT compare1 _ Goto {} = GT compare1 Case { caseVal = val1, caseCases = cases1, caseDefault = def1 } Case { caseVal = val2, caseCases = cases2, caseDefault = def2 } = case compare val1 val2 of EQ -> case compare def1 def2 of EQ -> compare cases1 cases2 out -> out out -> out compare1 Case {} _ = LT compare1 _ Case {} = GT compare1 Ret { retVal = ret1 } Ret { retVal = ret2 } = compare ret1 ret2 compare1 Ret {} _ = LT compare1 _ Ret {} = GT compare1 (Unreachable _) (Unreachable _) = EQ instance Ord exp => Ord (Transfer exp) where compare = compare1 instance Hashable1 Transfer where hashWithSalt1 s Goto { gotoLabel = label } = s `hashWithSalt` (1 :: Int) `hashWithSalt` label hashWithSalt1 s Case { caseVal = val, caseCases = cases, caseDefault = def } = s `hashWithSalt` (2 :: Int) `hashWithSalt` val `hashWithSalt` cases `hashWithSalt` def hashWithSalt1 s Ret { retVal = val } = s `hashWithSalt` (3 :: Int) `hashWithSalt` val hashWithSalt1 s (Unreachable _) = s `hashWithSalt` (4 :: Int) instance Hashable elem => Hashable (Transfer elem) where hashWithSalt = hashWithSalt1 instance RenameType Typename exp => RenameType Typename (Transfer exp) where renameType f tr @ Case { caseVal = val } = tr { caseVal = renameType f val } renameType f tr @ Ret { retVal = val } = tr { retVal = renameType f val } renameType _ tr = tr instance Rename Id exp => Rename Id (Transfer exp) where rename f tr @ Case { caseVal = val } = tr { caseVal = rename f val } rename f tr @ Ret { retVal = val } = tr { retVal = rename f val } rename _ tr = tr instance Format exp => Format (Transfer exp) where format Goto { gotoLabel = l } = string "goto" <+> format l format Case { caseVal = e, caseCases = cases, caseDefault = def } = let mapfun (i, l) = format i <> colon <+> format l casesdoc = list ((string "default" <> colon <+> format def) : map mapfun cases) in string "case" <+> align (format e </> casesdoc) format Ret { retVal = Just e } = string "ret" <+> format e format Ret { retVal = Nothing } = string "ret" format (Unreachable _) = string "Unreachable" instance FormatM m exp => FormatM m (Transfer exp) where formatM Goto { gotoLabel = l } = return $! string "goto" <+> format l formatM Case { caseVal = e, caseCases = cases, caseDefault = def } = let mapfun (i, l) = format i <> colon <+> format l casesdoc = list ((string "default" <> colon <+> format def) : map mapfun cases) in do edoc <- formatM e return $! string "case" <> align (softbreak <> edoc </> casesdoc) formatM Ret { retVal = Just e } = do edoc <- formatM e return $! string "ret" <+> edoc formatM Ret { retVal = Nothing } = return $! string "ret" formatM (Unreachable _) = return $! string "Unreachable" gotoPickler :: (GenericXMLString tag, Show tag, GenericXMLString text, Show text) => PU [NodeG [] tag text] (Transfer exp) gotoPickler = let revfunc Goto { gotoLabel = l, gotoPos = pos } = (l, pos) revfunc _ = error $! "Can't convert" in xpWrap (\(l, pos) -> Goto { gotoLabel = l, gotoPos = pos }, revfunc) (xpElem (gxFromString "Goto") xpickle (xpElemNodes (gxFromString "pos") xpickle)) casePickler :: (GenericXMLString tag, Show tag, GenericXMLString text, Show text, XmlPickler [NodeG [] tag text] exp) => PU [NodeG [] tag text] (Transfer exp) casePickler = let revfunc Case { caseVal = val, caseDefault = def, caseCases = cases, casePos = pos } = (val, cases, def, pos) revfunc _ = error $! "Can't convert" casepickler = xpElemNodes (gxFromString "cases") (xpList (xpElemAttrs (gxFromString "case") (xpPair (xpAttr (gxFromString "val") xpPrim) xpickle))) in xpWrap (\(val, cases, def, pos) -> Case { caseVal = val, caseDefault = def, caseCases = cases, casePos = pos }, revfunc) (xpElemNodes (gxFromString "Case") (xp4Tuple (xpElemNodes (gxFromString "val") xpickle) (xpElemNodes (gxFromString "cases") casepickler) (xpElemAttrs (gxFromString "default") xpickle) (xpElemNodes (gxFromString "pos") xpickle))) retPickler :: (GenericXMLString tag, Show tag, GenericXMLString text, Show text, XmlPickler [NodeG [] tag text] exp) => PU [NodeG [] tag text] (Transfer exp) retPickler = let revfunc Ret { retVal = val, retPos = pos } = (pos, val) revfunc _ = error $! "Can't convert" in xpWrap (\(pos, val) -> Ret { retVal = val, retPos = pos }, revfunc) (xpElemNodes (gxFromString "Ret") (xpPair xpickle (xpOption (xpElemNodes (gxFromString "val") xpickle)))) unreachablePickler :: (GenericXMLString tag, Show tag, GenericXMLString text, Show text) => PU [NodeG [] tag text] (Transfer exp) unreachablePickler = let revfunc (Unreachable pos) = pos revfunc _ = error "cannot convert" in xpWrap (Unreachable, revfunc) (xpElemNodes (gxFromString "Unreachable") xpickle) instance (GenericXMLString tag, Show tag, GenericXMLString text, Show text, XmlPickler [NodeG [] tag text] exp) => XmlPickler [NodeG [] tag text] (Transfer exp) where xpickle = let picker Goto {} = 0 picker Case {} = 1 picker Ret {} = 2 picker Unreachable {} = 3 in xpAlt picker [gotoPickler, casePickler, retPickler, unreachablePickler]
emc2/iridium
src/IR/Common/Transfer.hs
bsd-3-clause
9,896
4
19
2,819
2,668
1,430
1,238
175
2
-- | This module contains fuctions and templates for building up and breaking -- down packed bit structures. It's something like Erlang's bit-syntax (or, -- actually, more like Python's struct module). -- -- This code uses Data.ByteString which is included in GHC 6.5 and you can -- get it for 6.4 at <http://www.cse.unsw.edu.au/~dons/fps.html> module Data.BitSyntax ( -- * Building bit structures -- | The core function here is makeBits, which is a perfectly normal function. -- Here's an example which makes a SOCKS4a request header: -- @ -- makeBits [U8 4, U8 1, U16 80, U32 10, NullTerminated \"username\", -- NullTerminated \"www.haskell.org\"] -- @ BitBlock(..), makeBits, -- * Breaking up bit structures -- | The main function for this is bitSyn, which is a template function and -- so you'll need to run with @-fth@ to enable template haskell -- <http://www.haskell.org/th/>. -- -- To expand the function you use the splice command: -- @ -- $(bitSyn [...]) -- @ -- -- The expanded function has type @ByteString -> (...)@ where the elements of -- the tuple depend of the argument to bitSyn (that's why it has to be a template -- function). -- -- Heres an example, translated from the Erlang manual, which parses an IP header: -- -- @ -- decodeOptions bs ([_, hlen], _, _, _, _, _, _, _, _, _) -- | hlen > 5 = return $ BS.splitAt (fromIntegral ((hlen - 5) * 4)) bs -- | otherwise = return (BS.empty, bs) -- @ -- -- @ -- ipDecode = $(bitSyn [PackedBits [4, 4], Unsigned 1, Unsigned 2, Unsigned 2, -- PackedBits [3, 13], Unsigned 1, Unsigned 1, Unsigned 2, -- Fixed 4, Fixed 4, Context \'decodeOptions, Rest]) -- @ -- -- @ -- ipPacket = BS.pack [0x45, 0, 0, 0x34, 0xd8, 0xd2, 0x40, 0, 0x40, 0x06, -- 0xa0, 0xca, 0xac, 0x12, 0x68, 0x4d, 0xac, 0x18, -- 0x00, 0xaf] -- @ -- -- This function has several weaknesses compared to the Erlang version: The -- elements of the bit structure are not named in place, instead you have to -- do a pattern match on the resulting tuple and match up the indexes. The -- type system helps in this, but it's still not quite as nice. ReadType(..), bitSyn, -- I get errors if these aren't exported (Can't find interface-file -- declaration for Data.BitSyntax.decodeU16) decodeU8, decodeU16, decodeU32, decodeU16LE, decodeU32LE) where import Language.Haskell.TH.Lib import Language.Haskell.TH.Syntax import qualified Data.ByteString as BS import Data.Char (ord) import Control.Monad import Test.QuickCheck (Arbitrary(), arbitrary, Gen()) import Foreign foreign import ccall unsafe "htonl" htonl :: Word32 -> Word32 foreign import ccall unsafe "htons" htons :: Word16 -> Word16 -- There's no good way to convert to little-endian. The htons functions only -- convert to big endian and they don't have any little endian friends. So we -- need to detect which kind of system we are on and act accordingly. We can -- detect the type of system by seeing if htonl actaully doesn't anything (it's -- the identity function on big-endian systems, of course). If it doesn't we're -- on a big-endian system and so need to do the byte-swapping in Haskell because -- the C functions are no-ops -- | A native Haskell version of htonl for the case where we need to convert -- to little-endian on a big-endian system endianSwitch32 :: Word32 -> Word32 endianSwitch32 a = ((a .&. 0xff) `shiftL` 24) .|. ((a .&. 0xff00) `shiftL` 8) .|. ((a .&. 0xff0000) `shiftR` 8) .|. (a `shiftR` 24) -- | A native Haskell version of htons for the case where we need to convert -- to little-endian on a big-endian system endianSwitch16 :: Word16 -> Word16 endianSwitch16 a = ((a .&. 0xff) `shiftL` 8) .|. (a `shiftR` 8) littleEndian32 :: Word32 -> Word32 littleEndian32 a = if htonl 1 == 1 then endianSwitch32 a else a littleEndian16 :: Word16 -> Word16 littleEndian16 a = if htonl 1 == 1 then endianSwitch16 a else a data BitBlock = -- | Unsigned 8-bit int U8 Int | -- | Unsigned 16-bit int U16 Int | -- | Unsigned 32-bit int U32 Int | -- | Little-endian, unsigned 16-bit int U16LE Int | -- | Little-endian, unsigned 32-bit int U32LE Int | -- | Appends the string with a trailing NUL byte NullTerminated String | -- | Appends the string without any terminator RawString String | -- | Appends a ByteString RawByteString BS.ByteString | -- | Packs a series of bit fields together. The argument is -- a list of pairs where the first element is the size -- (in bits) and the second is the value. The sum of the -- sizes for a given PackBits must be a multiple of 8 PackBits [(Int, Int)] deriving (Show) -- Encodes a member of the Bits class as a series of bytes and returns the -- ByteString of those bytes. getBytes :: (Integral a, Bounded a, Bits a) => a -> BS.ByteString getBytes input = let getByte _ 0 = [] getByte x remaining = (fromIntegral $ (x .&. 0xff)) : getByte (shiftR x 8) (remaining - 1) in if (bitSize input `mod` 8) /= 0 then error "Input data bit size must be a multiple of 8" else BS.pack $ getByte input (bitSize input `div` 8) -- Performs the work behind PackBits packBits :: (Word8, Int, [Word8]) -- ^ The current byte, the number of bits -- used in that byte and the (reverse) -- list of produced bytes -> (Int, Int) -- ^ The size (in bits) of the value, and the value -> (Word8, Int, [Word8]) -- See first argument packBits (current, used, bytes) (size, value) = if bitsWritten < size then packBits (0, 0, current' : bytes) (size - bitsWritten, value) else if used' == 8 then (0, 0, current' : bytes) else (current', used', bytes) where top = size - 1 topOfByte = 7 - used aligned = value `shift` (topOfByte - top) newBits = (fromIntegral aligned) :: Word8 current' = current .|. newBits bitsWritten = min (8 - used) size used' = used + bitsWritten bits :: BitBlock -> BS.ByteString bits (U8 v) = BS.pack [((fromIntegral v) :: Word8)] bits (U16 v) = getBytes ((htons $ fromIntegral v) :: Word16) bits (U32 v) = getBytes ((htonl $ fromIntegral v) :: Word32) bits (U16LE v) = getBytes (littleEndian16 $ fromIntegral v) bits (U32LE v) = getBytes (littleEndian32 $ fromIntegral v) bits (NullTerminated str) = BS.pack $ (map (fromIntegral . ord) str) ++ [0] bits (RawString str) = BS.pack $ map (fromIntegral . ord) str bits (RawByteString bs) = bs bits (PackBits bitspec) = if (sum $ map fst bitspec) `mod` 8 /= 0 then error "Sum of sizes of a bit spec must == 0 mod 8" else (\(_, _, a) -> BS.pack $ reverse a) $ foldl packBits (0, 0, []) bitspec -- | Make a binary string from the list of elements given makeBits :: [BitBlock] -> BS.ByteString makeBits = BS.concat . (map bits) data ReadType = -- | An unsigned number of some number of bytes. Valid -- arguments are 1, 2 and 4 Unsigned Integer | -- | An unsigned, little-endian integer of some number of -- bytes. Valid arguments are 2 and 4 UnsignedLE Integer | -- | A variable length element to be decoded by a custom -- function. The function's name is given as the single -- argument and should have type -- @Monad m => ByteString -> m (v, ByteString)@ Variable Name | -- | Skip some number of bytes Skip Integer | -- | A fixed size field, the result of which is a ByteString -- of that length. Fixed Integer | -- | Decode a value and ignore it (the result will not be part -- of the returned tuple) Ignore ReadType | -- | Like variable, but the decoding function is passed the -- entire result tuple so far. Thus the function whose name -- passed has type -- @Monad m => ByteString -> (...) -> m (v, ByteString)@ Context Name | -- | Takes the most recent element of the result tuple and -- interprets it as the length of this field. Results in -- a ByteString LengthPrefixed | -- | Decode a series of bit fields, results in a list of -- Integers. Each element of the argument is the length of -- the bit field. The sums of the lengths must be a multiple -- of 8 PackedBits [Integer] | -- | Results in a ByteString containing the undecoded bytes so -- far. Generally used at the end to return the trailing body -- of a structure, it can actually be used at any point in the -- decoding to return the trailing part at that point. Rest fromBytes :: (Num a, Bits a) => [a] -> a fromBytes input = let dofb accum [] = accum dofb accum (x:xs) = dofb ((shiftL accum 8) .|. x) xs in dofb 0 $ reverse input -- | First byte of a 'BS.ByteString'. decodeU8 :: BS.ByteString -> Word8 decodeU8 = fromIntegral . head . BS.unpack -- | Convert little-endian 'BS.ByteString' to big-endian 'Word16'. decodeU16 :: BS.ByteString -> Word16 decodeU16 = htons . fromBytes . map fromIntegral . BS.unpack -- | Convert little-endian 'BS.ByteString' to big-endian 'Word32'. decodeU32 :: BS.ByteString -> Word32 decodeU32 = htonl . fromBytes . map fromIntegral . BS.unpack -- | Convert little-endian 'BS.ByteString' to little-endian 'Word16'. decodeU16LE :: BS.ByteString -> Word16 decodeU16LE = littleEndian16 . fromBytes . map fromIntegral . BS.unpack -- | Convert little-endian 'BS.ByteString' to little-endian 'Word32'. decodeU32LE :: BS.ByteString -> Word32 decodeU32LE = littleEndian32 . fromBytes . map fromIntegral . BS.unpack decodeBits :: [Integer] -> BS.ByteString -> [Integer] decodeBits sizes bs = reverse values where (values, _, _) = foldl unpackBits ([], 0, BS.unpack bitdata) sizes bytesize = (sum sizes) `shiftR` 3 (bitdata, _) = BS.splitAt (fromIntegral bytesize) bs unpackBits :: ([Integer], Integer, [Word8]) -> Integer -> ([Integer], Integer, [Word8]) unpackBits state size = unpackBitsInner 0 state size unpackBitsInner :: Integer -> ([Integer], Integer, [Word8]) -> Integer -> ([Integer], Integer, [Word8]) unpackBitsInner _ (output, used, []) _ = (output, used, []) unpackBitsInner val (output, used, current : input) bitsToGet = if bitsToGet' > 0 then unpackBitsInner val'' (output, 0, input) bitsToGet' else if used' < 8 then (val'' : output, used', current'' : input) else (val'' : output, 0, input) where bitsAv = 8 - used bitsTaken = min bitsAv bitsToGet val' = val `shift` (fromIntegral bitsTaken) current' = current `shiftR` (fromIntegral (8 - bitsTaken)) current'' = current `shiftL` (fromIntegral bitsTaken) val'' = val' .|. (fromIntegral current') bitsToGet' = bitsToGet - bitsTaken used' = used + bitsTaken readElement :: ([Stmt], Name, [Name]) -> ReadType -> Q ([Stmt], Name, [Name]) readElement (stmts, inputname, tuplenames) (Context funcname) = do valname <- newName "val" restname <- newName "rest" let stmt = BindS (TupP [VarP valname, VarP restname]) (AppE (AppE (VarE funcname) (VarE inputname)) #if MIN_VERSION_template_haskell(2,16,0) (TupE $ map (Just . VarE) $ reverse tuplenames)) #else (TupE $ map VarE $ reverse tuplenames)) #endif return (stmt : stmts, restname, valname : tuplenames) readElement (stmts, inputname, tuplenames) (Fixed n) = do valname <- newName "val" restname <- newName "rest" let dec1 = ValD (TupP [VarP valname, VarP restname]) (NormalB $ AppE (AppE (VarE 'BS.splitAt) (LitE (IntegerL n))) (VarE inputname)) [] return (LetS [dec1] : stmts, restname, valname : tuplenames) readElement state@(_, _, tuplenames) (Ignore n) = do (a, b, _) <- readElement state n return (a, b, tuplenames) readElement (stmts, inputname, tuplenames) LengthPrefixed = do valname <- newName "val" restname <- newName "rest" let sourcename = head tuplenames dec = ValD (TupP [VarP valname, VarP restname]) (NormalB $ AppE (AppE (VarE 'BS.splitAt) (AppE (VarE 'fromIntegral) (VarE sourcename))) (VarE inputname)) [] return (LetS [dec] : stmts, restname, valname : tuplenames) readElement (stmts, inputname, tuplenames) (Variable funcname) = do valname <- newName "val" restname <- newName "rest" let stmt = BindS (TupP [VarP valname, VarP restname]) (AppE (VarE funcname) (VarE inputname)) return (stmt : stmts, restname, valname : tuplenames) readElement (stmts, inputname, tuplenames) Rest = do restname <- newName "rest" let dec = ValD (VarP restname) (NormalB $ VarE inputname) [] return (LetS [dec] : stmts, inputname, restname : tuplenames) readElement (stmts, inputname, tuplenames) (Skip n) = do -- Expands to something like: -- rest = Data.ByteString.drop n input restname <- newName "rest" let dec = ValD (VarP restname) (NormalB $ AppE (AppE (VarE 'BS.drop) (LitE (IntegerL n))) (VarE inputname)) [] return (LetS [dec] : stmts, restname, tuplenames) readElement state (Unsigned size) = do -- Expands to something like: -- (aval, arest) = Data.ByteString.splitAt 1 input -- a = BitSyntax.decodeU8 aval let decodefunc = case size of 1 -> 'decodeU8 2 -> 'decodeU16 _ -> 'decodeU32 -- Default to 32 decodeHelper state (VarE decodefunc) size readElement state (UnsignedLE size) = do -- Expands to something like: -- (aval, arest) = Data.ByteString.splitAt 1 input -- a = BitSyntax.decodeU8LE aval let decodefunc = case size of 2 -> 'decodeU16LE _ -> 'decodeU32LE -- Default to 4 decodeHelper state (VarE decodefunc) size readElement state (PackedBits sizes) = if sum sizes `mod` 8 /= 0 then error "Sizes of packed bits must == 0 mod 8" else decodeHelper state (AppE (VarE 'decodeBits) (ListE $ map (LitE . IntegerL) sizes)) ((sum sizes) `shiftR` 3) decodeHelper :: ([Stmt], Name, [Name]) -> Exp -> Integer -> Q ([Stmt], Name, [Name]) decodeHelper (stmts, inputname, tuplenames) decodefunc size = do valname <- newName "val" restname <- newName "rest" tuplename <- newName "tup" let dec1 = ValD (TupP [VarP valname, VarP restname]) (NormalB $ AppE (AppE (VarE 'BS.splitAt) (LitE (IntegerL size))) (VarE inputname)) [] let dec2 = ValD (VarP tuplename) (NormalB $ AppE decodefunc (VarE valname)) [] return (LetS [dec1, dec2] : stmts, restname, tuplename : tuplenames) decGetName :: Dec -> Name decGetName (ValD (VarP name) _ _) = name decGetName _ = undefined -- Error! -- | Example usage: -- -- > parsePascalString :: Monad m => ByteString -> m (Word16, ByteString) -- > parsePascalString bs = $( bitSyn [UnsignedLE 2, LengthPrefixed] ) bs bitSyn :: [ReadType] -> Q Exp bitSyn elements = do inputname <- newName "input" (stmts, restname, tuplenames) <- foldM readElement ([], inputname, []) elements returnS <- NoBindS `liftM` [| return $(tupE . map varE $ reverse tuplenames) |] return $ LamE [VarP inputname] (DoE . reverse $ returnS : stmts) -- Tests prop_bitPacking :: [(Int, Int)] -> Bool prop_bitPacking fields = prevalues == (map fromIntegral postvalues) || any (< 1) (map fst fields) || any (< 0) (map snd fields) where undershoot = sum (map fst fields) `mod` 8 fields' = if undershoot > 0 then (8 - undershoot, 1) : fields else fields prevalues = map snd fields' packed = bits $ PackBits fields' postvalues = decodeBits (map (fromIntegral . fst) fields') packed #if !MIN_VERSION_QuickCheck(2,1,2) instance Arbitrary Word16 where arbitrary = (arbitrary :: Gen Int) >>= return . fromIntegral instance Arbitrary Word32 where arbitrary = (arbitrary :: Gen Int) >>= return . fromIntegral #endif -- | This only works on little-endian machines as it checks that the foreign -- functions (htonl and htons) match the native ones prop_nativeByteShuffle32 :: Word32 -> Bool prop_nativeByteShuffle32 x = endianSwitch32 x == htonl x prop_nativeByteShuffle16 :: Word16 -> Bool prop_nativeByteShuffle16 x = endianSwitch16 x == htons x prop_littleEndian16 :: Word16 -> Bool prop_littleEndian16 x = littleEndian16 x == x prop_littleEndian32 :: Word32 -> Bool prop_littleEndian32 x = littleEndian32 x == x
joecrayne/hs-bitsyntax
Data/BitSyntax.hs
bsd-3-clause
18,156
0
19
5,527
4,002
2,207
1,795
-1
-1
-------------------------------------------------------------------------------- -- | Interval-based implementation of preview polling {-# LANGUAGE CPP #-} module Hakyll.Preview.Poll ( previewPoll ) where -------------------------------------------------------------------------------- import Control.Applicative ((<$>)) import Control.Concurrent (threadDelay) import Control.Monad (filterM) #if MIN_VERSION_directory(1,2,0) import Data.Time (getCurrentTime) #else import System.Time (getClockTime) #endif import System.Directory (doesFileExist, getModificationTime) -------------------------------------------------------------------------------- import Hakyll.Core.Configuration -------------------------------------------------------------------------------- -- | A preview thread that periodically recompiles the site. previewPoll :: Configuration -- ^ Configuration -> IO [FilePath] -- ^ Updating action -> IO () -- ^ Can block forever previewPoll _ update = do #if MIN_VERSION_directory(1,2,0) time <- getCurrentTime #else time <- getClockTime #endif loop time =<< update where delay = 1000000 loop time files = do threadDelay delay files' <- filterM doesFileExist files filesTime <- case files' of [] -> return time _ -> maximum <$> mapM getModificationTime files' if filesTime > time || files' /= files then loop filesTime =<< update else loop time files'
bergmark/hakyll
src/Hakyll/Preview/Poll.hs
bsd-3-clause
1,653
0
14
434
247
136
111
25
3
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module HypeStat.Valve where import Data.Hashable import qualified Data.HashMap.Strict as HM import Data.Sequence as S import Prelude as P ---------------- -- Declarations ---------------- type Predicate a = a -> Bool data Valve p intype outtype = Valve { unValve :: intype -> outtype } deriving Functor instance Applicative (Valve p intype) where pure a = Valve (const a) Valve g <*> Valve t = Valve $ \x -> g x (t x) type Group gid gval = HM.HashMap gid (Seq gval) runValve :: Valve p a b -> a -> b runValve = unValve ------------- -- Operators ------------- infixl 2 |=> (|=>) :: Valve p a b -> Valve p b c -> Valve p a c Valve f1 |=> Valve f2 = Valve (f2 . f1) infixl 1 !=> (!=>) :: a -> Valve p a b -> b (!=>) = P.flip runValve --------- -- Valves --------- count :: (Foldable t) => Valve p (t a) Int count = Valve P.length min :: (Ord a, Foldable t) => Valve p (t a) a min = Valve P.minimum max :: (Ord a, Foldable t) => Valve p (t a) a max = Valve P.maximum sum :: (Num a, Foldable t) => Valve p (t a) a sum = Valve P.sum -- Imperformant avg :: (Fractional a, Foldable t) => Valve p (t a) a avg = (/) <$> Valve P.sum <*> Valve (P.fromIntegral . P.length) match :: (Applicative t, Foldable t, Monoid (t a)) => Predicate a -> Valve p (t a) (t a) match predicator = Valve (ffilter predicator) where ffilter :: (Applicative t, Foldable t, Monoid (t a)) => Predicate a -> t a -> t a ffilter pred = foldMap (\elem -> if pred elem then pure elem else mempty) project :: Functor f => (a -> b) -> Valve p (f a) (f b) project f = Valve (fmap f) group :: (Eq a, Hashable a, Foldable t) => Valve p (t a) (Group a a) group = groupBy id groupBy :: forall a gid p t. (Eq gid, Hashable gid, Foldable t) => (a -> gid) -> Valve p (t a) (Group gid a) groupBy f = Valve (foldr ins HM.empty) where ins :: a -> Group gid a -> Group gid a ins val = HM.insertWith (flip (><)) (f val) (S.singleton val)
KenetJervet/hypestat
src/HypeStat/Valve.hs
bsd-3-clause
2,260
0
11
585
964
509
455
48
2
{-# LANGUAGE OverloadedStrings, RecursiveDo, ScopedTypeVariables, FlexibleContexts, TypeFamilies, ConstraintKinds #-} module Frontend.Properties.RDS ( rdsProperties ) where import Prelude hiding (mapM, mapM_, all, sequence) import qualified Data.Map as Map import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import Reflex import Reflex.Dom.Core ------ import AWSFunction -------------------------------------------------------------------------- -- Amazon RDS Properties ------- calcRDSInst :: T.Text -> T.Text -> Int -> Int -> Int -> Int -> T.Text -> T.Text calcRDSInst rdsi rdsu ukey ekey ckey dkey rdss = case ekey of 1 -> toText $ (readDouble rdsu) * (calcUsage' ukey) * (calcEngine' dkey ckey) * (readDouble rdss) _ -> toText $ (readDouble rdsu) * (calcUsage' ukey) * (calcEngine'' dkey ckey) * (readDouble rdss) where calcUsage' x = case x of 1 -> 30 2 -> 4 _ -> 1 calcEngine' dk ck = case dk of 1 -> calcDeploy' ck (readDouble rdsi) _ -> calcDeploy'' ck (readDouble rdsi) where calcDeploy' ck' rds' = case ck' of 1 -> rds' * 0.026 2 -> rds' * 0.052 3 -> rds' * 0.104 _ -> rds' * 0.209 calcDeploy'' ck' rds' = case ck' of 1 -> rds' * 0.052 2 -> rds' * 0.104 3 -> rds' * 0.208 _ -> rds' * 0.418 calcEngine'' dk ck = case dk of 1 -> calcDeploy' ck (readDouble rdsi) _ -> calcDeploy'' ck (readDouble rdsi) where calcDeploy' ck' rds' = case ck' of 1 -> rds' * 0.028 2 -> rds' * 0.056 3 -> rds' * 0.112 _ -> rds' * 0.224 calcDeploy'' ck' rds' = case ck' of 1 -> rds' * 0.056 2 -> rds' * 0.112 3 -> rds' * 0.224 _ -> rds' * 0.448 ------------------ rdsProperties :: (Reflex t, MonadWidget t m) => Dynamic t (Map.Map T.Text T.Text) -> m (Dynamic t Text) rdsProperties dynAttrs = do result <- elDynAttr "div" ((constDyn $ idAttrs RDS) <> dynAttrs <> rightClassAttrs) $ do rec rdsInst <- rdsInstance evReset evReset <- button "Reset" return $ rdsInst return $ result rdsInstance :: (Reflex t, MonadWidget t m) => Event t a -> m (Dynamic t Text) rdsInstance evReset = do rec let resultRds = calcRDSInst <$> (value rdsInstances) <*> (value rdsUsage) <*> (value ddRdsUsage) <*> (value ddRdsEngine) <*> (value ddRdsClass) <*> (value ddRdsDeploy) <*> (value rdsStore) el "h4" $ text "RDS On-Demand DB Instances: " el "p" $ text "Instances:" rdsInstances <- textInput $ def & textInputConfig_inputType .~ "number" & textInputConfig_initialValue .~ "0" & setValue .~ (leftmost ["0" <$ evReset]) el "p" $ text "Usage:" rdsUsage <- textInput $ def & textInputConfig_inputType .~ "number" & textInputConfig_initialValue .~ "0" & setValue .~ (leftmost ["0" <$ evReset]) ddRdsUsage <- dropdown 1 (constDyn ddUsage) def el "p" $ text "UsageDB Engine" el "p" $ text "and License: " ddRdsEngine <- dropdown 1 (constDyn ddEngine) def el "p" $ text "Class and Deployment: " el "p" $ blank ddRdsClass <- dropdown 1 (constDyn ddType) def ddRdsDeploy <- dropdown 1 (constDyn ddDeploy) def el "p" $ text "Storage (in GB): " rdsStore <- textInput $ def & textInputConfig_inputType .~ "number" & textInputConfig_initialValue .~ "0" & setValue .~ (leftmost ["0" <$ evReset]) return $ resultRds
Rizary/awspi
Lib/Frontend/Properties/RDS.hs
bsd-3-clause
3,692
6
28
1,111
1,201
594
607
95
18
module Lava.IOBuffering where import System.IO ( hSetBuffering , stdout , BufferMode(..) ) noBuffering :: IO () noBuffering = hSetBuffering stdout NoBuffering
dfordivam/lava
Lava/IOBuffering.hs
bsd-3-clause
169
0
6
31
46
27
19
7
1
{-# LANGUAGE UndecidableInstances, ConstraintKinds, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-} module Control.Monad.Incremental.Internal.Adapton.Display where import Control.Monad.Incremental.Display import Control.Monad.Incremental import Control.Monad.Incremental.Internal.Adapton.Types import Control.Monad.Incremental.Internal.Adapton.Layers import Control.Monad.Trans import Data.Typeable import Control.Monad -- * Display instance (IncK inc a,Display Outside inc a,Input M l inc ) => Display Outside inc (M l inc a) where displaysPrec proxyL proxyInc m rest = getOutside m >>= \x -> liftM (\x -> "<" ++ (show $ idNM $ metaM m) ++ " " ++ x) $ displaysPrec proxyL proxyInc x ('>':rest) {-# INLINE displaysPrec #-} instance (IncK inc a,Display Inside inc a,Input M Inside inc ) => Display Inside inc (M Inside inc a) where displaysPrec proxyL proxyInc m rest = get m >>= \x -> liftM (\x -> "<" ++ (show $ idNM $ metaM m) ++ " " ++ x) $ displaysPrec proxyL proxyInc x ('>':rest) {-# INLINE displaysPrec #-} instance (IncK inc a,Display Outside inc a,Output U l inc ) => Display Outside inc (U l inc a) where displaysPrec proxyL proxyInc m rest = forceOutside m >>= \x -> liftM (\x -> "<" ++ (show $ idNM $ metaU m) ++ " " ++ x) $ displaysPrec proxyL proxyInc x ('>':rest) {-# INLINE displaysPrec #-} instance (IncK inc a,Display Inside inc a,Output U Inside inc ) => Display Inside inc (U Inside inc a) where displaysPrec proxyL proxyInc m rest = force m >>= \x -> liftM (\x -> "<" ++ (show $ idNM $ metaU m) ++ " " ++ x) $ displaysPrec proxyL proxyInc x ('>':rest) {-# INLINE displaysPrec #-} instance (IncK inc a,Display Outside inc a,Input L l inc ) => Display Outside inc (L l inc a) where displaysPrec proxyL proxyInc m rest = getOutside m >>= \x -> liftM (\x -> "<" ++ (show $ idNM $ metaL m) ++ " " ++ x) $ displaysPrec proxyL proxyInc x ('>':rest) {-# INLINE displaysPrec #-} instance (IncK inc a,Display Inside inc a,Input L Inside inc ) => Display Inside inc (L Inside inc a) where displaysPrec proxyL proxyInc m rest = get m >>= \x -> liftM (\x -> "<" ++ (show $ idNM $ metaL m) ++ " " ++ x) $ displaysPrec proxyL proxyInc x ('>':rest) {-# INLINE displaysPrec #-} -- * NFDataInc instance (IncK inc a,NFDataInc Outside inc a,Input M l inc ) => NFDataInc Outside inc (M l inc a) where nfDataInc proxyL proxyInc m = getOutside m >>= nfDataInc proxyL proxyInc {-# INLINE nfDataInc #-} instance (IncK inc a,NFDataInc Inside inc a,Input M Inside inc ) => NFDataInc Inside inc (M Inside inc a) where nfDataInc proxyL proxyInc m = get m >>= nfDataInc proxyL proxyInc {-# INLINE nfDataInc #-} instance (IncK inc a,NFDataInc Outside inc a,Output U l inc ) => NFDataInc Outside inc (U l inc a) where nfDataInc proxyL proxyInc m = forceOutside m >>= nfDataInc proxyL proxyInc {-# INLINE nfDataInc #-} instance (IncK inc a,NFDataInc Inside inc a,Output U Inside inc ) => NFDataInc Inside inc (U Inside inc a) where nfDataInc proxyL proxyInc m = force m >>= nfDataInc proxyL proxyInc {-# INLINE nfDataInc #-} instance (IncK inc a,NFDataInc Outside inc a,Input L l inc ) => NFDataInc Outside inc (L l inc a) where nfDataInc proxyL proxyInc m = getOutside m >>= nfDataInc proxyL proxyInc {-# INLINE nfDataInc #-} instance (IncK inc a,NFDataInc Inside inc a,Input L Inside inc ) => NFDataInc Inside inc (L Inside inc a) where nfDataInc proxyL proxyInc m = get m >>= nfDataInc proxyL proxyInc {-# INLINE nfDataInc #-} -- * Show instances instance Show (U l inc a) where show t = "U" ++ show (idNM $ metaU t) instance Show (M l inc a) where show t = "M" ++ show (idNM $ metaM t) instance Show (L l inc a) where show t = "L" ++ show (idNM $ metaL t)
cornell-pl/HsAdapton
src/Control/Monad/Incremental/Internal/Adapton/Display.hs
bsd-3-clause
3,750
4
17
725
1,484
764
720
51
0
module Text.DivideCSVSpec (main, spec) where import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "someFunction" $ do it "should work fine" $ do True `shouldBe` False
smurphy8/divide-csv
test/Text/DivideCSVSpec.hs
bsd-3-clause
211
0
13
49
76
40
36
9
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 OverloadedStrings #-} module Duckling.Temperature.TR.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.Resolve import Duckling.Temperature.Types import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale TR Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (simple Celsius 37) [ "37°C" , "37 ° santigrat" , "37 derece C" , "37 C" , "37 derece santigrat" , "otuz yedi santigrat" ] , examples (simple Fahrenheit 70) [ "70°F" , "70 ° Fahrenhayt" , "70 ° Fahrenayt" , "70 derece fahrenhayt" , "70 derece F" , "70 F" , "yetmiş fahrenayt" ] , examples (simple Degree 45) [ "45°" , "45 derece" , "kırk beş derece" ] , examples (simple Degree (-2)) [ "-2°" , "- 2 derece" , "sıfırın altında 2°" , "sıfırın altında 2 derece" , "2° sıfırın altında" , "2 derece sıfırın altında" ] ]
facebookincubator/duckling
Duckling/Temperature/TR/Corpus.hs
bsd-3-clause
1,495
0
11
535
232
141
91
39
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE TypeOperators #-} module Control.Eff.Fresh where import Control.Eff import Control.Concurrent.Supply data Fresh a x where Fresh :: Fresh a a fresh :: (Fresh a :< effs) => Eff effs a fresh = eta Fresh runFresh :: IsSupply s a => Eff (Fresh a ': effs) b -> s -> Eff effs b runFresh (Pure b) _ = pure b runFresh (Impure es k) s = case decomp es of Left es' -> Impure es' (\x -> runFresh (k x) s) Right Fresh -> let (a, s') = fresh_ s in runFresh (k a) s' class IsSupply s a | s -> a where fresh_ :: s -> (a, s) instance IsSupply Supply Int where fresh_ = freshId instance IsSupply [a] a where fresh_ (x:xs) = (x,xs) fresh_ [] = error "IsSupply.fresh_: empty list"
mitchellwrosen/effects-a-la-carte
src/Control/Eff/Fresh.hs
bsd-3-clause
928
0
13
249
328
172
156
-1
-1
module CalculatorKata.Day4Spec (spec) where import Test.Hspec import CalculatorKata.Day4 (calculate) spec :: Spec spec = do it "calculates one digit" (calculate "4" == 4.0) it "calculates many digits" (calculate "345" == 345.0) it "calculates addition" (calculate "56+78" == 56.0+78.0) it "calculates subtraction" (calculate "768-45" == 768.0-45.0) it "calculates multiplication" (calculate "65*2" == 65.0*2.0) it "calculates division" (calculate "66/3" == 66.0/3.0)
Alex-Diez/haskell-tdd-kata
old-katas/test/CalculatorKata/Day4Spec.hs
bsd-3-clause
610
0
11
202
160
78
82
17
1
module Main where import System.FilePath ((</>)) import qualified System.Directory import qualified Test.DocTest main :: IO () main = do pwd <- System.Directory.getCurrentDirectory prefix <- System.Directory.makeAbsolute pwd let src = prefix </> "src" Test.DocTest.doctest [ "--fast", "-i" <> src, src ]
Gabriel439/Haskell-Dhall-Library
dhall-toml/doctest/Main.hs
bsd-3-clause
325
0
10
61
101
56
45
10
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE CPP #-} module Language.Haskell.Generate.Monad ( Generate(..), ExpG , runGenerate, newName , returnE , useValue, useCon, useVar , caseE , applyE, applyE2, applyE3, applyE4, applyE5, applyE6 , (<>$) , GenExp(..) , ModuleM(..) , ModuleG , FunRef(..) , Name(..) , exportFun , addDecl , runModuleM , generateModule , generateExp ) where import Control.Applicative import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.State import Control.Monad.Trans.Writer import qualified Data.Set as S import Language.Haskell.Exts.Pretty import Language.Haskell.Exts.SrcLoc import Language.Haskell.Exts.Syntax import Language.Haskell.Generate.Expression import Prelude -------------------------------------------------------------------------------- -- Generate expressions -- | This monad keeps track of a counter for generating unique names and the set of modules -- that are needed for the expression. newtype Generate a = Generate { unGenerate :: StateT Integer (Writer (S.Set ModuleName)) a } deriving (Functor, Applicative, Monad) -- | Extract the set of modules and the value from a Generate action. runGenerate :: Generate a -> (a, S.Set ModuleName) runGenerate (Generate a) = runWriter $ evalStateT a 0 -- | This is a type alias for a Generate action that returns an expression of type 't'. type ExpG t = Generate (Expression t) -- | Use a haskell-src-exts Exp as the result of a Generate action. returnE :: Exp -> ExpG t returnE = return . Expression -- | Pretty print the expression generated by a given action. generateExp :: ExpG t -> String generateExp = prettyPrint . runExpression . fst . runGenerate -- | Generate a case expression. caseE :: ExpG x -> [(Pat, ExpG t)] -> ExpG t caseE v alt = do v' <- v #if MIN_VERSION_haskell_src_exts(1,17,0) alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') Nothing) a) alt #elif MIN_VERSION_haskell_src_exts(1,16,0) alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') (BDecls [])) a) alt #else alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedAlt $ runExpression a') (BDecls [])) a) alt #endif return $ Expression $ Case (runExpression v') alt' -- | Import a function from a module. This function is polymorphic in the type of the resulting expression, -- you should probably only use this function to define type-restricted specializations. -- -- Example: -- -- > addInt :: ExpG (Int -> Int -> Int) -- Here we restricted the type to something sensible -- > addInt = useValue "Prelude" $ Symbol "+" -- useValue :: String -> Name -> ExpG a useValue md name = Generate $ do lift $ tell $ S.singleton $ ModuleName md return $ Expression $ Var $ Qual (ModuleName md) name -- | Import a value constructor from a module. Returns the qualified name of the constructor. useCon :: String -> Name -> Generate QName useCon md name = Generate $ do lift $ tell $ S.singleton $ ModuleName md return $ Qual (ModuleName md) name -- | Use the value of a variable with the given name. useVar :: Name -> ExpG t useVar name = return $ Expression $ Var $ UnQual name -- | Generate a new unique variable name with the given prefix. Note that this new variable name -- is only unique relative to other variable names generated by this function. newName :: String -> Generate Name newName pref = Generate $ do i <- get <* modify succ return $ Ident $ pref ++ show i -- | Generate a expression from a haskell value. This can for example be used to create lambdas: -- -- >>> putStrLn $ generateExp $ expr (\x f -> f <>$ x) -- \ pvar_0 -> \ pvar_1 -> pvar_1 pvar_0 -- -- Or string literals: -- -- >>> putStrLn $ generateExp $ expr "I'm a string!" -- ['I', '\'', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', '!'] -- class GenExp t where type GenExpType t :: * -- | This function generates the haskell expression from the given haskell value. expr :: t -> ExpG (GenExpType t) instance GenExp (ExpG a) where type GenExpType (ExpG a) = a expr = id instance GenExp (Expression t) where type GenExpType (Expression t) = t expr = return instance GenExp Char where type GenExpType Char = Char expr = return . Expression . Lit . Char instance GenExp Integer where type GenExpType Integer = Integer expr = return . Expression . Lit . Int instance GenExp Rational where type GenExpType Rational = Rational expr = return . Expression . Lit . Frac instance GenExp a => GenExp [a] where type GenExpType [a] = [GenExpType a] expr = Generate . fmap (Expression . List . map runExpression) . mapM (unGenerate . expr) instance GenExp x => GenExp (ExpG a -> x) where type GenExpType (ExpG a -> x) = a -> GenExpType x expr f = do pvarName <- newName "pvar_" body <- expr $ f $ return $ Expression $ Var $ UnQual pvarName return $ Expression $ Lambda noLoc [PVar pvarName] $ runExpression body -------------------------------------------------------------------------------- -- Apply functions -- | Apply a function in a haskell expression to a value. applyE :: ExpG (a -> b) -> ExpG a -> ExpG b applyE a b = wrap $ liftM (foldl1 App) $ sequence [unwrap a, unwrap b] where wrap = fmap Expression unwrap = fmap runExpression -- | Operator for 'applyE'. (<>$) :: ExpG (a -> b) -> ExpG a -> ExpG b (<>$) = applyE infixl 1 <>$ -- | ApplyE for 2 arguments applyE2 :: ExpG (a -> b -> c) -> ExpG a -> ExpG b -> ExpG c applyE2 a b c = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 3 arguments applyE3 :: ExpG (a -> b -> c -> d) -> ExpG a -> ExpG b -> ExpG c -> ExpG d applyE3 a b c d = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 4 arguments applyE4 :: ExpG (a -> b -> c -> d -> e) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e applyE4 a b c d e = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 5 arguments applyE5 :: ExpG (a -> b -> c -> d -> e -> f) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f applyE5 a b c d e f = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 6 arguments applyE6 :: ExpG (a -> b -> c -> d -> e -> f -> g) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f -> ExpG g applyE6 a b c d e f g = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f,unwrap g] where wrap = fmap Expression unwrap = fmap runExpression -------------------------------------------------------------------------------- -- Generate modules -- | A module keeps track of the needed imports, but also has a list of declarations in it. newtype ModuleM a = ModuleM (Writer (S.Set ModuleName, [Decl]) a) deriving (Functor, Applicative, Monad) -- | This is the resulting type of a function generating a module. It is a ModuleM action returning the export list. type ModuleG = ModuleM (Maybe [ExportSpec]) -- | A reference to a function. With a reference to a function, you can apply it (by lifting it into ExprT using 'expr') to some value -- or export it using 'exportFun'. data FunRef t = FunRef Name instance GenExp (FunRef t) where type GenExpType (FunRef t) = t expr (FunRef n) = return $ Expression $ Var $ UnQual n -- | Generate a ExportSpec for a given function item. exportFun :: FunRef t -> ExportSpec #if MIN_VERSION_haskell_src_exts(1,16,0) && !MIN_VERSION_haskell_src_exts(1,17,0) exportFun (FunRef name) = EVar NoNamespace (UnQual name) #else exportFun (FunRef name) = EVar (UnQual name) #endif -- | Add a declaration to the module. Return a reference to it that can be used to either apply the function to some values or export it. addDecl :: Name -> ExpG t -> ModuleM (FunRef t) addDecl name e = ModuleM $ do let (body, mods) = runGenerate e #if MIN_VERSION_haskell_src_exts(1,17,0) tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) Nothing]]) #else tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) $ BDecls []]]) #endif return $ FunRef name -- | Extract the Module from a module generator. runModuleM :: ModuleG -> String -> Module runModuleM (ModuleM act) name = #if MIN_VERSION_haskell_src_exts(1,16,0) Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False False Nothing Nothing Nothing) $ S.toList imps) decls #else Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False Nothing Nothing Nothing) $ S.toList imps) decls #endif where (export, (imps, decls)) = runWriter act -- | Generate the source code for a module. generateModule :: ModuleG -> String -> String generateModule = fmap prettyPrint . runModuleM
bennofs/haskell-generate
src/Language/Haskell/Generate/Monad.hs
bsd-3-clause
9,406
0
17
1,911
2,467
1,295
1,172
135
1
module Paths_asda ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/huggaida/Desktop/haskell-game/.stack-work/install/x86_64-linux/lts-3.6/7.10.2/bin" libdir = "/home/huggaida/Desktop/haskell-game/.stack-work/install/x86_64-linux/lts-3.6/7.10.2/lib/x86_64-linux-ghc-7.10.2/asda-0.1.0.0-LWuyTh33Dd94mI6jxOtQX8" datadir = "/home/huggaida/Desktop/haskell-game/.stack-work/install/x86_64-linux/lts-3.6/7.10.2/share/x86_64-linux-ghc-7.10.2/asda-0.1.0.0" libexecdir = "/home/huggaida/Desktop/haskell-game/.stack-work/install/x86_64-linux/lts-3.6/7.10.2/libexec" sysconfdir = "/home/huggaida/Desktop/haskell-game/.stack-work/install/x86_64-linux/lts-3.6/7.10.2/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "asda_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "asda_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "asda_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "asda_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "asda_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
huggaida/haskell-game
.stack-work/dist/x86_64-linux/Cabal-1.22.4.0/build/autogen/Paths_asda.hs
bsd-3-clause
1,631
0
10
177
362
206
156
28
1
{- - Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Hacq. - Hacq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE RankNTypes #-} module Control.Monad.Quantum.Counter (module Control.Monad.Quantum.Class, module Control.Monad.Quantum.Counter.Class, QuantumCounter, runQuantumCounter, execQuantumCounter, runQuantumCounterWithoutMemo, generateCost) where import Control.Monad.Quantum.Class import Control.Monad.Quantum.Base.Counter import Control.Monad.Quantum.Counter.Class import Control.Monad.Quantum.Toffoli.ToStandard import Control.Monad.Quantum.Control import Data.Void type QuantumCounter s r c k = QuantumControlT () (ToffoliToStandardT () (QuantumCounterBase s r c (k, [()]))) runQuantumCounter :: (forall s. QuantumCounter s r c k a) -> Int -> r -> (a, c) runQuantumCounter m ctrls = runQuantumCounterBase $ runToffoliToStandardT $ runQuantumControlT m $ replicate ctrls () execQuantumCounter :: (forall s. QuantumCounter s r c k a) -> Int -> r -> c execQuantumCounter m ctrls = execQuantumCounterBase $ runToffoliToStandardT $ runQuantumControlT m $ replicate ctrls () runQuantumCounterWithoutMemo :: (forall s. QuantumCounter s r c Void a) -> Int -> r -> (a, c) runQuantumCounterWithoutMemo = runQuantumCounter generateCost :: (forall s. QuantumCounter s r c k a) -> r -> c generateCost m = execQuantumCounter m 0
ti1024/hacq
src/Control/Monad/Quantum/Counter.hs
bsd-3-clause
1,454
0
12
215
371
213
158
21
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module Main where import AI import Analysis import Game import Types import Match import System.Console.CmdArgs import System.IO import Text.Printf data PlayMode = LosingMoves | BestMove | Play | Perft | Solve deriving (Show, Data, Typeable) data Opponents = AIHuman | HumanAI | HumanHuman | AIAI | Analyse deriving (Show, Data, Typeable) data Conf = Conf { algorithm :: Algorithm , implementation :: Implementation , depth :: Int , altDepth :: Int , playMode :: PlayMode , opponents :: Opponents } deriving (Show, Data, Typeable) conf :: Conf conf = Conf { depth = 5 &= help "Depth" , altDepth = 5 &= help "Depth used for the second AI when tw oAIs are playing each other" , algorithm = Negascout &= help "alphabeta | negascout | minimax | idalpha" , implementation = My &= help "gametree | my | tzaar" , playMode = LosingMoves &= help "losing | best | play | perft | solve" , opponents = AIHuman &= help "AIHuman | HumanAI | HumanHuman | AIAI | Analyse" } &= summary "Hamisado AI system" &= program "Hamisado" dumpOptions :: Conf -> String dumpOptions c = printf "Params: mode=%s, algo=%s, implementation=%s, depth=%d" (show $ playMode c) (show $ algorithm c) (show $ implementation c) (depth c) main :: IO () main = do c@Conf{..} <- cmdArgs conf hSetBuffering stdout NoBuffering putStrLn $ dumpOptions c case playMode of LosingMoves -> do putStr "Losing moves: " print $ losingFirstMoves algorithm implementation depth BestMove -> do putStr "Best move: " let (pv, score) = bestMove algorithm implementation depth printf "Score: %d, PV: %s\n" score (show pv) Play -> let ai = \d -> aiStrategy algorithm implementation d analysis = analysisStrategy algorithm implementation depth analyse = match analysis analysis human = humanStrategy in case opponents of AIHuman -> match (ai depth) human HumanAI -> match human (ai depth) HumanHuman -> match human human AIAI -> match (ai depth) (ai altDepth) Analyse -> analyse Perft -> do -- You can learn more about Perft here: -- http://chessprogramming.wikispaces.com/Perft let leaves = map (reverse . pMoves) $ legalPositions depth initialPosition printf "Perft for depth=%d, total number of leaves=%d\n" depth (length leaves) mapM_ print leaves Solve -> printf "Solving result: %s\n" (show $ solve algorithm implementation depth)
sphynx/hamisado
Hamisado.hs
bsd-3-clause
2,742
0
18
736
689
356
333
72
9
module PFDS.Sec8.Ex2 where data RotationState a = Idle | Reversing Int [a] [a] [a] [a] | Appending Int [a] [a] | Done [a] deriving (Show) data Queue a = Q Int [a] (RotationState a) Int [a] deriving (Show) exec :: RotationState a -> RotationState a exec (Reversing ok (x:f) f' (y:r) r') = Reversing (ok+1) f (x:f') r (y:r') exec (Reversing ok [] f' [y] r') = Appending ok f' (y:r') exec (Appending 0 f' r') = Done r' exec (Appending ok (x:f') r') = Appending (ok-1) f' (x:r') exec state = state invalidate :: RotationState a -> RotationState a invalidate (Reversing ok f f' r r') = Reversing (ok-1) f f' r r' invalidate (Appending 0 f' (x:r')) = Done r' invalidate (Appending ok f' r') = Appending (ok-1) f' r' invalidate state = state exec1 :: Queue a -> Queue a exec1 (Q lenf f state lenr r) = case exec state of Done newf -> Q lenf newf Idle lenr r newstate -> Q lenf f newstate lenr r exec2 :: Queue a -> Queue a exec2 (Q lenf f state lenr r) = case exec (exec state) of Done newf -> Q lenf newf Idle lenr r newstate -> Q lenf f newstate lenr r check :: Queue a -> Queue a check q@(Q lenf f state lenr r) = if lenr <= lenf then exec1 q else exec2 (Q (lenf+lenr) f newstate 0 []) where newstate = Reversing 0 f [] r [] empty :: Queue a empty = Q 0 [] Idle 0 [] isEmpty :: Queue a -> Bool isEmpty (Q lenf _ _ _ _) = lenf == 0 snoc :: Queue a -> a -> Queue a snoc (Q lenf f state lenr r) x = check (Q lenf f state (lenr+1) (x:r)) head :: Queue a -> a head (Q _ [] _ _ _) = error "empty" head (Q _ (x:_) _ _ _) = x tail :: Queue a -> Queue a tail (Q _ [] _ _ _) = error "empty" tail (Q lenf (x:f) state lenr r) = check (Q (lenf-1) f (invalidate state) lenr r)
matonix/pfds
src/PFDS/Sec8/Ex2.hs
bsd-3-clause
1,756
0
10
457
1,009
512
497
45
2
module Craft.Ant where type Ants = Int anteater :: Int -> Int anteater x = x+1 aardvark = anteater
Numberartificial/workflow
snipets/src/Craft/Chapter15/Ant.hs
mit
103
0
5
23
38
22
16
5
1
module CLI where import Options.Applicative -------------------------------------------------------------------------------- -- | Represents arguments that can be passed to the CLI. data CLIOpts = CLIOpts { configPath :: Maybe FilePath , envPath :: Maybe FilePath } -------------------------------------------------------------------------------- -- | Parses CLIOpts and adds description when generating help text. cliOpts :: ParserInfo CLIOpts cliOpts = info (helper <*> cliOptsParser) (fullDesc <> progDesc "Print ShellCheck results as CodeClimate engine JSON" <> header "codeclimate-shellcheck - codeclimate shellcheck engine") -------------------------------------------------------------------------------- -- | Parses CLIOpts. cliOptsParser :: Parser CLIOpts cliOptsParser = CLIOpts <$> optional (strOption (long "config" <> help "Location of engine config")) <*> optional (strOption (long "env" <> help "Location of engine data mapping"))
filib/codeclimate-shellcheck
app/CLI.hs
gpl-3.0
1,097
0
12
257
149
79
70
16
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} import qualified SDL.GLFW as GLFW import Graphics.GL import Data.Bits import Control.Monad import Linear import SetupGLFW import Graphics.GL.Pal import Cube ------------------------------------------------------------- -- A test to make sure font rendering works ------------------------------------------------------------- resX, resY :: Num a => a resX = 1920 resY = 1080 main :: IO a main = do win <- createGLWindow "GL Pal" cubeProg <- createReshaderProgram "test/cube.vert" "test/cube.frag" cube <- makeCube =<< cubeProg glClearColor 0 0.1 0.1 1 glEnable GL_DEPTH_TEST whileWindow win $ \events -> do useProgram =<< cubeProg -- Clear the framebuffer glClear ( GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT ) -- Render our scene let projection = perspective 45 (resX/resY) 0.01 1000 model = mkTransformation 1 (V3 0 0 (-4)) view = lookAt (V3 0 2 5) (V3 0 0 (-4)) (V3 0 1 0) mvp = projection !*! view !*! model (x,y,w,h) = (0,0,1920,1080) glViewport x y w h renderCube cube mvp glSwapWindow win
lukexi/gl-pal
test/TestReshader.hs
bsd-3-clause
1,250
0
18
340
335
175
160
31
1
{-# OPTIONS -cpp #-} -- OPTIONS required for ghc-6.4.x compat, and must appear first {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -cpp #-} {-# OPTIONS_NHC98 -cpp #-} {-# OPTIONS_JHC -fcpp #-} -- #hide module Distribution.Compat.TempFile ( openTempFile, openBinaryTempFile, openNewBinaryFile, createTempDirectory, ) where import System.FilePath ((</>)) import Foreign.C (eEXIST) #if __NHC__ || __HUGS__ import System.IO (openFile, openBinaryFile, Handle, IOMode(ReadWriteMode)) import System.Directory (doesFileExist) import System.FilePath ((<.>), splitExtension) import System.IO.Error (try, isAlreadyExistsError) #else import System.IO (Handle, openTempFile, openBinaryTempFile) import Data.Bits ((.|.)) import System.Posix.Internals (c_open, c_close, o_CREAT, o_EXCL, o_RDWR, o_BINARY, o_NONBLOCK, o_NOCTTY) import System.IO.Error (isAlreadyExistsError) #if __GLASGOW_HASKELL__ >= 611 import System.Posix.Internals (withFilePath) #else import Foreign.C (withCString) #endif import Foreign.C (CInt) #if __GLASGOW_HASKELL__ >= 611 import GHC.IO.Handle.FD (fdToHandle) #else import GHC.Handle (fdToHandle) #endif import Distribution.Compat.Exception (onException, tryIO) #endif import Foreign.C (getErrno, errnoToIOError) #if __NHC__ import System.Posix.Types (CPid(..)) foreign import ccall unsafe "getpid" c_getpid :: IO CPid #else import System.Posix.Internals (c_getpid) #endif #ifdef mingw32_HOST_OS import System.Directory ( createDirectory ) #else import qualified System.Posix #endif -- ------------------------------------------------------------ -- * temporary files -- ------------------------------------------------------------ -- This is here for Haskell implementations that do not come with -- System.IO.openTempFile. This includes nhc-1.20, hugs-2006.9. -- TODO: Not sure about jhc #if __NHC__ || __HUGS__ -- use a temporary filename that doesn't already exist. -- NB. *not* secure (we don't atomically lock the tmp file we get) openTempFile :: FilePath -> String -> IO (FilePath, Handle) openTempFile tmp_dir template = do x <- getProcessID findTempName x where (templateBase, templateExt) = splitExtension template findTempName :: Int -> IO (FilePath, Handle) findTempName x = do let path = tmp_dir </> (templateBase ++ "-" ++ show x) <.> templateExt b <- doesFileExist path if b then findTempName (x+1) else do hnd <- openFile path ReadWriteMode return (path, hnd) openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) openBinaryTempFile tmp_dir template = do x <- getProcessID findTempName x where (templateBase, templateExt) = splitExtension template findTempName :: Int -> IO (FilePath, Handle) findTempName x = do let path = tmp_dir </> (templateBase ++ "-" ++ show x) <.> templateExt b <- doesFileExist path if b then findTempName (x+1) else do hnd <- openBinaryFile path ReadWriteMode return (path, hnd) openNewBinaryFile :: FilePath -> String -> IO (FilePath, Handle) openNewBinaryFile = openBinaryTempFile getProcessID :: IO Int getProcessID = fmap fromIntegral c_getpid #else -- This is a copy/paste of the openBinaryTempFile definition, but -- if uses 666 rather than 600 for the permissions. The base library -- needs to be changed to make this better. openNewBinaryFile :: FilePath -> String -> IO (FilePath, Handle) openNewBinaryFile dir template = do pid <- c_getpid findTempName pid where -- We split off the last extension, so we can use .foo.ext files -- for temporary files (hidden on Unix OSes). Unfortunately we're -- below filepath in the hierarchy here. (prefix,suffix) = case break (== '.') $ reverse template of -- First case: template contains no '.'s. Just re-reverse it. (rev_suffix, "") -> (reverse rev_suffix, "") -- Second case: template contains at least one '.'. Strip the -- dot from the prefix and prepend it to the suffix (if we don't -- do this, the unique number will get added after the '.' and -- thus be part of the extension, which is wrong.) (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix) -- Otherwise, something is wrong, because (break (== '.')) should -- always return a pair with either the empty string or a string -- beginning with '.' as the second component. _ -> error "bug in System.IO.openTempFile" oflags = rw_flags .|. o_EXCL .|. o_BINARY #if __GLASGOW_HASKELL__ < 611 withFilePath = withCString #endif findTempName x = do fd <- withFilePath filepath $ \ f -> c_open f oflags 0o666 if fd < 0 then do errno <- getErrno if errno == eEXIST then findTempName (x+1) else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir)) else do -- TODO: We want to tell fdToHandle what the filepath is, -- as any exceptions etc will only be able to report the -- fd currently h <- #if __GLASGOW_HASKELL__ >= 609 fdToHandle fd #elif __GLASGOW_HASKELL__ <= 606 && defined(mingw32_HOST_OS) -- fdToHandle is borked on Windows with ghc-6.6.x openFd (fromIntegral fd) Nothing False filepath ReadWriteMode True #else fdToHandle (fromIntegral fd) #endif `onException` c_close fd return (filepath, h) where filename = prefix ++ show x ++ suffix filepath = dir `combine` filename -- FIXME: bits copied from System.FilePath combine a b | null b = a | null a = b | last a == pathSeparator = a ++ b | otherwise = a ++ [pathSeparator] ++ b -- FIXME: Should use filepath library pathSeparator :: Char #ifdef mingw32_HOST_OS pathSeparator = '\\' #else pathSeparator = '/' #endif -- FIXME: Copied from GHC.Handle std_flags, output_flags, rw_flags :: CInt std_flags = o_NONBLOCK .|. o_NOCTTY output_flags = std_flags .|. o_CREAT rw_flags = output_flags .|. o_RDWR #endif createTempDirectory :: FilePath -> String -> IO FilePath createTempDirectory dir template = do pid <- c_getpid findTempName pid where findTempName x = do let dirpath = dir </> template ++ "-" ++ show x r <- tryIO $ mkPrivateDir dirpath case r of Right _ -> return dirpath Left e | isAlreadyExistsError e -> findTempName (x+1) | otherwise -> ioError e mkPrivateDir :: String -> IO () #ifdef mingw32_HOST_OS mkPrivateDir s = createDirectory s #else mkPrivateDir s = System.Posix.createDirectory s 0o700 #endif
IreneKnapp/Faction
libfaction/Distribution/Compat/TempFile.hs
bsd-3-clause
7,096
1
16
1,913
1,087
586
501
75
5
{-# LANGUAGE Haskell2010, OverloadedStrings #-} {-# LINE 1 "Network/Wai/Middleware/Rewrite.hs" #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE CPP #-} module Network.Wai.Middleware.Rewrite ( -- * How to use this module -- $howto -- ** A note on semantics -- $semantics -- ** Paths and Queries -- $pathsandqueries PathsAndQueries -- ** An example rewriting paths with queries -- $takeover -- ** Upgrading from wai-extra ≤ 3.0.16.1 -- $upgrading -- * 'Middleware' -- ** Recommended functions , rewriteWithQueries , rewritePureWithQueries -- ** Deprecated , rewrite , rewritePure -- * Operating on 'Request's , rewriteRequest , rewriteRequestPure ) where import Network.Wai import Control.Monad.IO.Class (liftIO) import Data.Text (Text) import Data.Functor.Identity (Identity(..)) import qualified Data.Text.Encoding as TE import qualified Data.Text as T import Network.HTTP.Types as H -- GHC ≤ 7.10 does not export Applicative functions from the prelude. -- $howto -- This module provides 'Middleware' to rewrite URL paths. It also provides -- functions that will convert a 'Request' to a modified 'Request'. -- Both operations require a function that takes URL parameters and -- headers, and returns new URL parameters. Parameters are pieces of URL -- paths and query parameters. -- -- If you are a new user of the library, use 'rewriteWithQueries' or -- 'rewritePureWithQueries' for middleware. For modifying 'Request's -- directly, use 'rewriteRequest' or 'rewriteRequestPure'. -- $semantics -- -- Versions of this library in wai-extra ≤ 3.0.16.1 exported only -- 'rewrite' and 'rewritePure' and both modified 'rawPathInfo' of the -- underlying requests. Such modification has been proscribed. The -- semantics of these functions have not changed; instead the recommended -- approach is to use 'rewriteWithQueries' and 'rewritePureWithQueries'. -- The new functions are slightly different, as described in the section -- on upgrading; code for previous library versions can be upgraded with -- a single change, and as the type of the new function is different the -- compiler will indicate where this change must be made. -- -- The 'rewriteRequest' and 'rewriteRequestPure' functions use the new -- semantics, too. -- $pathsandqueries -- -- This library defines the type synonym `PathsAndQueries` to make code -- handling paths and queries easier to read. -- -- /e.g./ /\/foo\/bar/ would look like -- -- > ["foo", "bar"] :: Text -- -- /?bar=baz/ would look like -- -- > [("bar", Just "baz")] :: QueryText -- -- Together, -- -- /\/foo?bar=baz/ would look like -- -- > (["foo"],[("bar", Just "baz")]) :: PathsAndQueries -- $takeover -- Let’s say we want to replace a website written in PHP with one written -- using WAI. We’ll use the -- <https://hackage.haskell.org/package/http-reverse-proxy http-reverse-proxy> -- package to serve the old -- site from the new site, but there’s a problem. The old site uses pages like -- -- @ -- index.php?page=/page/ -- @ -- -- whereas the new site would look like -- -- @ -- index\//page/ -- @ -- -- In doing this, we want to separate the migration code from our new -- website. So we’d like to handle links internally using the path -- formulation, but externally have the old links still work. -- -- Therefore, we will use middleware ('rewritePureWithQueries') from this -- module to rewrite incoming requests from the query formulation to the -- paths formulation. -- -- > {-# LANGUAGE ViewPatterns #-} -- > -- > rewritePathFromPhp :: Middleware -- > rewritePathFromPhp = rewritePureWithQueries pathFromPhp -- > -- > pathFromPhp :: PathsAndQueries -> H.RequestHeaders -> PathsAndQueries -- > pathFromPhp (pieces, queries) _ = piecesConvert pieces queries -- > where -- > piecesConvert :: [Text] -> H.Query -> PathsAndQueries -- > piecesConvert ["index.php"] qs@(join . lookup "page" -> Just page) = -- > ( ["index", TE.decodeUtf8With TE.lenientDecode page] -- > , delete ("page", pure page) qs -- > ) -- > piecesConvert ps qs = (ps, qs) -- -- On the other side, we will use 'rewriteRequestPure' to rewrite outgoing -- requests to the original website from the reverse proxy code (using the -- 'Network.HTTP.ReverseProxy.WPRModifiedRequest' or -- 'Network.HTTP.ReverseProxy.WPRModifiedRequestSecure' constructors. Note, -- these links will only work if the haddock documentation for -- <https://hackage.haskell.org/package/http-reverse-proxy http-reverse-proxy> -- is installed). -- -- > rewritePhpFromPath :: Request -> Request -- > rewritePhpFromPath = rewriteRequestPure phpFromPath -- > -- > phpFromPath :: PathsAndQueries -> H.RequestHeaders -> PathsAndQueries -- > phpFromPath (pieces, queries) _ = piecesConvert pieces queries -- > where -- > piecesConvert :: [Text] -> H.Query -> PathsAndQueries -- > piecesConvert ["index", page] qs = ( ["index.php"], ("page", pure . TE.encodeUtf8 $ page) : qs ) -- > piecesConvert ps qs = (ps, qs) -- -- For the whole example, see -- <https://gist.github.com/dbaynard/c844d0df124f68ec8b6da152c581ce6d>. -- $upgrading -- It is quite simple to upgrade from 'rewrite' and 'rewritePure', to -- 'rewriteWithQueries' and 'rewritePureWithQueries'. -- Insert 'Data.Bifunctor.first', which specialises to -- -- @ -- 'Data.Bifunctor.first' :: (['Text'] -> ['Text']) -> 'PathsAndQueries' -> 'PathsAndQueries' -- @ -- -- as the following example demonstrates. -- -- Old versions of the libary could only handle path pieces, not queries. -- This could have been supplied to 'rewritePure'. -- -- @ -- staticConvert' :: [Text] -> H.RequestHeaders -> [Text] -- staticConvert' pieces _ = piecesConvert pieces -- where -- piecesConvert [] = ["static", "html", "pages.html"] -- piecesConvert route@("pages":_) = "static":"html":route -- @ -- -- Instead, use this function, supplied to 'rewritePureWithQueries'. -- -- @ -- staticConvert :: 'PathsAndQueries' -> H.RequestHeaders -> 'PathsAndQueries' -- staticConvert pathsAndQueries _ = 'Data.Bifunctor.first' piecesConvert pathsAndQueries -- where -- piecesConvert [] = ["static", "html", "pages.html"] -- piecesConvert route@("pages":_) = "static":"html":route -- @ -- -- The former formulation is deprecated for two reasons: -- -- 1. The original formulation of 'rewrite' modified 'rawPathInfo', which -- is deprecated behaviour. -- -- 2. The original formulation did not allow query parameters to -- influence the path. -- -- Concerning the first point, take care with semantics of your program when -- upgrading as the upgraded functions no longer modify 'rawPathInfo'. -------------------------------------------------- -- * Types -------------------------------------------------- -- | A tuple of the path sections as ['Text'] and query parameters as -- 'H.Query'. This makes writing type signatures for the conversion -- function far more pleasant. -- -- Note that this uses 'H.Query' not 'H.QueryText' to more accurately -- reflect the paramaters that can be supplied in URLs. It may be safe to -- treat parameters as text; use the 'H.queryToQueryText' and -- 'H.queryTextToQuery' functions to interconvert. type PathsAndQueries = ([Text], H.Query) -------------------------------------------------- -- * Rewriting 'Middleware' -------------------------------------------------- -- | Rewrite based on your own conversion function for paths only, to be -- supplied by users of this library (with the conversion operating in 'IO'). -- -- For new code, use 'rewriteWithQueries' instead. rewrite :: ([Text] -> H.RequestHeaders -> IO [Text]) -> Middleware rewrite convert app req sendResponse = do let convertIO = pathsOnly . curry $ liftIO . uncurry convert newReq <- rewriteRequestRawM convertIO req app newReq sendResponse {-# WARNING rewrite "This modifies the 'rawPathInfo' field of a 'Request'. This is not recommended behaviour; it is however how this function has worked in the past. Use 'rewriteWithQueries' instead" #-} -- | Rewrite based on pure conversion function for paths only, to be -- supplied by users of this library. -- -- For new code, use 'rewritePureWithQueries' instead. rewritePure :: ([Text] -> H.RequestHeaders -> [Text]) -> Middleware rewritePure convert app req = let convertPure = pathsOnly . curry $ Identity . uncurry convert newReq = runIdentity $ rewriteRequestRawM convertPure req in app newReq {-# WARNING rewritePure "This modifies the 'rawPathInfo' field of a 'Request'. This is not recommended behaviour; it is however how this function has worked in the past. Use 'rewritePureWithQueries' instead" #-} -- | Rewrite based on your own conversion function for paths and queries. -- This function is to be supplied by users of this library, and operates -- in 'IO'. rewriteWithQueries :: (PathsAndQueries -> H.RequestHeaders -> IO PathsAndQueries) -> Middleware rewriteWithQueries convert app req sendResponse = do newReq <- rewriteRequestM convert req app newReq sendResponse -- | Rewrite based on pure conversion function for paths and queries. This -- function is to be supplied by users of this library. rewritePureWithQueries :: (PathsAndQueries -> H.RequestHeaders -> PathsAndQueries) -> Middleware rewritePureWithQueries convert app req = app $ rewriteRequestPure convert req -------------------------------------------------- -- * Modifying 'Request's directly -------------------------------------------------- -- | Modify a 'Request' using the supplied function in 'IO'. This is suitable for -- the reverse proxy example. rewriteRequest :: (PathsAndQueries -> H.RequestHeaders -> IO PathsAndQueries) -> Request -> IO Request rewriteRequest convert req = let convertIO = curry $ liftIO . uncurry convert in rewriteRequestRawM convertIO req -- | Modify a 'Request' using the pure supplied function. This is suitable for -- the reverse proxy example. rewriteRequestPure :: (PathsAndQueries -> H.RequestHeaders -> PathsAndQueries) -> Request -> Request rewriteRequestPure convert req = let convertPure = curry $ Identity . uncurry convert in runIdentity $ rewriteRequestRawM convertPure req -------------------------------------------------- -- * Helper functions -------------------------------------------------- -- | This helper function factors out the common behaviour of rewriting requests. rewriteRequestM :: (Applicative m, Monad m) => (PathsAndQueries -> H.RequestHeaders -> m PathsAndQueries) -> Request -> m Request rewriteRequestM convert req = do (pInfo, qByteStrings) <- curry convert (pathInfo req) (queryString req) (requestHeaders req) pure req {pathInfo = pInfo, queryString = qByteStrings} -- | This helper function preserves the semantics of wai-extra ≤ 3.0, in -- which the rewrite functions modify the 'rawPathInfo' parameter. Note -- that this has not been extended to modify the 'rawQueryInfo' as -- modifying either of these values has been deprecated. rewriteRequestRawM :: (Applicative m, Monad m) => (PathsAndQueries -> H.RequestHeaders -> m PathsAndQueries) -> Request -> m Request rewriteRequestRawM convert req = do newReq <- rewriteRequestM convert req let rawPInfo = TE.encodeUtf8 . T.intercalate "/" . pathInfo $ newReq pure newReq { rawPathInfo = rawPInfo } {-# WARNING rewriteRequestRawM "This modifies the 'rawPathInfo' field of a 'Request'. This is not recommended behaviour; it is however how this function has worked in the past. Use 'rewriteRequestM' instead" #-} -- | Produce a function that works on 'PathsAndQueries' from one working -- only on paths. This is not exported, as it is only needed to handle -- code written for versions ≤ 3.0 of the library; see the -- example above using 'Data.Bifunctor.first' to do something similar. pathsOnly :: (Applicative m, Monad m) => ([Text] -> H.RequestHeaders -> m [Text]) -> PathsAndQueries -> H.RequestHeaders -> m PathsAndQueries pathsOnly convert psAndQs headers = (,[]) <$> convert (fst psAndQs) headers {-# INLINE pathsOnly #-}
phischu/fragnix
tests/packages/scotty/Network.Wai.Middleware.Rewrite.hs
bsd-3-clause
12,413
0
14
2,325
1,058
654
404
70
1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} -- | Parameter parsing/template haskell code. module DataAnalysis.Application.Params where import Control.Applicative import "mtl" Control.Monad.Error () import Data.Char import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T -- | A parameter specification. data Parameter = Parameter { paramName :: !String , paramType :: !String , paramMin :: !(Maybe String) , paramMax :: !(Maybe String) , paramDesc :: !String , paramDef :: !(Maybe String) } -- | Parse a parameter spec from tokens. fromTokens :: [Token] -> Either String Parameter fromTokens xs@(Token name:Spaces{}:Token typ:_) = Parameter <$> pure (T.unpack name) <*> pure (T.unpack typ) <*> opt asis "min" <*> opt asis "max" <*> text "desc" <*> opt asis "default" where asis = Right opt :: (String -> Either String a) -> Text -> Either String (Maybe a) opt cont name = do mv <- optional (text name) case mv of Nothing -> return Nothing Just t -> fmap Just (cont t) text :: Text -> Either String String text name = maybe (Left ("Expected argument: " <> T.unpack name <> "=<value>")) (Right . T.unpack) (listToMaybe (mapMaybe match xs)) where match tok = case tok of Token t -> case T.span (/='=') t of (key,value) | key == name && T.isPrefixOf "=" value -> Just (T.drop 1 value) _ -> Nothing _ -> Nothing fromTokens _ = Left "Parameter format: <name> <type> [arg1=value1 argn=valuen …]" -- | A token used by the parser. data Token = Spaces !Int -- ^ @Spaces n@ are @n@ consecutive spaces. | Token Text -- ^ @Token tok@ is token @tok@ already unquoted. deriving (Show, Eq) -- | Tokenize a string. tokenize :: Text -> [Token] tokenize t | T.null t = [] | "--" `T.isPrefixOf` t = [] -- Comment until the end of the line. | "#" `T.isPrefixOf` t = [] -- Also comment to the end of the -- line, needed for a CPP bug (#110) | T.head t == '"' = quotes (T.tail t) id | T.head t == '(' = parens 1 (T.tail t) id | isSpace (T.head t) = let (spaces, rest) = T.span isSpace t in Spaces (T.length spaces) : tokenize rest -- support mid-token quotes and parens | Just (beforeEquals, afterEquals) <- findMidToken t , not (T.any isSpace beforeEquals) , Token next : rest <- tokenize afterEquals = Token (T.concat [beforeEquals, "=", next]) : rest | otherwise = let (token, rest) = T.break isSpace t in Token token : tokenize rest where findMidToken t' = case T.break (== '=') t' of (x, T.drop 1 -> y) | "\"" `T.isPrefixOf` y || "(" `T.isPrefixOf` y -> Just (x, y) _ -> Nothing quotes t' front | T.null t' = error $ T.unpack $ T.concat $ "Unterminated quoted string starting with " : front [] | T.head t' == '"' = Token (T.concat $ front []) : tokenize (T.tail t') | T.head t' == '\\' && T.length t' > 1 = quotes (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):)) | otherwise = let (x, y) = T.break (`elem` "\\\"") t' in quotes y (front . (x:)) parens count t' front | T.null t' = error $ T.unpack $ T.concat $ "Unterminated parens string starting with " : front [] | T.head t' == ')' = if count == (1 :: Int) then Token (T.concat $ front []) : tokenize (T.tail t') else parens (count - 1) (T.tail t') (front . (")":)) | T.head t' == '(' = parens (count + 1) (T.tail t') (front . ("(":)) | T.head t' == '\\' && T.length t' > 1 = parens count (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):)) | otherwise = let (x, y) = T.break (`elem` "\\()") t' in parens count y (front . (x:))
teuffy/min-var-ci
src/DataAnalysis/Application/Params.hs
mit
4,419
0
20
1,509
1,543
779
764
112
4
{-# LANGUAGE ExistentialQuantification, PatternSynonyms, PolyKinds, TypeOperators #-} -- | Testing some pattern synonyms module PatternSyns where -- | FooType doc data FooType x = FooCtor x -- | Pattern synonym for 'Foo' x pattern Foo x = FooCtor x -- | Pattern synonym for 'Bar' x pattern Bar x = FooCtor (Foo x) -- | Pattern synonym for (':<->') pattern x :<-> y = (Foo x, Bar y) -- | BlubType is existentially quantified data BlubType = forall x. Show x => BlubCtor x -- | Pattern synonym for 'Blub' x pattern Blub x = BlubCtor x -- | Doc for ('><') data (a :: *) >< b = Empty -- | Pattern for 'Empty' pattern E = Empty -- | Earlier ghc versions didn't allow explicit signatures -- on pattern synonyms. pattern PatWithExplicitSig :: Eq somex => somex -> FooType somex pattern PatWithExplicitSig x = FooCtor x
Fuuzetsu/haddock
html-test/src/PatternSyns.hs
bsd-2-clause
822
0
8
158
178
95
83
12
0
{-# LANGUAGE CPP, LambdaCase, BangPatterns, MagicHash, TupleSections, ScopedTypeVariables #-} {-# OPTIONS_GHC -w #-} -- Suppress warnings for unimplemented methods ------------- WARNING --------------------- -- -- This program is utterly bogus. It takes a value of type () -- and unsafe-coerces it to a function, and applies it. -- This is caught by an ASSERT with a debug compiler. -- -- See #9208 for discussion -- -------------------------------------------- {- | Evaluate Template Haskell splices on node.js, using pipes to communicate with GHCJS -} -- module GHCJS.Prim.TH.Eval module Eval ( runTHServer ) where import Control.Applicative import Control.Monad #if __GLASGOW_HASKELL__ >= 800 import Control.Monad.Fail (MonadFail(fail)) #endif import Control.Monad.IO.Class (MonadIO (..)) import Data.Binary import Data.Binary.Get import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import GHC.Base (Any) import qualified Language.Haskell.TH as TH import qualified Language.Haskell.TH.Syntax as TH import Unsafe.Coerce data THResultType = THExp | THPat | THType | THDec data Message -- | GHCJS compiler to node.js requests = RunTH THResultType ByteString TH.Loc -- | node.js to GHCJS compiler responses | RunTH' THResultType ByteString [TH.Dec] -- ^ serialized AST and additional toplevel declarations instance Binary THResultType where put _ = return () get = return undefined instance Binary Message where put _ = return () get = return undefined data QState = QState data GHCJSQ a = GHCJSQ { runGHCJSQ :: QState -> IO (a, QState) } instance Functor GHCJSQ where fmap f (GHCJSQ s) = GHCJSQ $ fmap (\(x,s') -> (f x,s')) . s instance Applicative GHCJSQ where f <*> a = GHCJSQ $ \s -> do (f',s') <- runGHCJSQ f s (a', s'') <- runGHCJSQ a s' return (f' a', s'') pure x = GHCJSQ (\s -> return (x,s)) instance Monad GHCJSQ where (>>=) m f = GHCJSQ $ \s -> do (m', s') <- runGHCJSQ m s (a, s'') <- runGHCJSQ (f m') s' return (a, s'') return = pure #if __GLASGOW_HASKELL__ >= 800 instance MonadFail GHCJSQ where fail = undefined #endif instance MonadIO GHCJSQ where liftIO m = GHCJSQ $ \s -> fmap (,s) m instance TH.Quasi GHCJSQ -- | the Template Haskell server runTHServer :: IO () runTHServer = void $ runGHCJSQ server QState where server = TH.qRunIO awaitMessage >>= \case RunTH t code loc -> do a <- TH.qRunIO $ loadTHData code runTH t a loc _ -> TH.qRunIO (putStrLn "warning: ignoring unexpected message type") runTH :: THResultType -> Any -> TH.Loc -> GHCJSQ () runTH rt obj loc = do res <- case rt of THExp -> runTHCode (unsafeCoerce obj :: TH.Q TH.Exp) THPat -> runTHCode (unsafeCoerce obj :: TH.Q TH.Pat) THType -> runTHCode (unsafeCoerce obj :: TH.Q TH.Type) THDec -> runTHCode (unsafeCoerce obj :: TH.Q [TH.Dec]) TH.qRunIO (sendResult $ RunTH' rt res []) runTHCode :: {- Binary a => -} TH.Q a -> GHCJSQ ByteString runTHCode c = TH.runQ c >> return B.empty loadTHData :: ByteString -> IO Any loadTHData bs = return (unsafeCoerce ()) awaitMessage :: IO Message awaitMessage = fmap (runGet get) (return BL.empty) -- | send result back sendResult :: Message -> IO () sendResult msg = return ()
sdiehl/ghc
testsuite/tests/stranal/should_compile/T9208.hs
bsd-3-clause
3,510
0
15
854
995
534
461
67
4
{-# OPTIONS_JHC -fno-prelude -fffi #-} -- just a few basic operations on integers to jumpstart things module Jhc.Int(Int(),Int_(),increment,decrement,plus,minus,times,quotient,remainder,zero,one,boxInt,unboxInt) where import Jhc.Type.Word(Int(),Int_()) foreign import primitive increment :: Int -> Int foreign import primitive decrement :: Int -> Int foreign import primitive "Add" plus :: Int -> Int -> Int foreign import primitive "Sub" minus :: Int -> Int -> Int foreign import primitive "Mul" times :: Int -> Int -> Int foreign import primitive "Quot" quotient :: Int -> Int -> Int foreign import primitive "Rem" remainder :: Int -> Int -> Int foreign import primitive zero :: Int foreign import primitive one :: Int foreign import primitive "box" boxInt :: Int_ -> Int foreign import primitive "unbox" unboxInt :: Int -> Int_
m-alvarez/jhc
lib/jhc/Jhc/Int.hs
mit
883
5
7
174
260
150
110
-1
-1
import Test.QuickCheck import System.IO.Unsafe import Control.Concurrent.Chan import Control.Concurrent import Control.Monad data Action = NewChan | ReadChan | WriteChan Int | IsEmptyChan | ReturnInt Int | ReturnBool Bool deriving (Eq,Show) main = do t <- myThreadId forkIO (threadDelay 1000000 >> killThread t) -- just in case we deadlock testChan testChan :: IO () testChan = do quickCheck prop_NewIs_NewRet quickCheck prop_NewWriteIs_NewRet quickCheck prop_NewWriteRead_NewRet prop_NewIs_NewRet = [NewChan,IsEmptyChan] =^ [NewChan,ReturnBool True] prop_NewWriteIs_NewRet n = [NewChan,WriteChan n,IsEmptyChan] =^ [NewChan,WriteChan n,ReturnBool False] prop_NewWriteRead_NewRet n = [NewChan,WriteChan n,ReadChan] =^ [NewChan,ReturnInt n] perform :: [Action] -> IO ([Bool],[Int]) perform [] = return ([],[]) perform (a:as) = case a of ReturnInt v -> liftM (\(b,l) -> (b,v:l)) (perform as) ReturnBool v -> liftM (\(b,l) -> (v:b,l)) (perform as) NewChan -> newChan >>= \chan -> perform' chan as _ -> error $ "Please use NewChan as first action" perform' :: Chan Int -> [Action] -> IO ([Bool],[Int]) perform' _ [] = return ([],[]) perform' chan (a:as) = case a of ReturnInt v -> liftM (\(b,l) -> (b,v:l)) (perform' chan as) ReturnBool v -> liftM (\(b,l) -> (v:b,l)) (perform' chan as) ReadChan -> liftM2 (\v (b,l) -> (b,v:l)) (readChan chan) (perform' chan as) WriteChan n -> writeChan chan n >> perform' chan as IsEmptyChan -> liftM2 (\v (b,l) -> (v:b,l)) (isEmptyChan chan) (perform' chan as) _ -> error $ "If you want to use " ++ show a ++ " please use the =^ operator" actions :: Gen [Action] actions = liftM (NewChan:) (actions' 0) actions' :: Int -> Gen [Action] actions' contents = oneof ([return [], liftM (IsEmptyChan:) (actions' contents), liftM2 (:) (liftM WriteChan arbitrary) (actions' (contents+1))] ++ if contents==0 then [] else [liftM (ReadChan:) (actions' (contents-1))]) (=^) :: [Action] -> [Action] -> Property c =^ c' = forAll (actions' (delta 0 c)) (\suff -> observe c suff == observe c' suff) where observe x suff = unsafePerformIO (perform (x++suff)) (^=^) :: [Action] -> [Action] -> Property c ^=^ c' = forAll actions (\pref -> forAll (actions' (delta 0 (pref++c))) (\suff -> observe c pref suff == observe c' pref suff)) where observe x pref suff = unsafePerformIO (perform (pref++x++suff)) delta :: Int -> [Action] -> Int delta i [] = i delta i (ReturnInt _:as) = delta i as delta i (ReturnBool _:as) = delta i as delta _ (NewChan:as) = delta 0 as delta i (WriteChan _:as) = delta (i+1) as delta i (ReadChan:as) = delta (if i==0 then error "read on empty Chan" else i-1) as delta i (IsEmptyChan:as) = delta i as
ezyang/ghc
libraries/base/tests/Concurrent/Chan001.hs
bsd-3-clause
3,113
0
14
893
1,332
703
629
78
6
import Control.Concurrent import Control.Exception main = do m <- newEmptyMVar t <- forkIO (mask_ $ takeMVar m) threadDelay 100000 throwTo t (ErrorCall "I'm Interruptible") threadDelay 100000 putMVar m () -- to avoid t being garbage collected
urbanslug/ghc
testsuite/tests/concurrent/should_run/conc020.hs
bsd-3-clause
257
0
11
50
80
36
44
9
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} module Haarss.View (viewModel) where import Control.Lens import Data.Char (chr) import Data.Foldable (toList) import Data.Maybe (fromMaybe) import Data.Sequence (Seq) import Data.Text (Text) import qualified Data.Text as T import Data.Version (showVersion) import Graphics.Vty hiding (resize) import Network.HTTP.Types.Status import Numeric (readHex) import Paths_haarss (version) import Haarss.Feed.Annotated import Haarss.Fetching.History import Haarss.Interface import Haarss.Model hiding (update) import Haarss.Model.Window import Yeast.Feed ------------------------------------------------------------------------ viewModel :: Vty -> Model -> IO () viewModel v = update v . picForImage . render {- renderDebug :: Model -> Image renderDebug m = vertCat [ separator , drawList (string defAttr) (lines (show m)) , string defAttr "" , string defAttr ("Height: " ++ show h) ] where (_, h) = m^.displayRegion -} render :: Model -> Image render m = vertCat [ bar $ T.pack $ " haarss " ++ showVersion version , separator , resizeHeight (h - 5) (drawModel m) , separator , bar (T.pack (status (m^.downloading) (m^.prompt))) , separator ] where (_, h) = m^.displayRegion status :: Int -> Maybe (Prompt, String) -> String status 0 Nothing = "" status n Nothing = " Downloading (" ++ show n ++ " feed" ++ (if n == 1 then "" else "s") ++ " to go)" status 0 (Just (p, s)) = " " ++ show p ++ ": " ++ s status _ _ = error "Impossible." be :: (Contravariant f, Profunctor p) => a -> Optical' p p f (Maybe a) a be x = to (fromMaybe x) drawModel :: Model -> Image drawModel m = case m^.browsing.focus of TheFeed _ -> drawWin (m^.feeds) (feedImage w defAttr) (feedImage w standoutAttr) TheItems f is -> vertCat [ attributed boldAttr (desc f^.be "") , separator , drawWin is (itemImage defAttr boldAttr w) (itemImage standoutAttr standoutBoldAttr w) ] TheText f is sds -> vertCat [ attributed boldAttr (desc f^.be "") , separator , attributed defAttr (T.center (w - 1) ' ' (is^.focus.item.title.be "")) , separator , drawList (\t -> char defAttr ' ' <|> attributed defAttr t) $ is^.focus.item.description.be "(no desc)".to (scrollText sds . concatMap (fmt (min 60 w)) . T.lines . removeHtml) ] where (w, h) = m^.displayRegion desc :: AnnFeed -> Maybe Text desc f = asumOf both (f^.feed.description, f^.feed.title) -- XXX: Why do we need to add the blank line? scrollText :: [ScrollDir] -> [Text] -> [Text] scrollText sds ts = "" : drop scrollLines ts where scrollLines :: Int scrollLines = foldr (helper (h - 10) (length ts)) 0 sds where helper :: Int -> Int -> ScrollDir -> Int -> Int helper sz mx DownFull ih | ih + sz >= mx = ih | otherwise = ih + sz helper sz mx DownHalf ih | ih + (sz `div` 2) >= mx = ih | otherwise = ih + sz `div` 2 helper sz _ UpFull ih | ih - sz <= 0 = 0 | otherwise = ih - sz helper sz _ UpHalf ih | ih - (sz `div` 2) <= 0 = 0 | otherwise = ih - sz `div` 2 ------------------------------------------------------------------------ drawWin :: Window a -> (a -> Image) -> (a -> Image) -> Image drawWin w e f = vertCat [ drawSeq e (w^.prev) , w^.focus.to f , drawSeq e (w^.next) ] where drawSeq :: (a -> Image) -> Seq a -> Image drawSeq f' = vertCat . toList . fmap f' drawList :: (a -> Image) -> [a] -> Image drawList f = vertCat . map f failedImage :: Attr -> AnnFeed -> Image failedImage attr f = char attr $ case f^.history of [] -> ' ' Success _ : _ -> ' ' hs | length hs >= 10 && all isFailure hs -> '☠' Failure _ (DownloadFailure (StatusCodeException' s)) : _ | s == movedPermanently301 -> 'M' | s == notModified304 -> ' ' | s == notFound404 -> 'X' | s == forbidden403 -> 'F' | s == requestTimeout408 -> 'T' | s == internalServerError500 -> 'I' | otherwise -> '!' Failure _ (DownloadFailure OtherException) : _ -> '?' Failure _ (ParseFailure _) : _ -> 'P' Failure _ TimeoutFailure : _ -> '⌛' Failure _ UnknownFailure : _ -> '?' where isFailure (Failure _ _) = True isFailure _ = False feedImage :: Int -> Attr -> AnnFeed -> Image feedImage w attr f = horizCat [ failedImage attr f , text' attr tit , charFill attr ' ' (w - T.length tit - T.length unread - 3) 1 , attributed attr unread , charFill attr ' ' (1 :: Int) 1 ] where tit :: Text tit = (asumOf both (f^.alias, f^.feed.title))^.be "no title" unread :: Text unread = f^.feed.items.to (T.pack . (\s -> if s == "0" then "" else s ++ " new") . show . length . filter (not._isRead)) itemImage :: Attr -> Attr -> Int -> AnnItem -> Image itemImage r n w i = horizCat [ attributed attr (i^.item.title.be "no title") , charFill r ' ' w 1 ] where attr :: Attr attr | i^.isRead = r | otherwise = n ------------------------------------------------------------------------ standoutAttr, boldAttr, standoutBoldAttr :: Attr standoutAttr = defAttr `withStyle` standout boldAttr = defAttr `withStyle` bold standoutBoldAttr = standoutAttr `withStyle` bold bar :: Text -> Image bar t = text' standoutAttr t <|> charFill standoutAttr ' ' (200 :: Int) 1 separator :: Image separator = char defAttr ' ' attributed :: Attr -> Text -> Image attributed attr t = char attr ' ' <|> text' attr t ------------------------------------------------------------------------ fmt :: Int -> Text -> [Text] fmt maxLen = map T.unwords . go 0 [] . T.words where go :: Int -> [Text] -> [Text] -> [[Text]] go _ acc [] = [reverse acc] go rowLen acc (w : ws) | rowLen + wl + 1 > maxLen = reverse acc : go wl [w] ws | otherwise = go (rowLen + wl + 1) (w : acc) ws where wl = T.length w removeHtml :: Text -> Text removeHtml = go "" where go :: String -> Text -> Text go acc (T.uncons -> Nothing) = T.pack $ reverse acc go acc (T.uncons -> Just ('<', t)) = case T.break (== '>') t & _2 %~ T.uncons of -- XXX: fmt removes the newlines... ("p", Just ('>', t')) -> go ('\n' : '\n' : acc) t' -- XXX: might want to drop everything inside the style tag... ("style", Just ('>', t')) -> go acc t' (_, Just ('>', t')) -> go acc t' (tag, _) -> T.pack $ reverse acc ++ T.unpack tag ++ "[>]" go acc (T.uncons -> Just ('&', t0)) = case T.break (== ';') t0 & _2 %~ T.uncons of (code, Just (';', t')) -> go (maybe ('&' : T.unpack code ++";"++ acc) (: acc) (decode code)) t' (code, _) -> T.pack $ reverse acc ++ '&' : T.unpack code ++ "[;]" where decode :: Text -> Maybe Char decode "amp" = Just '&' decode "gt" = Just '>' decode "lt" = Just '<' decode "mdash" = Just '—' decode "nbsp" = Just ' ' decode "ndash" = Just '–' decode "quot" = Just '"' decode (T.unpack -> '#' : 'x' : hex) = fromHex hex decode (T.unpack -> '#' : 'X' : hex) = fromHex hex decode (T.unpack -> '#' : dec) = Just $ chr $ read dec decode _ = Nothing fromHex :: String -> Maybe Char fromHex s = case readHex s of [(i, "")] -> Just $ chr i _ -> Nothing go acc (T.uncons -> Just (c, t)) = go (c : acc) t go _ (T.uncons -> _) = error "Impossible."
stevana/haarss
src/Haarss/View.hs
isc
8,948
0
20
3,411
3,006
1,550
1,456
-1
-1
module Util.Numeric where import Util.Display import qualified Util.Unicode as U subscriptNumber :: Integer -> String subscriptNumber x = map U.subscriptDigit $ x `digitsInBase` 10 superscriptNumber :: Integer -> String superscriptNumber x = map U.superscriptDigit $ x `digitsInBase` 10 showBinary :: Integral a => a -> String showBinary x = map (\d -> if d == 1 then '1' else '0') $ numBaseDigits $ asBinary x numBaseDigits :: NumBase -> [Integer] numBaseDigits (NumBase xs _) = xs data NumBase = NumBase [Integer] Integer deriving Show instance Display NumBase where display nb = displayNumBase nb displayNumBase (NumBase ds b) | b > 10 = error "Character representation of digits larger than 9 is undefined" | otherwise = (concat $ map show ds) ++ (subscriptNumber b) inBase :: Integer -> Integer -> NumBase inBase x b = NumBase (x `digitsInBase` b) b evaluate :: NumBase -> Integer evaluate (NumBase xs b) = snd $ foldr f (1, 0) xs where f a (m, sum) = (m * b, sum + m * a) asBinary :: Integral a => a -> NumBase asBinary x = NumBase ((toInteger x) `digitsInBase` 2) 2 digitsInBase :: Integer -> Integer -> [Integer] digitsInBase 0 b = [0] digitsInBase x b = dIB x b where dIB x b | x == 0 = [] | otherwise = (x' `dIB` b) ++ [r] where (x', r) = x `divMod` b changeToBase :: NumBase -> Integer -> NumBase changeToBase (NumBase xs _) b = NumBase xs b powerRemainder :: Integer -> Integer -> (Integer, Integer) powerRemainder x b = (m, x - (toInteger $ b ^ m)) where m = floor $ logBase (fromInteger b) (fromInteger x) unbool :: Integral a => Bool -> a unbool True = 1 unbool False = 0 bool :: Integral a => a -> Bool bool 0 = False bool 1 = True bool _ = error "Coercing integers other than 0 and 1 to boolean values is not allowed"
sgord512/Utilities
Util/Numeric.hs
mit
1,823
0
11
414
726
381
345
41
2
-- | Common handler functions. module Handler.Common where import Data.FileEmbed (embedFile) import Import -- These handlers embed files in the executable at compile time to avoid a -- runtime dependency, and for efficiency. getFaviconR :: Handler TypedContent getFaviconR = do cacheSeconds $ 60 * 60 * 24 * 30 -- cache for a month return . TypedContent "image/x-icon" $ toContent $(embedFile "config/favicon.ico") getRobotsR :: Handler TypedContent getRobotsR = return . TypedContent typePlain $ toContent $(embedFile "config/robots.txt")
Tehnix/campaigns
Handler/Common.hs
mit
577
0
11
113
113
58
55
11
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE ScopedTypeVariables #-} import Control.Monad (unless) import Criterion.Main import Data.Monoid (Endo(..)) import Data.Vinyl import Data.Vinyl.Syntax () import Lens.Micro ((%~), (&)) import System.Exit (exitFailure) import Bench.ARec import Bench.SRec import Bench.Rec data HaskRec = HaskRec { a0 :: Int, a1 :: Int, a2 :: Int, a3 :: Int, a4 :: Int, a5 :: Int, a6 :: Int, a7 :: Int, a8 :: Int, a9 :: Int, a10 :: Int, a11 :: Int, a12 :: Int, a13 :: Int, a14 :: Int, a15 :: Int } deriving Show haskRec :: HaskRec haskRec = HaskRec 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 99 sumHaskRec r = a0 r + a1 r + a2 r + a3 r + a4 r + a5 r + a6 r + a7 r + a8 r + a9 r + a10 r + a11 r + a12 r + a13 r + a14 r + a15 r data StrictHaskRec = StrictHaskRec { sa0 :: !Int, sa1 :: !Int, sa2 :: !Int, sa3 :: !Int, sa4 :: !Int, sa5 :: !Int, sa6 :: !Int, sa7 :: !Int, sa8 :: !Int, sa9 :: !Int, sa10 :: !Int, sa11 :: !Int, sa12 :: !Int, sa13 :: !Int, sa14 :: !Int, sa15 :: !Int } shaskRec :: StrictHaskRec shaskRec = StrictHaskRec 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 99 sumSHaskRec r = sa0 r + sa1 r + sa2 r + sa3 r + sa4 r + sa5 r + sa6 r + sa7 r + sa8 r + sa9 r + sa10 r + sa11 r + sa12 r + sa13 r + sa14 r + sa15 r data UStrictHaskRec = UStrictHaskRec { usa0 :: {-# UNPACK #-} !Int, usa1 :: {-# UNPACK #-} !Int, usa2 :: {-# UNPACK #-} !Int, usa3 :: {-# UNPACK #-} !Int, usa4 :: {-# UNPACK #-} !Int, usa5 :: {-# UNPACK #-} !Int, usa6 :: {-# UNPACK #-} !Int, usa7 :: {-# UNPACK #-} !Int, usa8 :: {-# UNPACK #-} !Int, usa9 :: {-# UNPACK #-} !Int, usa10 :: {-# UNPACK #-} !Int, usa11 :: {-# UNPACK #-} !Int, usa12 :: {-# UNPACK #-} !Int, usa13 :: {-# UNPACK #-} !Int, usa14 :: {-# UNPACK #-} !Int, usa15 :: {-# UNPACK #-} !Int } ushaskRec :: UStrictHaskRec ushaskRec = UStrictHaskRec 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 99 sumUSHaskRec r = usa0 r + usa1 r + usa2 r + usa3 r + usa4 r + usa5 r + usa6 r + usa7 r + usa8 r + usa9 r + usa10 r + usa11 r + usa12 r + usa13 r + usa14 r + usa15 r type SubFields = '[ '("a0", Int), '("a8", Int), '("a15", Int)] -- updateSRec :: forall record. RecordSubset record ElField SubFields Fields -- => record ElField Fields -> record ElField Fields updateSRec :: SRec ElField Fields -> SRec ElField Fields updateSRec = rsubset %~ appEndo aux where aux :: Endo (SRec ElField SubFields) aux = Endo (\r -> r & #a15 %~ (+ 2) & #a8 %~ (+ 3) & #a0 %~ (+ 4)) updateARec :: ARec ElField Fields -> ARec ElField Fields updateARec = rsubset %~ appEndo aux where aux :: Endo (ARec ElField SubFields) aux = Endo (\r -> r & #a15 %~ (+ 2) & #a8 %~ (+ 3) & #a0 %~ (+ 4)) updateRec :: Rec ElField Fields -> Rec ElField Fields updateRec = rsubset %~ appEndo aux where aux :: Endo (Rec ElField SubFields) aux = Endo (\r -> r & #a15 %~ (+ 2) & #a8 %~ (+ 3) & #a0 %~ (+ 4)) data SubRec = SubRec { suba0 :: Int, suba8 :: Int, suba15 :: Int } updateHaskRec :: HaskRec -> HaskRec updateHaskRec r = r { a0 = suba0 s, a8 = suba8 s, a15 = suba15 s } where s = aux (SubRec (a0 r) (a8 r) (a15 r)) aux r' = r' { suba0 = suba0 r' + 4, suba8 = suba8 r' + 3, suba15 = suba15 r' + 2 } main :: IO () main = do let newF = mkRec 0 arec = toARec newF srec = toSRec newF unless (rvalf #a15 arec == rvalf #a15 newF) (do putStrLn "AFieldRec accessor disagrees with rvalf" exitFailure) unless (rvalf #a15 srec == rvalf #a15 newF) (do putStrLn "SFieldRec accessor disagrees with rvalf" exitFailure) let srec' = updateSRec srec haskRec' = updateHaskRec haskRec arec' = updateARec arec unless (rvalf #a0 srec' == a0 haskRec' && a0 haskRec' == 4 && rvalf #a8 srec' == a8 haskRec' && a8 haskRec' == 3 && rvalf #a15 srec' == a15 haskRec' && a15 haskRec' == 101) (do putStrLn "SRec and Haskell Record updates disagree" exitFailure) unless (rvalf #a0 arec' == 4 && rvalf #a8 arec' == 3 && rvalf #a15 arec' == 101) (do putStrLn "ARec record updates are inconsistent" exitFailure) defaultMain [ bgroup "Update" [ bench "Haskell Record" $ nf (a15 . updateHaskRec) haskRec , bench "Rec" $ nf (rvalf #a15 . updateRec) newF , bench "ARec" $ nf (rvalf #a15 . updateARec) arec , bench "SRec" $ nf (rvalf #a15 . updateSRec) srec ] , bgroup "creating" [ bench "vinyl record" $ whnf mkRec 0 , bench "toSRec" $ whnf mkToSRec 0 , bench "New style ARec with toARec " $ whnf mkToARec 0 , bench "New style ARec with arec " $ whnf mkARec 0 ] ,bgroup "sums" [ bench "haskell record" $ nf sumHaskRec haskRec , bench "strict haskell record" $ whnf sumSHaskRec shaskRec , bench "unboxed strict haskell record" $ whnf sumUSHaskRec ushaskRec , bench "vinyl SRec" $ nf sumSRec srec , bench "vinyl Rec" $ nf sumRec newF , bench "vinyl ARec" $ nf sumARec arec ] , bgroup "FieldRec" [ bench "a0" $ nf (rvalf #a0) newF , bench "a4" $ nf (rvalf #a4) newF , bench "a8" $ nf (rvalf #a8) newF , bench "a12" $ nf (rvalf #a12) newF , bench "a15" $ nf (rvalf #a15) newF ] , bgroup "AFieldRec" [ bench "a0" $ nf (rvalf #a0) arec -- , bench "a4" $ nf (rvalf #a4) arec -- , bench "a8" $ nf (rvalf #a8) arec -- , bench "a12" $ nf (rvalf #a12) arec , bench "a15" $ nf (rvalf #a15) arec ] , bgroup "SFieldRec" [ bench "a0" $ nf (rvalf #a0) srec -- , bench "a4" $ nf (rvalf #a4) srec -- , bench "a8" $ nf (rvalf #a8) srec -- , bench "a12" $ nf (rvalf #a12) srec , bench "a15" $ nf (rvalf #a15) srec ] , bgroup "Haskell Record" [ bench "a0" $ nf a0 haskRec -- , bench "a4" $ nf a4 haskRec -- , bench "a8" $ nf a8 haskRec -- , bench "a12" $ nf a12 haskRec , bench "a15" $ nf a15 haskRec ] , bgroup "Strict Haskell Record" [ bench "a0" $ nf sa0 shaskRec -- , bench "a4" $ nf sa4 shaskRec -- , bench "a8" $ nf sa8 shaskRec -- , bench "a12" $ nf sa12 shaskRec , bench "a15" $ nf sa15 shaskRec ] , bgroup "Unpacked Strict Haskell Record" [ bench "a0" $ nf usa0 ushaskRec -- , bench "a4" $ nf usa4 ushaskRec -- , bench "a8" $ nf usa8 ushaskRec -- , bench "a12" $ nf usa12 ushaskRec , bench "a15" $ nf usa15 ushaskRec ] ]
VinylRecords/Vinyl
benchmarks/AccessorsBench.hs
mit
7,024
0
20
2,362
2,361
1,214
1,147
192
1
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} #ifndef NO_OVERLAP {-# LANGUAGE OverlappingInstances #-} #endif module Database.Persist.Sql.Class ( RawSql (..) , PersistFieldSql (..) ) where import Control.Applicative ((<$>), (<*>)) import Database.Persist import Data.Monoid ((<>)) import Database.Persist.Sql.Types import Control.Arrow ((&&&)) import Data.Text (Text, intercalate, pack) import Data.Maybe (fromMaybe) import Data.Fixed import Data.Proxy (Proxy) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Class (MonadTrans) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Map as M import qualified Data.IntMap as IM import qualified Data.Set as S import Data.Time (UTCTime, TimeOfDay, Day) import Data.Int import Data.Word import Data.ByteString (ByteString) import Text.Blaze.Html (Html) import Data.Bits (bitSize) import qualified Data.Vector as V -- | Class for data types that may be retrived from a 'rawSql' -- query. class RawSql a where -- | Number of columns that this data type needs and the list -- of substitutions for @SELECT@ placeholders @??@. rawSqlCols :: (DBName -> Text) -> a -> (Int, [Text]) -- | A string telling the user why the column count is what -- it is. rawSqlColCountReason :: a -> String -- | Transform a row of the result into the data type. rawSqlProcessRow :: [PersistValue] -> Either Text a instance PersistField a => RawSql (Single a) where rawSqlCols _ _ = (1, []) rawSqlColCountReason _ = "one column for a 'Single' data type" rawSqlProcessRow [pv] = Single <$> fromPersistValue pv rawSqlProcessRow _ = Left $ pack "RawSql (Single a): wrong number of columns." instance (PersistEntity a, PersistEntityBackend a ~ SqlBackend) => RawSql (Entity a) where rawSqlCols escape = ((+1) . length . entityFields &&& process) . entityDef . Just . entityVal where process ed = (:[]) $ intercalate ", " $ map ((name ed <>) . escape) $ (fieldDB (entityId ed) :) $ map fieldDB $ entityFields ed name ed = escape (entityDB ed) <> "." rawSqlColCountReason a = case fst (rawSqlCols (error "RawSql") a) of 1 -> "one column for an 'Entity' data type without fields" n -> show n ++ " columns for an 'Entity' data type" rawSqlProcessRow (idCol:ent) = Entity <$> fromPersistValue idCol <*> fromPersistValues ent rawSqlProcessRow _ = Left "RawSql (Entity a): wrong number of columns." -- | Since 1.0.1. instance RawSql a => RawSql (Maybe a) where rawSqlCols e = rawSqlCols e . extractMaybe rawSqlColCountReason = rawSqlColCountReason . extractMaybe rawSqlProcessRow cols | all isNull cols = return Nothing | otherwise = case rawSqlProcessRow cols of Right v -> Right (Just v) Left msg -> Left $ "RawSql (Maybe a): not all columns were Null " <> "but the inner parser has failed. Its message " <> "was \"" <> msg <> "\". Did you apply Maybe " <> "to a tuple, perhaps? The main use case for " <> "Maybe is to allow OUTER JOINs to be written, " <> "in which case 'Maybe (Entity v)' is used." where isNull PersistNull = True isNull _ = False instance (RawSql a, RawSql b) => RawSql (a, b) where rawSqlCols e x = rawSqlCols e (fst x) # rawSqlCols e (snd x) where (cnta, lsta) # (cntb, lstb) = (cnta + cntb, lsta ++ lstb) rawSqlColCountReason x = rawSqlColCountReason (fst x) ++ ", " ++ rawSqlColCountReason (snd x) rawSqlProcessRow = let x = getType processRow getType :: (z -> Either y x) -> x getType = error "RawSql.getType" colCountFst = fst $ rawSqlCols (error "RawSql.getType2") (fst x) processRow row = let (rowFst, rowSnd) = splitAt colCountFst row in (,) <$> rawSqlProcessRow rowFst <*> rawSqlProcessRow rowSnd in colCountFst `seq` processRow -- Avoids recalculating 'colCountFst'. instance (RawSql a, RawSql b, RawSql c) => RawSql (a, b, c) where rawSqlCols e = rawSqlCols e . from3 rawSqlColCountReason = rawSqlColCountReason . from3 rawSqlProcessRow = fmap to3 . rawSqlProcessRow from3 :: (a,b,c) -> ((a,b),c) from3 (a,b,c) = ((a,b),c) to3 :: ((a,b),c) -> (a,b,c) to3 ((a,b),c) = (a,b,c) instance (RawSql a, RawSql b, RawSql c, RawSql d) => RawSql (a, b, c, d) where rawSqlCols e = rawSqlCols e . from4 rawSqlColCountReason = rawSqlColCountReason . from4 rawSqlProcessRow = fmap to4 . rawSqlProcessRow from4 :: (a,b,c,d) -> ((a,b),(c,d)) from4 (a,b,c,d) = ((a,b),(c,d)) to4 :: ((a,b),(c,d)) -> (a,b,c,d) to4 ((a,b),(c,d)) = (a,b,c,d) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e) => RawSql (a, b, c, d, e) where rawSqlCols e = rawSqlCols e . from5 rawSqlColCountReason = rawSqlColCountReason . from5 rawSqlProcessRow = fmap to5 . rawSqlProcessRow from5 :: (a,b,c,d,e) -> ((a,b),(c,d),e) from5 (a,b,c,d,e) = ((a,b),(c,d),e) to5 :: ((a,b),(c,d),e) -> (a,b,c,d,e) to5 ((a,b),(c,d),e) = (a,b,c,d,e) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e, RawSql f) => RawSql (a, b, c, d, e, f) where rawSqlCols e = rawSqlCols e . from6 rawSqlColCountReason = rawSqlColCountReason . from6 rawSqlProcessRow = fmap to6 . rawSqlProcessRow from6 :: (a,b,c,d,e,f) -> ((a,b),(c,d),(e,f)) from6 (a,b,c,d,e,f) = ((a,b),(c,d),(e,f)) to6 :: ((a,b),(c,d),(e,f)) -> (a,b,c,d,e,f) to6 ((a,b),(c,d),(e,f)) = (a,b,c,d,e,f) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e, RawSql f, RawSql g) => RawSql (a, b, c, d, e, f, g) where rawSqlCols e = rawSqlCols e . from7 rawSqlColCountReason = rawSqlColCountReason . from7 rawSqlProcessRow = fmap to7 . rawSqlProcessRow from7 :: (a,b,c,d,e,f,g) -> ((a,b),(c,d),(e,f),g) from7 (a,b,c,d,e,f,g) = ((a,b),(c,d),(e,f),g) to7 :: ((a,b),(c,d),(e,f),g) -> (a,b,c,d,e,f,g) to7 ((a,b),(c,d),(e,f),g) = (a,b,c,d,e,f,g) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e, RawSql f, RawSql g, RawSql h) => RawSql (a, b, c, d, e, f, g, h) where rawSqlCols e = rawSqlCols e . from8 rawSqlColCountReason = rawSqlColCountReason . from8 rawSqlProcessRow = fmap to8 . rawSqlProcessRow from8 :: (a,b,c,d,e,f,g,h) -> ((a,b),(c,d),(e,f),(g,h)) from8 (a,b,c,d,e,f,g,h) = ((a,b),(c,d),(e,f),(g,h)) to8 :: ((a,b),(c,d),(e,f),(g,h)) -> (a,b,c,d,e,f,g,h) to8 ((a,b),(c,d),(e,f),(g,h)) = (a,b,c,d,e,f,g,h) extractMaybe :: Maybe a -> a extractMaybe = fromMaybe (error "Database.Persist.GenericSql.extractMaybe") class PersistField a => PersistFieldSql a where sqlType :: Proxy a -> SqlType #ifndef NO_OVERLAP instance PersistFieldSql String where sqlType _ = SqlString #endif instance PersistFieldSql ByteString where sqlType _ = SqlBlob instance PersistFieldSql T.Text where sqlType _ = SqlString instance PersistFieldSql TL.Text where sqlType _ = SqlString instance PersistFieldSql Html where sqlType _ = SqlString instance PersistFieldSql Int where sqlType _ | bitSize (0 :: Int) <= 32 = SqlInt32 | otherwise = SqlInt64 instance PersistFieldSql Int8 where sqlType _ = SqlInt32 instance PersistFieldSql Int16 where sqlType _ = SqlInt32 instance PersistFieldSql Int32 where sqlType _ = SqlInt32 instance PersistFieldSql Int64 where sqlType _ = SqlInt64 instance PersistFieldSql Word where sqlType _ = SqlInt64 instance PersistFieldSql Word8 where sqlType _ = SqlInt32 instance PersistFieldSql Word16 where sqlType _ = SqlInt32 instance PersistFieldSql Word32 where sqlType _ = SqlInt64 instance PersistFieldSql Word64 where sqlType _ = SqlInt64 instance PersistFieldSql Double where sqlType _ = SqlReal instance PersistFieldSql Bool where sqlType _ = SqlBool instance PersistFieldSql Day where sqlType _ = SqlDay instance PersistFieldSql TimeOfDay where sqlType _ = SqlTime instance PersistFieldSql UTCTime where sqlType _ = SqlDayTime instance PersistFieldSql a => PersistFieldSql [a] where sqlType _ = SqlString instance PersistFieldSql a => PersistFieldSql (V.Vector a) where sqlType _ = SqlString instance (Ord a, PersistFieldSql a) => PersistFieldSql (S.Set a) where sqlType _ = SqlString instance (PersistFieldSql a, PersistFieldSql b) => PersistFieldSql (a,b) where sqlType _ = SqlString instance PersistFieldSql v => PersistFieldSql (IM.IntMap v) where sqlType _ = SqlString instance PersistFieldSql v => PersistFieldSql (M.Map T.Text v) where sqlType _ = SqlString instance PersistFieldSql PersistValue where sqlType _ = SqlInt64 -- since PersistValue should only be used like this for keys, which in SQL are Int64 instance PersistFieldSql Checkmark where sqlType _ = SqlBool instance (HasResolution a) => PersistFieldSql (Fixed a) where sqlType a = SqlNumeric long prec where prec = round $ (log $ fromIntegral $ resolution n) / (log 10 :: Double) -- FIXME: May lead to problems with big numbers long = prec + 10 -- FIXME: Is this enough ? n = 0 _mn = return n `asTypeOf` a instance PersistFieldSql Rational where sqlType _ = SqlNumeric 32 20 -- need to make this field big enough to handle Rational to Mumber string conversion for ODBC -- An embedded Entity instance (PersistField record, PersistEntity record) => PersistFieldSql (Entity record) where sqlType _ = SqlString
jcristovao/persistent
persistent/Database/Persist/Sql/Class.hs
mit
10,236
0
17
2,629
3,652
2,069
1,583
-1
-1
------------------------------------------------------------------------------ -- | -- Module : Handler.Personal -- Copyright : (C) 2016 Samuli Thomasson -- License : %% (see the file LICENSE) -- Maintainer : Samuli Thomasson <[email protected]> -- Stability : experimental -- Portability : non-portable -- File Created : 2016-01-01T17:40:21+0200 ------------------------------------------------------------------------------ module Handler.Personal where import Import import Yesod.Auth.Account (resetPasswordR) -- | User's pages getPersonalR :: Handler Html getPersonalR = do (_uid, Entity userId User{..}) <- requireAuthPair res <- runDB $ selectList [SavedRoundStateUser ==. userId] [Desc SavedRoundStateCreated] defaultLayout $ do setTitle "Me" addScript $ StaticR js_elm_js $(widgetFile "personal")
SimSaladin/hajong
hajong-site/Handler/Personal.hs
mit
908
0
12
181
130
70
60
-1
-1
module CovenantEyes.Api.Types.Endpoints ( BasicAuthCreds(..) , ApiCredsFor(..) , ApiRoot(..), mkApiRoot , Secure , NonSecure ) where import CovenantEyes.Api.Internal.Prelude import qualified Data.ByteString.Char8 as B data BasicAuthCreds = BasicAuthCreds { basicAuthUser :: !ByteString , basicAuthPassword :: !ByteString } deriving (Show, Eq, Ord) data ApiCredsFor a = ApiCredsFor { credId :: !a , basicAuthCreds :: !BasicAuthCreds } deriving instance Eq a => Eq (ApiCredsFor a) deriving instance Ord a => Ord (ApiCredsFor a) deriving instance Show a => Show (ApiCredsFor a) newtype ApiRoot a = ApiRoot { unApiRoot :: ByteString } deriving (Show, Eq) instance IsString (ApiRoot a) where fromString = mkApiRoot . fromString data Secure data NonSecure mkApiRoot :: ByteString -> ApiRoot a mkApiRoot root = ApiRoot $ if B.last root == '/' then B.init root else root
3noch/covenanteyes-api-hs
src/CovenantEyes/Api/Types/Endpoints.hs
mit
981
0
9
243
281
160
121
-1
-1
module Haggcat.Types ( module Haggcat.Types , module Haggcat.JSON.Institution ) where import qualified Data.ByteString as BS import Haggcat.JSON.Institution (Institution) type IssuerId = BS.ByteString type ConsumerKey = BS.ByteString type ConsumerSecret = BS.ByteString type CustomerId = BS.ByteString type ErrorMessage = String type SamlAssertion = BS.ByteString
carymrobbins/haggcat
src/Haggcat/Types.hs
mit
395
0
5
73
86
56
30
11
0
module JagMaHaLeva where import Haskore import AutoComp -- note updaters for mappings fd d n = n d v vol n = n v v = [Volume(80)] lmap f l = line (map f l) bar1 = lmap vol [ds 4 qn, ds 4 den, ds 4 sn, ds 4 qn, as 3 qn] bar2 = lmap vol [g 4 qn, g 4 den, g 4 sn, g 4 qn, ds 4 qn] bar3 = lmap vol [as 4 qn, as 4 den, as 4 sn, c 5 en, as 4 en, gs 4 en, g 4 en] bar4 = lmap vol [g 4 qn, f 4 den, f 4 sn, f 4 dqn, g 4 en] bar5 = lmap vol [gs 4 qn, gs 4 den, g 4 sn,f 4 qn, f 4 den, f 4 sn] bar6 = lmap vol [g 4 qn, g 4 den, f 4 sn, ds 4 qn, ds 4 den, ds 4 sn] bar7 = lmap vol [f 4 qn, f 4 den, f 4 sn, ds 4 en, d 4 en, c 4 en, d 4 en] bar8 = lmap vol [ds 4 qn, g 4 den, as 4 sn, ds 4 hn] mainVoice = bar1 :+: bar2 :+: bar3 :+: bar4 :+: bar5 :+: bar6 :+: bar7 :+: bar8 chords :: [[Chord]] chords = [[(Ds,"Major"),(Ds,"Major")],[(Ds,"Major"),(Ds,"Major")],[(Ds,"Major"),(Ds,"Major")],[(As,"Major"),(As,"Major")],[(Gs,"Major"),(Gs,"Major")],[(Ds,"Major"),(Ds,"Major")],[(As,"Major"),(As,"Major")],[(Ds,"Major"),(Ds,"Major")]] jagMaHaLevaBasic = (Instr "marimba" (Tempo 3 (Phrase [Dyn SF] mainVoice))) :=: (Instr "xylo" (Tempo 3 (Phrase [Dyn SF] (autoComp basic (Ef, "Major") chords)))) jagMaHaLevaCalypso = (Instr "marimba" (Tempo 3 (Phrase [Dyn SF] mainVoice))) :=: (Instr "xylo" (Tempo 3 (Phrase [Dyn SF] (autoComp calypso (Ef, "Major") chords)))) jagMaHaLevaBoogie = (Instr "piano" (Tempo 3 (Phrase [Dyn SF] mainVoice))) :=: (Instr "xylo" (Tempo 3 (Phrase [Dyn SF] (autoComp boogie (Ef, "Major") chords))))
Zolomon/edan40-functional-music
jagmahaleva.hs
mit
1,562
0
14
354
984
529
455
21
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( getApplicationDev , appMain , develMain , taskMain , makeFoundation , withEnv -- * for DevelMain , getApplicationRepl , shutdownApp -- * for GHCI , handler , db ) where import Control.Monad.Logger (liftLoc, runLoggingT) import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr, pgPoolSize, runSqlPool) import Import import Language.Haskell.TH.Syntax (qLocation) import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) import Tasks (parseTask) import LoadEnv import System.Environment (getEnv) import Web.Heroku.Persist.Postgresql (postgresConf) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Root import Handler.Common import Handler.Comments import Handler.Init import Handler.Embed import Handler.User import Handler.Feed import Handler.Unsubscribe import Handler.Sites import Handler.Docs import Handler.Purchase import Handler.Plan import Handler.Cancel -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- | This function allocates resources (such as a database connection pool), -- performs initialization and return a foundation datatype value. This is also -- the place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do dbconf <- if appDatabaseUrl appSettings then postgresConf $ pgPoolSize $ appDatabaseConf appSettings else return $ appDatabaseConf appSettings -- Some basic initializations: HTTP connection manager, logger, and static -- subsite. appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) appGithubOAuthKeys <- getOAuthKeys "GITHUB" appGoogleOAuthKeys <- getOAuthKeys "GOOGLE" appStripeKeys <- getStripeKeys -- We need a log function to create a connection pool. We need a connection -- pool to create our foundation. And we need our foundation to get a -- logging function. To get out of this loop, we initially create a -- temporary foundation without a real connection pool, get a log function -- from there, and then create the real foundation. let mkFoundation appConnPool = App {..} tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger -- Create the database connection pool pool <- flip runLoggingT logFunc $ createPostgresqlPool (pgConnStr dbconf) (pgPoolSize dbconf) -- Perform database migration using our application's logging settings. runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc -- Return the foundation return $ mkFoundation pool where getOAuthKeys :: String -> IO OAuthKeys getOAuthKeys plugin = OAuthKeys <$> getEnvText (plugin ++ "_OAUTH_CLIENT_ID") <*> getEnvText (plugin ++ "_OAUTH_CLIENT_SECRET") getStripeKeys :: IO StripeKeys getStripeKeys = StripeKeys <$> getEnvText "STRIPE_SECRET_KEY" <*> getEnvText "STRIPE_PUBLISHABLE_KEY" getEnvText :: String -> IO Text getEnvText = fmap pack . getEnv -- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and -- applyng some additional middlewares. makeApplication :: App -> IO Application makeApplication foundation = do logWare <- mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } -- Create the WAI application and apply middlewares appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain -- | Warp settings for the given foundation value. warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) defaultSettings -- | For yesod devel, return the Warp settings and WAI Application. getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = withEnv $ loadYamlSettings [configSettingsYml] [] useEnv -- | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev -- | The @main@ function for an executable running this site. appMain :: IO () appMain = do -- Get the settings from all relevant sources settings <- withEnv $ loadYamlSettingsArgs -- fall back to compile-time values, set to [] to require values at runtime [configSettingsYmlValue] -- allow environment variables to override useEnv -- Generate the foundation from the settings foundation <- makeFoundation settings -- Generate a WAI Application from the foundation app <- makeApplication foundation -- Run the application with Warp runSettings (warpSettings foundation) app taskMain :: IO () taskMain = parseTask >>= handler withEnv :: IO a -> IO a withEnv = (loadEnv >>) -------------------------------------------------------------- -- Functions for DevelMain.hs (a way to run the app from GHCi) -------------------------------------------------------------- getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () --------------------------------------------- -- Functions for use in development with GHCi --------------------------------------------- -- | Run a handler handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h -- | Run DB queries db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB
thoughtbot/carnival
Application.hs
mit
7,840
0
16
1,980
1,310
698
612
-1
-1
module Handler.Home where import Import import Util.Handler (title) import Widget.Languages (languagesWidget) import Data.Function ((&)) import qualified Util.Handler as Handler import qualified Glot.Language as Language getHomeR :: Handler Html getHomeR = do defaultLayout $ do App{..} <- getYesod setTitle $ title "Home" setDescription (metaDescription languages) Handler.setCanonicalUrl HomeR $(widgetFile "homepage") metaDescription :: [Language.Language] -> Text metaDescription languages = [ "Run code online in the browser. " , pack $ show $ length languages , " languages supported: " , languages & map Language.name & intercalate "," ] & concat
prasmussen/glot-www
Handler/Home.hs
mit
743
0
12
176
195
104
91
-1
-1
module Dataset.Backend.Scatter ( dataset ) where import Dataset.Internal.Types -- | The dataset for a histogram is not terribly interesting, it's basically -- just a list. dataset :: Dataset Point dataset = Dataset { _insert = (:) , _removeEnd = id , _dataset = [] , _toList = id , _xbounds = const Nothing , _ybounds = const Nothing }
SilverSylvester/cplot
src/Dataset/Backend/Scatter.hs
mit
381
0
7
104
81
51
30
11
1
import XMonad main = xmonad defaultConfig { terminal = "urxvt" , modMask = mod4Mask , borderWidth = 3 }
agilecreativity/dotfiles
xmonad/xmonad.hs
mit
128
0
7
43
32
19
13
5
1
module JSON.Prettify(toString, prettyJSON) where import JSON.Type toString :: JValue -> String toString (JObject obj) = showListLike ('{','}') obj $ \(key, value) ->'"':key ++ "\":" ++ toString value toString (JArray array) = showListLike ('[',']') array toString toString (JString string) = show string toString (JBool True) = "\"true\"" toString (JBool False) = "\"false\"" toString (JNumber num) = properShow num toString JNull = "null" showListLike :: (Char, Char) -> [a] -> (a -> String) -> String showListLike (open, close) list itemToString = open :showListLike' list ++ [close] where showListLike' [] = "" showListLike' (firstitem:restitems) = itemToString firstitem ++ foldr (\item result ->"," ++ itemToString item ++ result) "" restitems prettyJSON :: JValue -> String prettyJSON = prettyJSON' 0 prettyJSON' :: Int -> JValue -> String prettyJSON' k (JArray x) = "[\n" ++ foldl (+|+) "" (map prettyJSONvalue x) ++ "\n" ++ space k ++ "]" where prettyJSONvalue value = space (k + 4) ++ prettyJSON' (k + 4) value prettyJSON' k (JObject x) = "{\n" ++ foldl (+|+) "" (map prettyJSONkeyvalue x) ++ "\n" ++ space k ++ "}" where prettyJSONkeyvalue (key, value) = space (k + 4) ++ show key ++ ": " ++ prettyJSON' (k + 4) value prettyJSON' _ (JString value) = show value prettyJSON' _ (JBool value) = show value prettyJSON' _ (JNumber value) = properShow value prettyJSON' _ JNull = "null" properShow :: Double -> String properShow value = if fraction == 0 then show k else show value where k::Integer (k, fraction) = properFraction value (+|+):: String -> String -> String "" +|+ b = b a +|+ b = a ++ ",\n" ++ b space :: Int -> String space k = replicate k ' '
zsedem/haskell-playground
json-parser/src/JSON/Prettify.hs
mit
1,858
0
13
476
721
370
351
40
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html module Stratosphere.ResourceProperties.EC2LaunchTemplateSpotOptions where import Stratosphere.ResourceImports -- | Full data type definition for EC2LaunchTemplateSpotOptions. See -- 'ec2LaunchTemplateSpotOptions' for a more convenient constructor. data EC2LaunchTemplateSpotOptions = EC2LaunchTemplateSpotOptions { _eC2LaunchTemplateSpotOptionsInstanceInterruptionBehavior :: Maybe (Val Text) , _eC2LaunchTemplateSpotOptionsMaxPrice :: Maybe (Val Text) , _eC2LaunchTemplateSpotOptionsSpotInstanceType :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON EC2LaunchTemplateSpotOptions where toJSON EC2LaunchTemplateSpotOptions{..} = object $ catMaybes [ fmap (("InstanceInterruptionBehavior",) . toJSON) _eC2LaunchTemplateSpotOptionsInstanceInterruptionBehavior , fmap (("MaxPrice",) . toJSON) _eC2LaunchTemplateSpotOptionsMaxPrice , fmap (("SpotInstanceType",) . toJSON) _eC2LaunchTemplateSpotOptionsSpotInstanceType ] -- | Constructor for 'EC2LaunchTemplateSpotOptions' containing required fields -- as arguments. ec2LaunchTemplateSpotOptions :: EC2LaunchTemplateSpotOptions ec2LaunchTemplateSpotOptions = EC2LaunchTemplateSpotOptions { _eC2LaunchTemplateSpotOptionsInstanceInterruptionBehavior = Nothing , _eC2LaunchTemplateSpotOptionsMaxPrice = Nothing , _eC2LaunchTemplateSpotOptionsSpotInstanceType = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-instanceinterruptionbehavior ecltsoInstanceInterruptionBehavior :: Lens' EC2LaunchTemplateSpotOptions (Maybe (Val Text)) ecltsoInstanceInterruptionBehavior = lens _eC2LaunchTemplateSpotOptionsInstanceInterruptionBehavior (\s a -> s { _eC2LaunchTemplateSpotOptionsInstanceInterruptionBehavior = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-maxprice ecltsoMaxPrice :: Lens' EC2LaunchTemplateSpotOptions (Maybe (Val Text)) ecltsoMaxPrice = lens _eC2LaunchTemplateSpotOptionsMaxPrice (\s a -> s { _eC2LaunchTemplateSpotOptionsMaxPrice = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-spotinstancetype ecltsoSpotInstanceType :: Lens' EC2LaunchTemplateSpotOptions (Maybe (Val Text)) ecltsoSpotInstanceType = lens _eC2LaunchTemplateSpotOptionsSpotInstanceType (\s a -> s { _eC2LaunchTemplateSpotOptionsSpotInstanceType = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EC2LaunchTemplateSpotOptions.hs
mit
3,107
0
12
253
355
202
153
32
1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : Expression -- Copyright : -- License : AllRightsReserved -- -- Maintainer : -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Expression ( RawExpr (..) , Elem (..) , render , cons , consTo , reverse , optimize , commutative , openBrackets , cleanup ) where import Prelude hiding(reverse) import Data.Text (Text) import qualified Data.Text as T import qualified Data.List as L import Data.List (sortBy, groupBy, permutations) import Data.Function (on) import qualified Operation as O import Operation (Operation(..), toChar) data RawExpr = RawExpr Operation Elem deriving (Show, Eq) data Elem = Term Text | Brackets [RawExpr] deriving (Show, Eq) render :: RawExpr -> Text render = T.tail . render' render' :: RawExpr -> Text render' (RawExpr op (Term name)) = toChar op `T.cons` name render' (RawExpr op (Brackets es)) = toChar op `T.cons` T.concat ["(", inner', ")"] where inner = T.concat . map render' $ es inner' = case T.head inner of '+' -> T.tail inner _ -> inner consTo :: Int -> RawExpr -> RawExpr -> RawExpr consTo 0 expr (RawExpr op (Brackets es)) = RawExpr op (Brackets $ expr : es) consTo n expr (RawExpr op (Brackets (e : es))) = RawExpr op (Brackets $ new : es) where new = consTo (n - 1) expr e consTo _ _ _ = error "cannot cons to this expression" cons :: RawExpr -> RawExpr -> RawExpr cons = consTo 0 reverse :: RawExpr -> RawExpr reverse (RawExpr op (Brackets es)) = RawExpr op . Brackets . map reverse . L.reverse $ es reverse e = e inverse :: RawExpr -> RawExpr inverse (RawExpr op e) = RawExpr (O.inverse op) e unsign :: RawExpr -> RawExpr unsign (RawExpr _ e) = RawExpr Sum e pairsB :: Operation -> [RawExpr] -> [RawExpr] pairsB by (e1@(RawExpr op1 _) : e2@(RawExpr op2 _) : rest) | op2 == by || op2 == O.inverse by = new : pairsB by rest | otherwise = pairs by e1 : pairsB by (e2 : rest) where new = if O.negFor by op1 then RawExpr op1 (Brackets [ pairs by (unsign e1) , pairs by (inverse e2) ]) else RawExpr op1 (Brackets [ pairs by (unsign e1) , pairs by e2]) pairsB by [e] = [pairs by e] pairsB _ [] = [] pairs :: Operation -> RawExpr -> RawExpr pairs by (RawExpr op (Brackets [e1, e2])) = RawExpr op (Brackets [ pairs by e1, pairs by e2 ]) pairs by (RawExpr op (Brackets es)) = RawExpr op new where new = case pairsB by es of es'@[RawExpr Diff _] -> Brackets es' [RawExpr _ e] -> e es' -> Brackets es' pairs _ e = e apply :: Eq c => (c -> c) -> c -> c apply f = last . takeWhile2 (/=) . iterate f optimize :: RawExpr -> RawExpr optimize = apply (pairs Sum) . apply (pairs Mul) splitTerms' :: [RawExpr] -> [RawExpr] splitTerms' (e1@(RawExpr op1 _) : e2 : rest) | isTerm e2 = term : terms | otherwise = splitTerms e1 : splitTerms' (e2 : rest) where (restTerm, rest') = span isTerm rest term = RawExpr op1 (Brackets $ [splitTerms (unsign e1), splitTerms e2] ++ restTerm) terms = splitTerms' rest' isTerm (RawExpr op _) = op == Mul || op == Div splitTerms' [e] = [splitTerms e] splitTerms' [] = [] splitTerms :: RawExpr -> RawExpr splitTerms (RawExpr op (Brackets es)) = RawExpr op splited where splited = case splitTerms' es of es'@[RawExpr Diff _] -> Brackets es' [RawExpr _ e] -> e es' -> Brackets es' splitTerms e = e weight' :: [RawExpr] -> Int weight' (e1@(RawExpr op _) : es) = O.time op + weight e1 + weight' es weight' [] = 0 weight :: RawExpr -> Int weight (RawExpr _ (Term _)) = 0 weight (RawExpr _ (Brackets [])) = 0 weight (RawExpr _ (Brackets (e:es))) = weight e + weight' es commutative' :: [RawExpr] -> [[RawExpr]] commutative' es = map concat variants where sorted = sortBy (compare `on` weight) (splitTerms' es) (zeros, rest) = span ((== 0) . weight) sorted -- do not need to permutate zero-weight terms grouped = groupBy ((==) `on` weight) rest perms = map permutations grouped variants = sequence ([zeros] : perms) commutative :: RawExpr -> [RawExpr] commutative e@(RawExpr _ (Term _)) = [e] commutative (RawExpr op (Brackets es)) = map (cleanup . brackets) . commutative' $ es where brackets = RawExpr op . Brackets mulOp :: Operation -> Operation -> Operation mulOp Sum Diff = Diff mulOp Diff Sum = Diff mulOp Sum Sum = Sum mulOp Diff Diff = Sum mulOp _ _ = error "Try to multiply wrong operations" opTerm :: Operation -> RawExpr -> RawExpr -> RawExpr opTerm op (RawExpr op1 e1) (RawExpr op2 e2) = RawExpr (mulOp op1 op2) (Brackets [RawExpr Sum e1, RawExpr op e2]) -- opTerm op (RawExpr op1 e1) (RawExpr op2 (Brackets (RawExpr opb eb : es))) = -- RawExpr (mulOp op1 op2) (Brackets (RawExpr opb e1 : RawExpr op (Brackets (eb : es)))) multiply :: RawExpr -> RawExpr -> RawExpr multiply = opTerm Mul divide :: RawExpr -> RawExpr -> RawExpr divide = opTerm Div openOneBracket' :: [RawExpr] -> [RawExpr] openOneBracket' (RawExpr op1 e1 : RawExpr Mul (Brackets es) : rest) = RawExpr op1 (Brackets (open es)) : rest where open = map (multiply (RawExpr Sum e1)) . splitTerms' openOneBracket' (RawExpr op1 (Brackets es) : RawExpr Mul e2 : rest) = openOneBracket' swapped where swapped = RawExpr op1 e2 : RawExpr Mul (Brackets es) : rest openOneBracket' (RawExpr op1 (Brackets es) : RawExpr Div e2 : rest) = RawExpr op1 (Brackets (open es)) : rest where open = map (`divide` RawExpr Sum e2) . splitTerms' openOneBracket' (old@(RawExpr op (Brackets es)) : rest) = if es' == es then old : openOneBracket' rest else new : rest where es' = openOneBracket' es new = RawExpr op (Brackets es') openOneBracket' (e:es) = e : openOneBracket' es openOneBracket' [] = [] takeWhile2 :: (a -> a -> Bool) -> [a] -> [a] takeWhile2 p (x:ys@(y:_)) | p x y = x : takeWhile2 p ys | otherwise = [x] takeWhile2 _ [x] = [x] takeWhile2 _ [] = [] openBrackets :: RawExpr -> [RawExpr] openBrackets (RawExpr op (Brackets es)) = tail . takeWhile2 (/=) . map (cleanup . brackets) . iterate openOneBracket' $ es where brackets = RawExpr op . Brackets openBrackets e = [e] cleanup :: RawExpr -> RawExpr -- cleanup (RawExpr op (Brackets es)) = RawExpr op . Brackets . concatMap rmBrs $ es -- where rmBrs (RawExpr Sum (Brackets es)) -- | all isSum es = es -- rmBrs e = [e] -- isSum (RawExpr Sum _) = True -- isSum _ = False cleanup (RawExpr Diff (Brackets [RawExpr Diff el])) = cleanup $ RawExpr Sum el cleanup (RawExpr Diff (Brackets [RawExpr op1 el1, RawExpr Diff el2])) = cleanup $ RawExpr Sum (Brackets [e1', e2']) where e1' = RawExpr (O.inverse op1) el1 e2' = RawExpr Sum el2 cleanup (RawExpr op (Brackets [e])) = RawExpr op new where new = case cleanup e of RawExpr Sum e' -> e' e' -> Brackets [e'] cleanup (RawExpr op (Brackets es)) = RawExpr op $ Brackets (map cleanup es) cleanup e = e
uvNikita/SyntacticAnalyzer
src/Expression.hs
mit
7,554
0
14
2,059
2,877
1,497
1,380
158
3
{-# LANGUAGE ForeignFunctionInterface #-} module Safe where import Foreign.C.Types fibonacci :: Int -> Int fibonacci n = fibs !! n where fibs = 0 : 1 : zipWith (+) fibs (tail fibs) -- wrapper code - I think it might be possible to autogenerate this? fibonacci_hs :: CInt -> CInt fibonacci_hs = fromIntegral . fibonacci . fromIntegral foreign export ccall fibonacci_hs :: CInt -> CInt
ssteinbach/calling_haskell_from_c
Safe.hs
mit
398
0
10
79
99
56
43
9
1
{-# LANGUAGE DeriveAnyClass, DeriveGeneric, OverloadedStrings #-} {- | Module : System.JBI.Commands.Nix Description : Nix tooling support Copyright : (c) Ivan Lazar Miljenovic License : MIT Maintainer : [email protected] -} module System.JBI.Commands.Nix where import System.JBI.Commands.Tool import System.JBI.Config (Config) import System.JBI.Tagged import Data.Aeson (ToJSON) import Data.Char (isSpace) import GHC.Generics (Generic) -------------------------------------------------------------------------------- data NixSupport = NixSupport { nixShell :: !(Maybe (Installed NixShell)) , cabal2Nix :: !(Maybe (Installed Cabal2Nix)) , nixInstantiate :: !(Maybe (Installed NixInstantiate)) } deriving (Eq, Ord, Show, Read, Generic, ToJSON) findNixSupport :: Config -> IO NixSupport findNixSupport cfg = NixSupport <$> commandInformation cfg <*> commandInformation cfg <*> commandInformation cfg data NixShell instance Tool NixShell where commandName = "nix-shell" data Cabal2Nix instance Tool Cabal2Nix where commandName = "cabal2nix" commandVersion = withTaggedF . tryFindVersionBy getVer where -- There's a digit in the command name, so the naive approach -- doesn't work. getVer = takeVersion . drop 1 . dropWhile (not . isSpace) data NixInstantiate instance Tool NixInstantiate where commandName = "nix-instantiate"
ivan-m/jbi
lib/System/JBI/Commands/Nix.hs
mit
1,499
0
13
327
289
160
129
-1
-1
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-} module Main where import System.Environment import Control.Concurrent import Control.Monad import Yesod import Yesod.Core data ImpulseManagerRoutes = ImpulseManagerRoutes{ impulseManagerStatus :: MVar Int } mkYesod "ImpulseManagerRoutes" [parseRoutes| / HomeR GET /new NewNodeR GET |] instance Yesod ImpulseManagerRoutes main :: IO () main = do putStrLn "Starting" managerStatus <- newEmptyMVar _ <- forkIO $ startWarpNode managerStatus id <- readMVar managerStatus putStrLn "Stopping" startWarpNode :: MVar Int -> IO () startWarpNode status = do portS <- getEnv "PORT" warp 3000 (ImpulseManagerRoutes status) getHomeR :: Handler Html getHomeR = defaultLayout [whamlet|Hello World!|] getNewNodeR :: Handler Html getNewNodeR = do master <- getYesod liftIO $ putMVar (impulseManagerStatus master) 5 defaultLayout [whamlet|New Node?!?!|]
smurphy8/tach
apps/tach-manager-impulse/src/Main.hs
mit
937
0
10
154
240
121
119
29
1