code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Language.Sampler where
import Language.Syntax
import Language.Type
import Language.Inter
import Autolib.Util.Zufall
import Autolib.Util.Wort ( alle )
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Set
import Data.Typeable
import Data.List
data Sampler =
Sampler { language :: Language.Syntax.Type
, num_samples :: Int -- ^ anzahl der samples
, min_sample_length :: Int -- ^ minimale länge der samples
, max_sample_length :: Int -- ^ maximal länge der samples
}
deriving ( Eq, Typeable )
$(derives [makeReader, makeToDoc] [''Sampler])
example = Sampler
{ language = Lukas
, num_samples = 50
, min_sample_length = 4
, max_sample_length = 40
}
create :: Integral s
=> Sampler
-> s -- ^ random seed
-> Maybe Int -- ^ if present, create some words longer than this
-> ( [String], [String] ) -- ^ (yeah, noh)
create i seed large = randomly ( fromIntegral seed ) $ do
let l = inter $ language i
w = min_sample_length i
n = num_samples i
-- die kleinen sollten ja auch schnell zu testen sein
let klein = take 40 $ do
n <- [0 .. ]
alle ( setToList $ alphabet l ) n
-- watch argument ordering! -- TODO: use records instead
here <- samples l n w
there <- anti_samples l n w
let top = case large of
Nothing -> max_sample_length i
Just lrg -> 5 + max lrg ( max_sample_length i )
farout <- samples l 10 top
return $ partition (contains l)
$ nub
$ filter ( \ w -> length w <= top )
$ klein ++ here ++ there ++ farout
-- local variables:
-- mode: haskell
-- end:
| Erdwolf/autotool-bonn | src/Language/Sampler.hs | gpl-2.0 | 1,807 | 0 | 17 | 558 | 463 | 248 | 215 | 46 | 2 |
module Lib.TimeIt
( timeIt
) where
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
timeIt :: IO a -> IO (NominalDiffTime, a)
timeIt act = do
before <- getCurrentTime
res <- act
after <- getCurrentTime
return (after `diffUTCTime` before, res)
| nadavshemer/buildsome | src/Lib/TimeIt.hs | gpl-2.0 | 272 | 0 | 9 | 51 | 95 | 51 | 44 | 9 | 1 |
main = do
let l1 = [1,2,3,4]
print l1
let l2 = 5:l1
print l2
print $ l1 !! 1
print $ head l1
print $ tail l1
print $ last l1
print $ init l1
print $ length l1
print $ null l1
print $ null []
print $ null [[]]
print $ reverse l1
print $ take 3 l1
print $ drop 3 l1
print $ minimum l1
print $ maximum l1
print $ sum l1
print $ product l1
print $ 4 `elem` l1
print $ [1..10]
print $ [2,4..10]
print $ take 10 [2,4..]
print $ take 10 (cycle [1,2,3])
print $ replicate 3 10
-- list comprehension, predicate
print $ [x*2 | x <- [1..10]]
print $ [x*2 | x <- [1..10], x*2 >= 12]
print $ [x | x <- [50..100], x `mod` 7 == 3]
print $ [ x | x <- [10..20], x /= 13, x /= 15, x /= 19]
print $ [ if x < 10 then "BOOM!" else "BANG!" | x <- [7..13], odd x]
print $ [ x*y | x <- [2,5,10], y <- [8,10,11]]
print $ ['a'..'z']
print $ ['Y'..'Z']
print $ [3,2,1] > [2,1,0]
print $ [3,2,1] == [2,1,0]
| solvery/lang-features | haskell/list_2.hs | gpl-2.0 | 1,042 | 0 | 11 | 366 | 644 | 319 | 325 | 37 | 2 |
{-# LANGUAGE RankNTypes #-}
module Control.Monad.MaybeCPS where
-- IDEA: Use continuation passing style to get rid of pattern matching in
-- successful cases.
--
-- Didn't really work for the entailment check.
--
-- cf. http://www.haskell.org/haskellwiki/Performance/Monads
import Control.Monad
newtype MaybeCPS a = MaybeCPS { unMaybeCPS :: forall r. (a -> Maybe r) -> Maybe r }
runMaybeCPS m = unMaybeCPS m return
-- The Cont definitions of return and (>>=)
instance Monad MaybeCPS where
return a = MaybeCPS (\k -> k a)
MaybeCPS m >>= f = MaybeCPS (\k -> m (\a -> unMaybeCPS (f a) k))
instance MonadPlus MaybeCPS where
mzero = MaybeCPS (\_ -> Nothing) -- equivalent to MaybeCPS (Nothing >>=)
m `mplus` n = case runMaybeCPS m of
Nothing -> n
Just a -> return a
| meiersi/scyther-proof | src/Control/Monad/MaybeCPS.hs | gpl-3.0 | 828 | 0 | 14 | 196 | 209 | 113 | 96 | 13 | 1 |
{-# OPTIONS_GHC -w #-}
module GtkBlast.ROW_ROW_FIGHT_THE_POWER
(
i ,am ,playing ,the ,game
,the ,one ,that'll ,take ,me ,to ,my ,end
,i ,am ,waiting ,for ,the ,rain
,to ,wash ,up ,who ,i ,am
,libera ,me ,from ,S,osach
,{-ROW-}ROW__FIGHT_THE_POWER (DO)
,THE(..), IMPOSSIBLE(..)
,{-ROW-}ROW__FIGHT_THE_POWER (SEE)
,THE, INVISIBLE(..)
,{-ROW-}ROW__FIGHT_THE_POWER (TOUCH)
,THE, UNTOUCHABLE(..)
,{-ROW-}ROW__FIGHT_THE_POWER (BREAK)
,THE, UNBREAKABLE(..)
,{-ROW-}ROW__FIGHT_THE_POWER (ROW, ROW)
,{-ROW-}ROW__FIGHT_THE_POWER (FIGHT)
,THE, POWER(..)
,{-ROW-}ROW__FIGHT_THE_POWER (ROW, ROW)
,{-ROW-}ROW__FIGHT_THE_POWER (FIGHT)
,THE, POWER(..)
,you, lost, The(..), Game(..), (!)
) where
import Prelude
import Graphics.UI.Gtk
data {-ROW-}ROW__FIGHT_THE_POWER =
DO THE IMPOSSIBLE
| SEE THE INVISIBLE
-- ROW ROW FIGHT THE POWER
| TOUCH THE UNTOUCHABLE
| BREAK THE UNBREAKABLE
| ROW ROW__FIGHT_THE_POWER
| {-ROW ROW-}FIGHT THE POWER
i :: a -> b -> b
i _ a = a
am :: a
am = undefined
playing :: Monad m => a -> m b -> m b
playing _ m = m
the :: a -> b -> c -> d -> e -> f -> g -> IO ()
the _ _ _ _ _ _ _ = return ()
game :: Monad m => m ()
game = return ()
one :: a
one = undefined
that'll :: a
that'll = undefined
me :: a
me = undefined
to :: a -> b -> c -> d -> e -> IO ()
to _ _ _ _ _ = return ()
my :: a
my = undefined
end :: a
end = undefined
waiting :: Monad m => a -> b -> c -> m ()
waiting _ _ _ = return ()
for :: a
for = undefined
rain :: a
rain = undefined
wash :: a
wash = undefined
up :: a
up = undefined
who :: a
who = undefined
libera :: a -> b -> [c] -> c
libera _ _ a = last a
from :: a
from = undefined
osach :: a
osach = undefined
you :: a -> b -> c -> IO ()
you _ _ _ = mainGUI
lost :: a
lost = undefined
data The = The
data Game = Game
infixr 6 !
(!) :: a -> b -> b
(!) _ b = b
data THE = THE
data IMPOSSIBLE = IMPOSSIBLE
data INVISIBLE = INVISIBLE
data UNTOUCHABLE = UNTOUCHABLE
data UNBREAKABLE = UNBREAKABLE
data POWER = POWER
data S
| exbb2/BlastItWithPiss | src/GtkBlast/ROW_ROW_FIGHT_THE_POWER.hs | gpl-3.0 | 2,140 | 0 | 13 | 581 | 858 | 507 | 351 | -1 | -1 |
{- | The public face of Template Haskell
For other documentation, refer to:
<http://www.haskell.org/haskellwiki/Template_Haskell>
-}
module Language.Haskell.TH(
-- * The monad and its operations
Q,
runQ,
-- ** Administration: errors, locations and IO
reportError, -- :: String -> Q ()
reportWarning, -- :: String -> Q ()
report, -- :: Bool -> String -> Q ()
recover, -- :: Q a -> Q a -> Q a
location, -- :: Q Loc
Loc(..),
runIO, -- :: IO a -> Q a
-- ** Querying the compiler
-- *** Reify
reify, -- :: Name -> Q Info
reifyModule,
thisModule,
Info(..), ModuleInfo(..),
InstanceDec,
ParentName,
Arity,
Unlifted,
-- *** Name lookup
lookupTypeName, -- :: String -> Q (Maybe Name)
lookupValueName, -- :: String -> Q (Maybe Name)
-- *** Instance lookup
reifyInstances,
isInstance,
-- *** Roles lookup
reifyRoles,
-- *** Annotation lookup
reifyAnnotations, AnnLookup(..),
-- * Typed expressions
TExp, unType,
-- * Names
Name, NameSpace, -- Abstract
-- ** Constructing names
mkName, -- :: String -> Name
newName, -- :: String -> Q Name
-- ** Deconstructing names
nameBase, -- :: Name -> String
nameModule, -- :: Name -> Maybe String
-- ** Built-in names
tupleTypeName, tupleDataName, -- Int -> Name
unboxedTupleTypeName, unboxedTupleDataName, -- :: Int -> Name
-- * The algebraic data types
-- | The lowercase versions (/syntax operators/) of these constructors are
-- preferred to these constructors, since they compose better with
-- quotations (@[| |]@) and splices (@$( ... )@)
-- ** Declarations
Dec(..), Con(..), Clause(..),
Strict(..), Foreign(..), Callconv(..), Safety(..), Pragma(..),
Inline(..), RuleMatch(..), Phases(..), RuleBndr(..), AnnTarget(..),
FunDep(..), FamFlavour(..), TySynEqn(..),
Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence,
-- ** Expressions
Exp(..), Match(..), Body(..), Guard(..), Stmt(..), Range(..), Lit(..),
-- ** Patterns
Pat(..), FieldExp, FieldPat,
-- ** Types
Type(..), TyVarBndr(..), TyLit(..), Kind, Cxt, Pred(..), Syntax.Role(..),
-- * Library functions
-- ** Abbreviations
InfoQ, ExpQ, DecQ, DecsQ, ConQ, TypeQ, TyLitQ, CxtQ, PredQ, MatchQ, ClauseQ,
BodyQ, GuardQ, StmtQ, RangeQ, StrictTypeQ, VarStrictTypeQ, PatQ, FieldPatQ,
RuleBndrQ, TySynEqnQ,
-- ** Constructors lifted to 'Q'
-- *** Literals
intPrimL, wordPrimL, floatPrimL, doublePrimL, integerL, rationalL,
charL, stringL, stringPrimL,
-- *** Patterns
litP, varP, tupP, conP, uInfixP, parensP, infixP,
tildeP, bangP, asP, wildP, recP,
listP, sigP, viewP,
fieldPat,
-- *** Pattern Guards
normalB, guardedB, normalG, normalGE, patG, patGE, match, clause,
-- *** Expressions
dyn, global, varE, conE, litE, appE, uInfixE, parensE,
infixE, infixApp, sectionL, sectionR,
lamE, lam1E, lamCaseE, tupE, condE, multiIfE, letE, caseE, appsE,
listE, sigE, recConE, recUpdE, stringE, fieldExp,
-- **** Ranges
fromE, fromThenE, fromToE, fromThenToE,
-- ***** Ranges with more indirection
arithSeqE,
fromR, fromThenR, fromToR, fromThenToR,
-- **** Statements
doE, compE,
bindS, letS, noBindS, parS,
-- *** Types
forallT, varT, conT, appT, arrowT, listT, tupleT, sigT, litT,
promotedT, promotedTupleT, promotedNilT, promotedConsT,
-- **** Type literals
numTyLit, strTyLit,
-- **** Strictness
isStrict, notStrict, strictType, varStrictType,
-- **** Class Contexts
cxt, classP, equalP, normalC, recC, infixC, forallC,
-- *** Kinds
varK, conK, tupleK, arrowK, listK, appK, starK, constraintK,
-- *** Roles
nominalR, representationalR, phantomR, inferR,
-- *** Top Level Declarations
-- **** Data
valD, funD, tySynD, dataD, newtypeD,
-- **** Class
classD, instanceD, sigD,
-- **** Role annotations
roleAnnotD,
-- **** Type Family / Data Family
familyNoKindD, familyKindD, dataInstD,
closedTypeFamilyNoKindD, closedTypeFamilyKindD,
newtypeInstD, tySynInstD,
typeFam, dataFam, tySynEqn,
-- **** Foreign Function Interface (FFI)
cCall, stdCall, unsafe, safe, forImpD,
-- **** Pragmas
ruleVar, typedRuleVar,
pragInlD, pragSpecD, pragSpecInlD, pragSpecInstD, pragRuleD, pragAnnD,
-- * Pretty-printer
Ppr(..), pprint, pprExp, pprLit, pprPat, pprParendType
) where
import Language.Haskell.TH.Syntax as Syntax
import Language.Haskell.TH.Lib
import Language.Haskell.TH.Ppr
| jwiegley/ghc-release | libraries/template-haskell/Language/Haskell/TH.hs | gpl-3.0 | 4,547 | 96 | 5 | 963 | 1,074 | 734 | 340 | 80 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
import Prelude hiding (minimum,
maximum,
min,
Left,
Right)
import Data.Int
import Data.Maybe
import Data.Char
import Debug.Trace
import qualified Data.ByteString.Char8 as B
-- Util stuff
-- Two argument (.)
($$) = (.).(.)
-- Data declaration
data Tree a = Empty
| Leaf
{ min :: a
}
| Two
{ keyRight :: a
, left :: Tree a
, right :: Tree a
, min :: a
}
| Three
{ keyMid :: a
, keyRight :: a
, left :: Tree a
, mid :: Tree a
, right :: Tree a
, min :: a
}
instance Show a => Show (Tree a) where
show Empty = "()"
show (Leaf { min=val }) = show val
show (Two { left=l, right=r }) = "(" ++ show l ++ ", " ++ show r ++ ")"
show (Three { left=l, mid=m, right=r }) = "[" ++ show l ++ ", " ++ show m ++ ", " ++ show r ++ "]"
data Query = Insert Int32
| Delete Int32
| Next Int32
| Prev Int32
| Exists Int32
deriving Show
data Direction = Left
| Mid
| Right
deriving Eq
-- Ugly functions for easy implementation of other code.
leaf x = Leaf x
two t1 t2
| mn1 < mn2 = Two mn2 t1 t2 mn1
| otherwise = Two mn1 t2 t1 mn2
where
mn1 = min t1
mn2 = min t2
three t1 t2
| k3 < k1 = Three k1 k2 t2 l r k3
| k3 < k2 = Three k3 k2 l t2 r k1
| otherwise = Three k2 k3 l r t2 k1
where
l = left t1
r = right t1
k1 = min $ left t1
k2 = keyRight t1
k3 = min t2
isEmpty (Empty) = True
isEmpty _ = False
isLeaf (Leaf _) = True
isLeaf _ = False
isTwo (Two _ _ _ _) = True
isTwo _ = False
isThree (Three _ _ _ _ _ _) = True
isThree _ = False
-- Other code
getBranch :: Direction -> Tree a -> Tree a
getBranch Left = left
getBranch Right = right
getBranch Mid = mid
selectBranchTwo (Two k l r _) x
| x < k = Left
| otherwise = Right
selectBranchThree (Three k1 k2 l m r _) x
| x < k1 = Left
| x < k2 = Mid
| otherwise = Right
selectBranch :: Ord a => Tree a -> a -> Direction
selectBranch t x
| isTwo t = selectBranchTwo t x
| isThree t = selectBranchThree t x
findPath :: Ord a => [Tree a] -> Tree a -> a -> Maybe ([Tree a], Tree a)
findPath p t x
| isLeaf t && min t == x = Just (p, t)
| isTwo t || isThree t = findPath (t:p) (getBranch (selectBranch t x) t) x
| otherwise = Nothing
findClosest :: Ord a => [Tree a] -> Tree a -> a -> ([Tree a], Tree a)
findClosest p t x
| isLeaf t = (p, t)
| otherwise = findClosest (t:p) (getBranch (selectBranch t x) t) x
find :: Ord a => Tree a -> a -> Maybe (Tree a)
find t x
| isLeaf t && min t == x = Just t
| isTwo t || isThree t = find (getBranch (selectBranch t x) t) x
| otherwise = Nothing
contains :: Ord a => Tree a -> a -> Bool
contains Empty _ = False
contains (Leaf key) x = x == key
contains t x = contains (getBranch (selectBranch t x) t) x
next :: Ord a => Tree a -> a -> Maybe a
next Empty _ = Nothing
next t x
| maximum t <= x = Nothing
| otherwise = if min v' > x then Just $ min v'
else Just $ min $ nextLeaf p' v' (min v')
where
(p', v') = findClosest [] t x
nextLeaf :: Ord a => [Tree a] -> Tree a -> a -> Tree a
nextLeaf p t k
| isLeaf t && min t /= k = t
| isLeaf t = findInParent
| selectBranch t k == Right = findInParent
| selectBranch t k == Mid = findIn right
| selectBranch t k == Left = if isTwo t then findIn right
else findIn mid
where
findIn f = fromJust $ find t $ min $ f t
findInParent = nextLeaf (tail p) (head p) k
prev :: Ord a => Tree a -> a -> Maybe a
prev Empty _ = Nothing
prev t x
| min t >= x = Nothing
| otherwise = if min v' < x then Just $ min v'
else Just $ min $ prevLeaf p' v' (min v')
where
(p', v') = findClosest [] t x
prevLeaf :: Ord a => [Tree a] -> Tree a -> a -> Tree a
prevLeaf p t k
| isLeaf t && min t /= k = t
| isLeaf t = findInParent
| selectBranch t k == Left = findInParent
| selectBranch t k == Mid = findIn left
| selectBranch t k == Right = if isTwo t then findIn left
else findIn mid
where
findIn f = fromJust $ find t $ maximum $ f t
findInParent = prevLeaf (tail p) (head p) k
goToSelected :: Tree a -> (Tree a -> Tree a) -> a
goToSelected t f
| isLeaf t = min t
| otherwise = goToSelected (f t) f
maximum :: Ord a => Tree a -> a
maximum = (`goToSelected` right)
insert :: Ord a => Tree a -> a -> Tree a
insert t k
| isEmpty t = leaf k
-- | t `contains` k = t
| otherwise = updateRoot t' u
where
(t', u) = insert' t k
delete :: Ord a => Tree a -> a -> Tree a
delete Empty _ = Empty
delete t@(Leaf x) k
| x == k = Empty
| otherwise = t
delete t k =
updateTree t dir (delete (getBranch dir t) k)
where
dir = selectBranch t k
updateTree :: Ord a => Tree a -> Direction -> Tree a -> Tree a
updateTree t d c
| isEmpty c = removeBranch t d
| otherwise = changeChild t d c
removeBranch :: Ord a => Tree a -> Direction -> Tree a
removeBranch t d
| isTwo t = if d == Left then right t
else left t
| isThree t = case d of
Left -> two (mid t) (right t)
Mid -> two (left t) (right t)
Right -> two (left t) (mid t)
updateRoot :: Ord a => Tree a -> Maybe (Tree a) -> Tree a
updateRoot t u
| isNothing u = t
| isLeaf t = two t u'
| isTwo t = three t u'
| isThree t = updateRoot t' u''
where
u' = fromJust u
(t', u'') = splitThree t u'
insert' :: Ord a => Tree a -> a -> (Tree a, Maybe (Tree a))
insert' t k
| isLeaf t && min t == k = (t, Nothing)
| isLeaf t = (t, Just $ leaf k)
| otherwise = mergedNode
where
dir = selectBranch t k
branch = getBranch dir t
mergedNode = if isNothing update then (newNode, Nothing)
else mergeNode newNode (fromJust update)
newNode = changeChild t dir newChild
(newChild, update) = insert' branch k
changeChild :: Ord a => Tree a -> Direction -> Tree a -> Tree a
changeChild t Left c = t { left = c, min = min c }
changeChild t Right c = t { keyRight = min c,right = c }
changeChild t Mid c = t { keyMid = min c,mid = c }
mergeNode :: Ord a => Tree a -> Tree a -> (Tree a, Maybe (Tree a))
mergeNode t1 t2
| isTwo t1 = (three t1 t2, Nothing)
| isThree t1 = splitThree t1 t2
splitThree :: Ord a => Tree a -> Tree a -> (Tree a, Maybe (Tree a))
splitThree t1 t2 =
if min t2 < keyMid t1 then
(two (left t1) t2, Just $ two (mid t1) (right t1))
else
(two (left t1) (mid t1), Just $ two t2 (right t1))
-- Solution
showBool :: Bool -> B.ByteString
showBool True = "true"
showBool False = "false"
showRes :: Maybe Int32 -> B.ByteString
showRes (Just x) = B.pack $ show x
showRes Nothing = "none"
parse :: B.ByteString -> [Query]
parse = parse' . B.words
parse' :: [B.ByteString] -> [Query]
parse' [] = []
parse' (s:x:xs)
| B.head s == 'i' = Insert (fromInteger $ fst $ fromJust $ B.readInteger x) : parse' xs
| B.head s == 'd' = Delete (fromInteger $ fst $ fromJust $ B.readInteger x) : parse' xs
| B.head s == 'n' = Next (fromInteger $ fst $ fromJust $ B.readInteger x) : parse' xs
| B.head s == 'p' = Prev (fromInteger $ fst $ fromJust $ B.readInteger x) : parse' xs
| B.head s == 'e' = Exists (fromInteger $ fst $ fromJust $ B.readInteger x) : parse' xs
solveQuery :: Query -> Tree Int32 -> (B.ByteString, Tree Int32)
solveQuery (Insert x) t = ("", t `insert` x)
solveQuery (Delete x) t = ("", t `delete` x)
solveQuery (Next x) t = (showRes $ t `next` x, t)
solveQuery (Prev x) t = (showRes $ t `prev` x, t)
solveQuery (Exists x) t = (showBool $ t `contains` x, t)
runner :: [Query] -> Tree Int32 -> [B.ByteString]
runner [] _ = []
runner (q:qs) t =
(if res /= "" then (res:) else id)
$ runner qs t'
where
(res, t') = solveQuery q t
solve :: B.ByteString -> B.ByteString
solve = B.unlines . (`runner` Empty) . parse
fileName :: String
fileName = "bst"
interactFiles :: String -> (B.ByteString -> B.ByteString) -> IO()
interactFiles s f = do
inp <- B.readFile (s ++ ".in")
B.writeFile (s ++ ".out") (f inp)
main :: IO ()
main = interactFiles fileName solve
| zakharvoit/discrete-math-labs | Season2/BinaryTrees/Tree23/Tree23.hs | gpl-3.0 | 8,844 | 32 | 12 | 2,994 | 4,052 | 2,013 | 2,039 | 235 | 4 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, BangPatterns #-}
module Sound.Tidal.Core where
import Prelude hiding ((<*), (*>))
import Data.Fixed (mod')
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Sound.Tidal.Pattern
-- ** Elemental patterns
-- | An empty pattern
silence :: Pattern a
silence = empty
-- | Takes a function from time to values, and turns it into a 'Pattern'.
sig :: (Time -> a) -> Pattern a
sig f = Pattern q
where q (State (Arc s e) _)
| s > e = []
| otherwise = [Event (Context []) Nothing (Arc s e) (f (s+((e-s)/2)))]
-- | @sine@ returns a 'Pattern' of continuous 'Fractional' values following a
-- sinewave with frequency of one cycle, and amplitude from 0 to 1.
sine :: Fractional a => Pattern a
sine = sig $ \t -> (sin_rat ((pi :: Double) * 2 * fromRational t) + 1) / 2
where sin_rat = fromRational . toRational . sin
-- | @cosine@ is a synonym for @0.25 ~> sine@.
cosine :: Fractional a => Pattern a
cosine = 0.25 `rotR` sine
-- | @saw@ is the equivalent of 'sine' for (ascending) sawtooth waves.
saw :: (Fractional a, Real a) => Pattern a
saw = sig $ \t -> mod' (fromRational t) 1
-- | @isaw@ is the equivalent of 'sine' for inverse (descending) sawtooth waves.
isaw :: (Fractional a, Real a) => Pattern a
isaw = (1-) <$> saw
-- | @tri@ is the equivalent of 'sine' for triangular waves.
tri :: (Fractional a, Real a) => Pattern a
tri = fastAppend saw isaw
-- | @square@ is the equivalent of 'sine' for square waves.
square :: (Fractional a) => Pattern a
square = sig $
\t -> fromIntegral ((floor $ mod' (fromRational t :: Double) 1 * 2) :: Integer)
-- | @envL@ is a 'Pattern' of continuous 'Double' values, representing
-- a linear interpolation between 0 and 1 during the first cycle, then
-- staying constant at 1 for all following cycles. Possibly only
-- useful if you're using something like the retrig function defined
-- in tidal.el.
envL :: Pattern Double
envL = sig $ \t -> max 0 $ min (fromRational t) 1
-- | like 'envL' but reversed.
envLR :: Pattern Double
envLR = (1-) <$> envL
-- | 'Equal power' version of 'env', for gain-based transitions
envEq :: Pattern Double
envEq = sig $ \t -> sqrt (sin (pi/2 * max 0 (min (fromRational (1-t)) 1)))
-- | Equal power reversed
envEqR :: Pattern Double
envEqR = sig $ \t -> sqrt (cos (pi/2 * max 0 (min (fromRational (1-t)) 1)))
-- ** Pattern algebra
-- class for types that support a left-biased union
class Unionable a where
union :: a -> a -> a
-- default union is just to take the left hand side..
instance Unionable a where
union = const
instance {-# OVERLAPPING #-} Unionable ControlMap where
union = Map.union
(|+|) :: (Applicative a, Num b) => a b -> a b -> a b
a |+| b = (+) <$> a <*> b
(|+ ) :: Num a => Pattern a -> Pattern a -> Pattern a
a |+ b = (+) <$> a <* b
( +|) :: Num a => Pattern a -> Pattern a -> Pattern a
a +| b = (+) <$> a *> b
(|++|) :: Applicative a => a String -> a String -> a String
a |++| b = (++) <$> a <*> b
(|++ ) :: Pattern String -> Pattern String -> Pattern String
a |++ b = (++) <$> a <* b
( ++|) :: Pattern String -> Pattern String -> Pattern String
a ++| b = (++) <$> a *> b
(|/|) :: (Applicative a, Fractional b) => a b -> a b -> a b
a |/| b = (/) <$> a <*> b
(|/ ) :: Fractional a => Pattern a -> Pattern a -> Pattern a
a |/ b = (/) <$> a <* b
( /|) :: Fractional a => Pattern a -> Pattern a -> Pattern a
a /| b = (/) <$> a *> b
(|*|) :: (Applicative a, Num b) => a b -> a b -> a b
a |*| b = (*) <$> a <*> b
(|* ) :: Num a => Pattern a -> Pattern a -> Pattern a
a |* b = (*) <$> a <* b
( *|) :: Num a => Pattern a -> Pattern a -> Pattern a
a *| b = (*) <$> a *> b
(|-|) :: (Applicative a, Num b) => a b -> a b -> a b
a |-| b = (-) <$> a <*> b
(|- ) :: Num a => Pattern a -> Pattern a -> Pattern a
a |- b = (-) <$> a <* b
( -|) :: Num a => Pattern a -> Pattern a -> Pattern a
a -| b = (-) <$> a *> b
(|%|) :: (Applicative a, Real b) => a b -> a b -> a b
a |%| b = mod' <$> a <*> b
(|% ) :: Real a => Pattern a -> Pattern a -> Pattern a
a |% b = mod' <$> a <* b
( %|) :: Real a => Pattern a -> Pattern a -> Pattern a
a %| b = mod' <$> a *> b
(|**|) :: (Applicative a, Floating b) => a b -> a b -> a b
a |**| b = (**) <$> a <*> b
(|** ) :: Floating a => Pattern a -> Pattern a -> Pattern a
a |** b = (**) <$> a <* b
( **|) :: Floating a => Pattern a -> Pattern a -> Pattern a
a **| b = (**) <$> a *> b
(|>|) :: (Applicative a, Unionable b) => a b -> a b -> a b
a |>| b = flip union <$> a <*> b
(|> ) :: Unionable a => Pattern a -> Pattern a -> Pattern a
a |> b = flip union <$> a <* b
( >|) :: Unionable a => Pattern a -> Pattern a -> Pattern a
a >| b = flip union <$> a *> b
(|<|) :: (Applicative a, Unionable b) => a b -> a b -> a b
a |<| b = union <$> a <*> b
(|< ) :: Unionable a => Pattern a -> Pattern a -> Pattern a
a |< b = union <$> a <* b
( <|) :: Unionable a => Pattern a -> Pattern a -> Pattern a
a <| b = union <$> a *> b
-- Backward compatibility - structure from left, values from right.
(#) :: Unionable b => Pattern b -> Pattern b -> Pattern b
(#) = (|>)
-- ** Constructing patterns
-- | Turns a list of values into a pattern, playing one of them per cycle.
fromList :: [a] -> Pattern a
fromList = cat . map pure
-- | Turns a list of values into a pattern, playing all of them per cycle.
fastFromList :: [a] -> Pattern a
fastFromList = fastcat . map pure
-- | A synonym for 'fastFromList'
listToPat :: [a] -> Pattern a
listToPat = fastFromList
-- | 'fromMaybes; is similar to 'fromList', but allows values to
-- be optional using the 'Maybe' type, so that 'Nothing' results in
-- gaps in the pattern.
fromMaybes :: [Maybe a] -> Pattern a
fromMaybes = fastcat . map f
where f Nothing = silence
f (Just x) = pure x
-- | A pattern of whole numbers from 0 to the given number, in a single cycle.
run :: (Enum a, Num a) => Pattern a -> Pattern a
run = (>>= _run)
_run :: (Enum a, Num a) => a -> Pattern a
_run n = fastFromList [0 .. n-1]
-- | From @1@ for the first cycle, successively adds a number until it gets up to @n@
scan :: (Enum a, Num a) => Pattern a -> Pattern a
scan = (>>= _scan)
_scan :: (Enum a, Num a) => a -> Pattern a
_scan n = slowcat $ map _run [1 .. n]
-- ** Combining patterns
-- | Alternate between cycles of the two given patterns
append :: Pattern a -> Pattern a -> Pattern a
append a b = cat [a,b]
-- | Like 'append', but for a list of patterns. Interlaces them, playing the first cycle from each
-- in turn, then the second cycle from each, and so on.
cat :: [Pattern a] -> Pattern a
cat [] = silence
cat ps = Pattern $ q
where n = length ps
q st = concatMap (f st) $ arcCyclesZW (arc st)
f st a = query (withResultTime (+offset) p) $ st {arc = Arc (subtract offset (start a)) (subtract offset (stop a))}
where p = ps !! i
cyc = (floor $ start a) :: Int
i = cyc `mod` n
offset = (fromIntegral $ cyc - ((cyc - i) `div` n)) :: Time
-- | Alias for 'cat'
slowCat :: [Pattern a] -> Pattern a
slowCat = cat
slowcat :: [Pattern a] -> Pattern a
slowcat = slowCat
-- | Alias for 'append'
slowAppend :: Pattern a -> Pattern a -> Pattern a
slowAppend = append
slowappend :: Pattern a -> Pattern a -> Pattern a
slowappend = append
-- | Like 'append', but twice as fast
fastAppend :: Pattern a -> Pattern a -> Pattern a
fastAppend a b = _fast 2 $ append a b
fastappend :: Pattern a -> Pattern a -> Pattern a
fastappend = fastAppend
-- | The same as 'cat', but speeds up the result by the number of
-- patterns there are, so the cycles from each are squashed to fit a
-- single cycle.
fastCat :: [Pattern a] -> Pattern a
fastCat ps = _fast (toTime $ length ps) $ cat ps
fastcat :: [Pattern a] -> Pattern a
fastcat = fastCat
-- | Similar to @fastCat@, but each pattern is given a relative duration
timeCat :: [(Time, Pattern a)] -> Pattern a
timeCat tps = stack $ map (\(s,e,p) -> compressArc (Arc (s/total) (e/total)) p) $ arrange 0 tps
where total = sum $ map fst tps
arrange :: Time -> [(Time, Pattern a)] -> [(Time, Time, Pattern a)]
arrange _ [] = []
arrange t ((t',p):tps') = (t,t+t',p) : arrange (t+t') tps'
-- | 'overlay' combines two 'Pattern's into a new pattern, so that
-- their events are combined over time.
overlay :: Pattern a -> Pattern a -> Pattern a
overlay !p !p' = Pattern $ \st -> query p st ++ query p' st
-- | An infix alias of @overlay@
(<>) :: Pattern a -> Pattern a -> Pattern a
(<>) = overlay
-- | 'stack' combines a list of 'Pattern's into a new pattern, so that
-- their events are combined over time.
stack :: [Pattern a] -> Pattern a
stack = foldr overlay silence
-- ** Manipulating time
-- | Shifts a pattern back in time by the given amount, expressed in cycles
(<~) :: Pattern Time -> Pattern a -> Pattern a
(<~) = tParam rotL
-- | Shifts a pattern forward in time by the given amount, expressed in cycles
(~>) :: Pattern Time -> Pattern a -> Pattern a
(~>) = tParam rotR
-- | Speed up a pattern by the given time pattern
fast :: Pattern Time -> Pattern a -> Pattern a
fast = tParam _fast
-- | Slow down a pattern by the factors in the given time pattern, 'squeezing'
-- the pattern to fit the slot given in the time pattern
fastSqueeze :: Pattern Time -> Pattern a -> Pattern a
fastSqueeze = tParamSqueeze _fast
-- | An alias for @fast@
density :: Pattern Time -> Pattern a -> Pattern a
density = fast
_fast :: Time -> Pattern a -> Pattern a
_fast r p | r == 0 = silence
| r < 0 = rev $ _fast (negate r) p
| otherwise = withResultTime (/ r) $ withQueryTime (* r) p
-- | Slow down a pattern by the given time pattern
slow :: Pattern Time -> Pattern a -> Pattern a
slow = tParam _slow
_slow :: Time -> Pattern a -> Pattern a
_slow 0 _ = silence
_slow r p = _fast (1/r) p
-- | Slow down a pattern by the factors in the given time pattern, 'squeezing'
-- the pattern to fit the slot given in the time pattern
slowSqueeze :: Pattern Time -> Pattern a -> Pattern a
slowSqueeze = tParamSqueeze _slow
-- | An alias for @slow@
sparsity :: Pattern Time -> Pattern a -> Pattern a
sparsity = slow
-- | @rev p@ returns @p@ with the event positions in each cycle
-- reversed (or mirrored).
rev :: Pattern a -> Pattern a
rev p =
splitQueries $ p {
query = \st -> map makeWholeAbsolute $
mapParts (mirrorArc (midCycle $ arc st)) $
map makeWholeRelative
(query p st
{arc = mirrorArc (midCycle $ arc st) (arc st)
})
}
where makeWholeRelative :: Event a -> Event a
makeWholeRelative (e@(Event {whole = Nothing})) = e
makeWholeRelative (Event c (Just (Arc s e)) p'@(Arc s' e') v) =
Event c (Just $ Arc (s'-s) (e-e')) p' v
makeWholeAbsolute :: Event a -> Event a
makeWholeAbsolute (e@(Event {whole = Nothing})) = e
makeWholeAbsolute (Event c (Just (Arc s e)) p'@(Arc s' e') v) =
Event c (Just $ Arc (s'-e) (e'+s)) p' v
midCycle :: Arc -> Time
midCycle (Arc s _) = sam s + 0.5
mapParts :: (Arc -> Arc) -> [Event a] -> [Event a]
mapParts f es = (\(Event c w p' v) -> Event c w (f p') v) <$> es
-- | Returns the `mirror image' of a 'Arc' around the given point in time
mirrorArc :: Time -> Arc -> Arc
mirrorArc mid' (Arc s e) = Arc (mid' - (e-mid')) (mid'+(mid'-s))
{- | Plays a portion of a pattern, specified by a time arc (start and end time).
The new resulting pattern is played over the time period of the original pattern:
@
d1 $ zoom (0.25, 0.75) $ sound "bd*2 hh*3 [sn bd]*2 drum"
@
In the pattern above, `zoom` is used with an arc from 25% to 75%. It is equivalent to this pattern:
@
d1 $ sound "hh*3 [sn bd]*2"
@
-}
zoom :: (Time, Time) -> Pattern a -> Pattern a
zoom (s,e) = zoomArc (Arc s e)
zoomArc :: Arc -> Pattern a -> Pattern a
zoomArc (Arc s e) p = splitQueries $
withResultArc (mapCycle ((/d) . subtract s)) $ withQueryArc (mapCycle ((+s) . (*d))) p
where d = e-s
-- | @fastGap@ is similar to 'fast' but maintains its cyclic
-- alignment. For example, @fastGap 2 p@ would squash the events in
-- pattern @p@ into the first half of each cycle (and the second
-- halves would be empty). The factor should be at least 1
fastGap :: Pattern Time -> Pattern a -> Pattern a
fastGap = tParam _fastGap
-- | An alias for @fastGap@
densityGap :: Pattern Time -> Pattern a -> Pattern a
densityGap = fastGap
compress :: (Time,Time) -> Pattern a -> Pattern a
compress (s,e) = compressArc (Arc s e)
compressTo :: (Time,Time) -> Pattern a -> Pattern a
compressTo (s,e) = compressArcTo (Arc s e)
repeatCycles :: Int -> Pattern a -> Pattern a
repeatCycles n p = cat (replicate n p)
fastRepeatCycles :: Int -> Pattern a -> Pattern a
fastRepeatCycles n p = cat (replicate n p)
-- | * Higher order functions
-- | Functions which work on other functions (higher order functions)
-- | @every n f p@ applies the function @f@ to @p@, but only affects
-- every @n@ cycles.
every :: Pattern Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
every tp f p = innerJoin $ (\t -> _every t f p) <$> tp
_every :: Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
_every 0 _ p = p
_every n f p = when ((== 0) . (`mod` n)) f p
-- | @every n o f'@ is like @every n f@ with an offset of @o@ cycles
every' :: Pattern Int -> Pattern Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
every' np op f p = do { n <- np; o <- op; _every' n o f p }
_every' :: Int -> Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
_every' n o = when ((== o) . (`mod` n))
-- | @foldEvery ns f p@ applies the function @f@ to @p@, and is applied for
-- each cycle in @ns@.
foldEvery :: [Int] -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
foldEvery ns f p = foldr (`_every` f) p ns
{-|
Only `when` the given test function returns `True` the given pattern
transformation is applied. The test function will be called with the
current cycle as a number.
@
d1 $ when ((elem '4').show)
(striate 4)
$ sound "hh hc"
@
The above will only apply `striate 4` to the pattern if the current
cycle number contains the number 4. So the fourth cycle will be
striated and the fourteenth and so on. Expect lots of striates after
cycle number 399.
-}
when :: (Int -> Bool) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
when test f p = splitQueries $ p {query = apply}
where apply st | test (floor $ start $ arc st) = query (f p) st
| otherwise = query p st
-- | Like 'when', but works on continuous time values rather than cycle numbers.
whenT :: (Time -> Bool) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
whenT test f p = splitQueries $ p {query = apply}
where apply st | test (start $ arc st) = query (f p) st
| otherwise = query p st
_getP_ :: (Value -> Maybe a) -> Pattern Value -> Pattern a
_getP_ f pat = filterJust $ f <$> pat
_getP :: a -> (Value -> Maybe a) -> Pattern Value -> Pattern a
_getP d f pat = (fromMaybe d . f) <$> pat
_cX :: a -> (Value -> Maybe a) -> String -> Pattern a
_cX d f s = Pattern $ \(State a m) -> queryArc (maybe (pure d) (_getP d f) $ Map.lookup s m) a
_cX_ :: (Value -> Maybe a) -> String -> Pattern a
_cX_ f s = Pattern $ \(State a m) -> queryArc (maybe silence (_getP_ f) $ Map.lookup s m) a
cF :: Double -> String -> Pattern Double
cF d = _cX d getF
cF_ :: String -> Pattern Double
cF_ = _cX_ getF
cF0 :: String -> Pattern Double
cF0 = _cX 0 getF
cI :: Int -> String -> Pattern Int
cI d = _cX d getI
cI_ :: String -> Pattern Int
cI_ = _cX_ getI
cI0 :: String -> Pattern Int
cI0 = _cX 0 getI
cB :: Bool -> String -> Pattern Bool
cB d = _cX d getB
cB_ :: String -> Pattern Bool
cB_ = _cX_ getB
cB0 :: String -> Pattern Bool
cB0 = _cX False getB
cR :: Rational -> String -> Pattern Rational
cR d = _cX d getR
cR_ :: String -> Pattern Rational
cR_ = _cX_ getR
cR0 :: String -> Pattern Rational
cR0 = _cX 0 getR
cT :: Time -> String -> Pattern Time
cT = cR
cT0 :: String -> Pattern Time
cT0 = cR0
cT_ :: String -> Pattern Time
cT_ = cR_
cS :: String -> String -> Pattern String
cS d = _cX d getS
cS_ :: String -> Pattern String
cS_ = _cX_ getS
cS0 :: String -> Pattern String
cS0 = _cX "" getS
-- Default controller inputs (for MIDI)
in0 :: Pattern Double
in0 = cF 0 "0"
in1 :: Pattern Double
in1 = cF 0 "1"
in2 :: Pattern Double
in2 = cF 0 "2"
in3 :: Pattern Double
in3 = cF 0 "3"
in4 :: Pattern Double
in4 = cF 0 "4"
in5 :: Pattern Double
in5 = cF 0 "5"
in6 :: Pattern Double
in6 = cF 0 "6"
in7 :: Pattern Double
in7 = cF 0 "7"
in8 :: Pattern Double
in8 = cF 0 "8"
in9 :: Pattern Double
in9 = cF 0 "9"
in10 :: Pattern Double
in10 = cF 0 "10"
in11 :: Pattern Double
in11 = cF 0 "11"
in12 :: Pattern Double
in12 = cF 0 "12"
in13 :: Pattern Double
in13 = cF 0 "13"
in14 :: Pattern Double
in14 = cF 0 "14"
in15 :: Pattern Double
in15 = cF 0 "15"
in16 :: Pattern Double
in16 = cF 0 "16"
in17 :: Pattern Double
in17 = cF 0 "17"
in18 :: Pattern Double
in18 = cF 0 "18"
in19 :: Pattern Double
in19 = cF 0 "19"
in20 :: Pattern Double
in20 = cF 0 "20"
in21 :: Pattern Double
in21 = cF 0 "21"
in22 :: Pattern Double
in22 = cF 0 "22"
in23 :: Pattern Double
in23 = cF 0 "23"
in24 :: Pattern Double
in24 = cF 0 "24"
in25 :: Pattern Double
in25 = cF 0 "25"
in26 :: Pattern Double
in26 = cF 0 "26"
in27 :: Pattern Double
in27 = cF 0 "27"
in28 :: Pattern Double
in28 = cF 0 "28"
in29 :: Pattern Double
in29 = cF 0 "29"
in30 :: Pattern Double
in30 = cF 0 "30"
in31 :: Pattern Double
in31 = cF 0 "31"
in32 :: Pattern Double
in32 = cF 0 "32"
in33 :: Pattern Double
in33 = cF 0 "33"
in34 :: Pattern Double
in34 = cF 0 "34"
in35 :: Pattern Double
in35 = cF 0 "35"
in36 :: Pattern Double
in36 = cF 0 "36"
in37 :: Pattern Double
in37 = cF 0 "37"
in38 :: Pattern Double
in38 = cF 0 "38"
in39 :: Pattern Double
in39 = cF 0 "39"
in40 :: Pattern Double
in40 = cF 0 "40"
in41 :: Pattern Double
in41 = cF 0 "41"
in42 :: Pattern Double
in42 = cF 0 "42"
in43 :: Pattern Double
in43 = cF 0 "43"
in44 :: Pattern Double
in44 = cF 0 "44"
in45 :: Pattern Double
in45 = cF 0 "45"
in46 :: Pattern Double
in46 = cF 0 "46"
in47 :: Pattern Double
in47 = cF 0 "47"
in48 :: Pattern Double
in48 = cF 0 "48"
in49 :: Pattern Double
in49 = cF 0 "49"
in50 :: Pattern Double
in50 = cF 0 "50"
in51 :: Pattern Double
in51 = cF 0 "51"
in52 :: Pattern Double
in52 = cF 0 "52"
in53 :: Pattern Double
in53 = cF 0 "53"
in54 :: Pattern Double
in54 = cF 0 "54"
in55 :: Pattern Double
in55 = cF 0 "55"
in56 :: Pattern Double
in56 = cF 0 "56"
in57 :: Pattern Double
in57 = cF 0 "57"
in58 :: Pattern Double
in58 = cF 0 "58"
in59 :: Pattern Double
in59 = cF 0 "59"
in60 :: Pattern Double
in60 = cF 0 "60"
in61 :: Pattern Double
in61 = cF 0 "61"
in62 :: Pattern Double
in62 = cF 0 "62"
in63 :: Pattern Double
in63 = cF 0 "63"
in64 :: Pattern Double
in64 = cF 0 "64"
in65 :: Pattern Double
in65 = cF 0 "65"
in66 :: Pattern Double
in66 = cF 0 "66"
in67 :: Pattern Double
in67 = cF 0 "67"
in68 :: Pattern Double
in68 = cF 0 "68"
in69 :: Pattern Double
in69 = cF 0 "69"
in70 :: Pattern Double
in70 = cF 0 "70"
in71 :: Pattern Double
in71 = cF 0 "71"
in72 :: Pattern Double
in72 = cF 0 "72"
in73 :: Pattern Double
in73 = cF 0 "73"
in74 :: Pattern Double
in74 = cF 0 "74"
in75 :: Pattern Double
in75 = cF 0 "75"
in76 :: Pattern Double
in76 = cF 0 "76"
in77 :: Pattern Double
in77 = cF 0 "77"
in78 :: Pattern Double
in78 = cF 0 "78"
in79 :: Pattern Double
in79 = cF 0 "79"
in80 :: Pattern Double
in80 = cF 0 "80"
in81 :: Pattern Double
in81 = cF 0 "81"
in82 :: Pattern Double
in82 = cF 0 "82"
in83 :: Pattern Double
in83 = cF 0 "83"
in84 :: Pattern Double
in84 = cF 0 "84"
in85 :: Pattern Double
in85 = cF 0 "85"
in86 :: Pattern Double
in86 = cF 0 "86"
in87 :: Pattern Double
in87 = cF 0 "87"
in88 :: Pattern Double
in88 = cF 0 "88"
in89 :: Pattern Double
in89 = cF 0 "89"
in90 :: Pattern Double
in90 = cF 0 "90"
in91 :: Pattern Double
in91 = cF 0 "91"
in92 :: Pattern Double
in92 = cF 0 "92"
in93 :: Pattern Double
in93 = cF 0 "93"
in94 :: Pattern Double
in94 = cF 0 "94"
in95 :: Pattern Double
in95 = cF 0 "95"
in96 :: Pattern Double
in96 = cF 0 "96"
in97 :: Pattern Double
in97 = cF 0 "97"
in98 :: Pattern Double
in98 = cF 0 "98"
in99 :: Pattern Double
in99 = cF 0 "99"
in100 :: Pattern Double
in100 = cF 0 "100"
in101 :: Pattern Double
in101 = cF 0 "101"
in102 :: Pattern Double
in102 = cF 0 "102"
in103 :: Pattern Double
in103 = cF 0 "103"
in104 :: Pattern Double
in104 = cF 0 "104"
in105 :: Pattern Double
in105 = cF 0 "105"
in106 :: Pattern Double
in106 = cF 0 "106"
in107 :: Pattern Double
in107 = cF 0 "107"
in108 :: Pattern Double
in108 = cF 0 "108"
in109 :: Pattern Double
in109 = cF 0 "109"
in110 :: Pattern Double
in110 = cF 0 "110"
in111 :: Pattern Double
in111 = cF 0 "111"
in112 :: Pattern Double
in112 = cF 0 "112"
in113 :: Pattern Double
in113 = cF 0 "113"
in114 :: Pattern Double
in114 = cF 0 "114"
in115 :: Pattern Double
in115 = cF 0 "115"
in116 :: Pattern Double
in116 = cF 0 "116"
in117 :: Pattern Double
in117 = cF 0 "117"
in118 :: Pattern Double
in118 = cF 0 "118"
in119 :: Pattern Double
in119 = cF 0 "119"
in120 :: Pattern Double
in120 = cF 0 "120"
in121 :: Pattern Double
in121 = cF 0 "121"
in122 :: Pattern Double
in122 = cF 0 "122"
in123 :: Pattern Double
in123 = cF 0 "123"
in124 :: Pattern Double
in124 = cF 0 "124"
in125 :: Pattern Double
in125 = cF 0 "125"
in126 :: Pattern Double
in126 = cF 0 "126"
in127 :: Pattern Double
in127 = cF 0 "127"
| d0kt0r0/Tidal | src/Sound/Tidal/Core.hs | gpl-3.0 | 21,476 | 0 | 18 | 5,060 | 8,385 | 4,274 | 4,111 | 538 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-|
Most data types are defined here to avoid import cycles.
Here is an overview of the hledger data model:
> Journal -- a journal is read from one or more data files. It contains..
> [Transaction] -- journal transactions (aka entries), which have date, status, code, description and..
> [Posting] -- multiple account postings, which have account name and amount
> [HistoricalPrice] -- historical commodity prices
>
> Ledger -- a ledger is derived from a journal, by applying a filter specification and doing some further processing. It contains..
> Journal -- a filtered copy of the original journal, containing only the transactions and postings we are interested in
> Tree AccountName -- all accounts named by the journal's transactions, as a hierarchy
> Map AccountName Account -- the postings, and resulting balances, in each account
For more detailed documentation on each type, see the corresponding modules.
Evolution of transaction\/entry\/posting terminology:
- ledger 2: entries contain transactions
- hledger 0.4: Entrys contain RawTransactions (which are flattened to Transactions)
- ledger 3: transactions contain postings
- hledger 0.5: LedgerTransactions contain Postings (which are flattened to Transactions)
- hledger 0.8: Transactions contain Postings (referencing Transactions..)
-}
module Hledger.Data.Types
where
import Control.Monad.Error (ErrorT)
import Data.Time.Calendar
import Data.Time.LocalTime
import Data.Tree
import Data.Typeable
import qualified Data.Map as Map
import System.Time (ClockTime)
type SmartDate = (String,String,String)
data WhichDate = ActualDate | EffectiveDate deriving (Eq,Show)
data DateSpan = DateSpan (Maybe Day) (Maybe Day) deriving (Eq,Show,Ord)
data Interval = NoInterval
| Days Int | Weeks Int | Months Int | Quarters Int | Years Int
| DayOfMonth Int | DayOfWeek Int
-- WeekOfYear Int | MonthOfYear Int | QuarterOfYear Int
deriving (Eq,Show,Ord)
type AccountName = String
data Side = L | R deriving (Eq,Show,Read,Ord)
data Commodity = Commodity {
symbol :: String, -- ^ the commodity's symbol
-- display preferences for amounts of this commodity
side :: Side, -- ^ should the symbol appear on the left or the right
spaced :: Bool, -- ^ should there be a space between symbol and quantity
precision :: Int, -- ^ number of decimal places to display
-- XXX these three might be better belonging to Journal
decimalpoint :: Char, -- ^ character to use as decimal point
separator :: Char, -- ^ character to use for separating digit groups (eg thousands)
separatorpositions :: [Int] -- ^ positions of separators, counting leftward from decimal point
} deriving (Eq,Ord,Show,Read)
-- | An amount's price in another commodity may be written as \@ unit
-- price or \@\@ total price. Note although a MixedAmount is used, it
-- should be in a single commodity, also the amount should be positive;
-- these are not enforced currently.
data Price = UnitPrice MixedAmount | TotalPrice MixedAmount
deriving (Eq,Ord)
data Amount = Amount {
commodity :: Commodity,
quantity :: Double,
price :: Maybe Price -- ^ the price for this amount at posting time
} deriving (Eq,Ord)
newtype MixedAmount = Mixed [Amount] deriving (Eq,Ord)
data PostingType = RegularPosting | VirtualPosting | BalancedVirtualPosting
deriving (Eq,Show)
data Posting = Posting {
pstatus :: Bool,
paccount :: AccountName,
pamount :: MixedAmount,
pcomment :: String,
ptype :: PostingType,
pmetadata :: [(String,String)],
ptransaction :: Maybe Transaction -- ^ this posting's parent transaction (co-recursive types).
-- Tying this knot gets tedious, Maybe makes it easier/optional.
}
-- The equality test for postings ignores the parent transaction's
-- identity, to avoid infinite loops.
instance Eq Posting where
(==) (Posting a1 b1 c1 d1 e1 f1 _) (Posting a2 b2 c2 d2 e2 f2 _) = a1==a2 && b1==b2 && c1==c2 && d1==d2 && e1==e2 && f1==f2
data Transaction = Transaction {
tdate :: Day,
teffectivedate :: Maybe Day,
tstatus :: Bool, -- XXX tcleared ?
tcode :: String,
tdescription :: String,
tcomment :: String,
tmetadata :: [(String,String)],
tpostings :: [Posting], -- ^ this transaction's postings (co-recursive types).
tpreceding_comment_lines :: String
} deriving (Eq)
data ModifierTransaction = ModifierTransaction {
mtvalueexpr :: String,
mtpostings :: [Posting]
} deriving (Eq)
data PeriodicTransaction = PeriodicTransaction {
ptperiodicexpr :: String,
ptpostings :: [Posting]
} deriving (Eq)
data TimeLogCode = SetBalance | SetRequiredHours | In | Out | FinalOut deriving (Eq,Ord)
data TimeLogEntry = TimeLogEntry {
tlcode :: TimeLogCode,
tldatetime :: LocalTime,
tlcomment :: String
} deriving (Eq,Ord)
data HistoricalPrice = HistoricalPrice {
hdate :: Day,
hsymbol :: String,
hamount :: MixedAmount
} deriving (Eq) -- & Show (in Amount.hs)
type Year = Integer
-- | A journal "context" is some data which can change in the course of
-- parsing a journal. An example is the default year, which changes when a
-- Y directive is encountered. At the end of parsing, the final context
-- is saved for later use by eg the add command.
data JournalContext = Ctx {
ctxYear :: !(Maybe Year) -- ^ the default year most recently specified with Y
, ctxCommodity :: !(Maybe Commodity) -- ^ the default commodity most recently specified with D
, ctxAccount :: ![AccountName] -- ^ the current stack of parent accounts/account name components
-- specified with "account" directive(s). Concatenated, these
-- are the account prefix prepended to parsed account names.
, ctxAliases :: ![(AccountName,AccountName)] -- ^ the current list of account name aliases in effect
} deriving (Read, Show, Eq)
data Journal = Journal {
jmodifiertxns :: [ModifierTransaction],
jperiodictxns :: [PeriodicTransaction],
jtxns :: [Transaction],
open_timelog_entries :: [TimeLogEntry],
historical_prices :: [HistoricalPrice],
final_comment_lines :: String, -- ^ any trailing comments from the journal file
jContext :: JournalContext, -- ^ the context (parse state) at the end of parsing
files :: [(FilePath, String)], -- ^ the file path and raw text of the main and
-- any included journal files. The main file is
-- first followed by any included files in the
-- order encountered.
filereadtime :: ClockTime -- ^ when this journal was last read from its file(s)
} deriving (Eq, Typeable)
-- | A JournalUpdate is some transformation of a Journal. It can do I/O or
-- raise an error.
type JournalUpdate = ErrorT String IO (Journal -> Journal)
-- | A hledger journal reader is a triple of format name, format-detecting
-- predicate, and a parser to Journal.
data Reader = Reader {rFormat :: String
,rDetector :: FilePath -> String -> Bool
,rParser :: FilePath -> String -> ErrorT String IO Journal
}
data Ledger = Ledger {
journal :: Journal,
accountnametree :: Tree AccountName,
accountmap :: Map.Map AccountName Account
}
data Account = Account {
aname :: AccountName,
apostings :: [Posting], -- ^ postings in this account
abalance :: MixedAmount -- ^ sum of postings in this account and subaccounts
}
-- | A generic, pure specification of how to filter (or search) transactions and postings.
data FilterSpec = FilterSpec {
datespan :: DateSpan -- ^ only include if in this date span
,cleared :: Maybe Bool -- ^ only include if cleared\/uncleared\/don't care
,real :: Bool -- ^ only include if real\/don't care
,empty :: Bool -- ^ include if empty (ie amount is zero)
,acctpats :: [String] -- ^ only include if matching these account patterns
,descpats :: [String] -- ^ only include if matching these description patterns
,depth :: Maybe Int
} deriving (Show)
| Lainepress/hledger | hledger-lib/Hledger/Data/Types.hs | gpl-3.0 | 8,735 | 0 | 16 | 2,351 | 1,262 | 774 | 488 | 124 | 0 |
{- |
Module : Tct.Method.Matrix.ArcticMI
Copyright : (c) Martin Avanzini <[email protected]>,
Georg Moser <[email protected]>,
Andreas Schnabl <[email protected]>
License : LGPL (see COPYING)
Maintainer : Andreas Schnabl <[email protected]>
Stability : unstable
Portability : unportable
This module defines the processor arctic.
-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeOperators #-}
module Tct.Method.Matrix.ArcticMI where
import Prelude hiding ((+), (&&), (||), not)
import Data.Typeable
import Control.Monad (liftM)
import Text.PrettyPrint.HughesPJ
import qualified Prelude as Prelude
import qualified Data.Map as Map
import qualified Data.Set as Set
import Qlogic.Arctic hiding (max)
import Qlogic.Diophantine
import Qlogic.Boolean
import Qlogic.MiniSat
import Qlogic.Semiring
import qualified Qlogic.ArcSat as AS
import qualified Qlogic.Semiring as SR
import qualified Qlogic.SatSolver as SatSolver
import Termlib.Utils
import qualified Termlib.FunctionSymbol as F
import qualified Termlib.Problem as Prob
import qualified Termlib.Rule as R
import qualified Termlib.Trs as Trs
import qualified Termlib.Variable as V
import Tct.Certificate (poly, certified, unknown)
import Tct.Encoding.AbstractInterpretation
import Tct.Encoding.Matrix
import Tct.Encoding.Natring ()
import Tct.Encoding.UsablePositions
import Tct.Method.Matrix.MatrixInterpretation
import Tct.Processor.Args
import Tct.Processor.Args.Instances
import Tct.Processor.Orderings
import qualified Tct.Processor.Args as A
import qualified Tct.Processor as P
import Tct.Processor (ComplexityProof(..),Answer(..))
import qualified Tct.Processor.Standard as S
data ArcticOrder = ArcticOrder { ordInter :: MatrixInter ArcInt
, uargs :: UsablePositions} deriving Show
data ArcticMI = ArcticMI deriving (Typeable, Show)
instance ComplexityProof ArcticOrder where
pprintProof order _ =
text "The following argument positions are usable:"
$+$ pprint (uargs order, signature $ ordInter order)
$+$ paragraph ("The input is compatible using the following arctic interpretation.")
$+$ pprint (ordInter order)
answer (ArcticOrder _ _) = CertAnswer $ certified (unknown, poly (Just 1))
instance S.Processor ArcticMI where
name ArcticMI = "arctic"
description ArcticMI = [ "This processor orients the problem using matrix interpretation over the arctic semiring." ]
type ArgumentsOf ArcticMI = (Arg Nat) :+: (Arg Nat) :+: (Arg (Maybe Nat)) :+: (Arg (Maybe Nat)) :+: (Arg Bool)
arguments ArcticMI = opt { A.name = "dim"
, A.description = unwords [ "This argument specifies the dimension of the vectors and square-matrices appearing"
, " in the matrix interpretation."]
, A.defaultValue = Nat 3 }
:+:
opt { A.name = "bound"
, A.description = unwords [ "This argument specifies an upper-bound on coefficients appearing in the interpretation."
, "Such an upper-bound is necessary as we employ bit-blasting to SAT internally"
, "when searching for compatible matrix interpretations."]
, A.defaultValue = Nat 3 }
:+:
opt { A.name = "bits"
, A.description = unwords [ "This argument plays the same role as 'bound',"
, "but instead of an upper-bound the number of bits is specified."
, "This argument overrides the argument 'bound'."]
, A.defaultValue = Nothing }
:+:
opt { A.name = "cbits"
, A.description = unwords [ "This argument specifies the number of bits used for intermediate results, "
, "as for instance coefficients of matrices obtained by interpreting"
, "left- and right-hand sides."]
, A.defaultValue = Nothing }
:+:
opt { A.name = "uargs"
, A.description = unwords [ "This argument specifies whether usable arguments are computed (if applicable)"
, "in order to relax the monotonicity constraints on the interpretation."]
, A.defaultValue = True }
instanceName inst = "arctic-interpretation of dimension " ++ show (dim inst)
type ProofOf ArcticMI = OrientationProof ArcticOrder
solve inst problem | not isMonadic = return $ Inapplicable "Arctic Interpretations only applicable for monadic problems"
| Trs.isEmpty (Prob.strictTrs problem) = orientDp strat st sr wr sig inst
| otherwise = orientRelative strat st sr wr sig inst
where sig = Prob.signature problem
st = Prob.startTerms problem
strat = Prob.strategy problem
sr = Prob.strictComponents problem
wr = Prob.weakComponents problem
isMonadic | Trs.isEmpty (Prob.strictTrs problem) = allMonadic $ Set.filter (F.isCompound sig) $ Trs.functionSymbols wr
| otherwise = allMonadic $ Trs.functionSymbols $ Prob.allComponents problem
allMonadic = all (\ f -> F.arity sig f Prelude.<= 1) . Set.toList
arcticProcessor :: S.StdProcessor ArcticMI
arcticProcessor = S.StdProcessor ArcticMI
-- | This processor implements arctic interpretations.
arctic :: S.ProcessorInstance ArcticMI
arctic = S.StdProcessor ArcticMI `S.withArgs` (nat 2 :+: (nat $ AS.intbound $ AS.Bits 2) :+: Nothing :+: (Just (nat 3)) :+: True)
-- argument accessors
bound :: S.TheProcessor ArcticMI -> AS.Size
bound inst = case mbits of
Just (Nat b) -> AS.Bits b
Nothing -> AS.Bound $ Fin bnd
where (_ :+: Nat bnd :+: mbits :+: _ :+: _) = S.processorArgs inst
cbits :: S.TheProcessor ArcticMI -> Maybe AS.Size
cbits inst = do Nat n <- b
return $ AS.Bits n
where (_ :+: _ :+: _ :+: b :+: _) = S.processorArgs inst
dim :: S.TheProcessor ArcticMI -> Int
dim inst = d where (Nat d :+: _ :+: _ :+: _ :+: _) = S.processorArgs inst
isUargsOn :: S.TheProcessor ArcticMI -> Bool
isUargsOn inst = ua where (_ :+: _ :+: _ :+: _ :+: ua) = S.processorArgs inst
instance PrettyPrintable ArcInt where
pprint MinusInf = text "-inf"
pprint (Fin n) = int n
data MatrixDP = MWithDP | MNoDP deriving Show
data MatrixRelativity = MDirect | MRelative [R.Rule] deriving Show
orientDirect :: P.SolverM m => Prob.Strategy -> Prob.StartTerms -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> m (S.ProofOf ArcticMI)
orientDirect strat st trs sig mp = orientMatrix relativeConstraints ua st trs Trs.empty sig mp
where ua = usableArgsWhereApplicable True sig st (isUargsOn mp) strat trs
orientRelative :: P.SolverM m => Prob.Strategy -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> m (S.ProofOf ArcticMI)
orientRelative strat st strict weak sig mp = orientMatrix relativeConstraints ua st strict weak sig mp
where ua = usableArgsWhereApplicable False sig st (isUargsOn mp) strat (strict `Trs.union` weak)
orientDp :: P.SolverM m => Prob.Strategy -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> m (S.ProofOf ArcticMI)
orientDp strat st strict weak sig mp = orientMatrix dpConstraints ua st strict weak sig mp
where ua = usableArgsWhereApplicable True sig st (isUargsOn mp) strat (strict `Trs.union` weak)
orientPartial :: P.SolverM m => [R.Rule] -> Prob.Strategy -> Prob.StartTerms -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> m (S.ProofOf ArcticMI)
orientPartial oblrules strat st trs sig mp = orientMatrix (partialConstraints oblrules) ua st trs Trs.empty sig mp
where ua = usableArgsWhereApplicable True sig st (isUargsOn mp) strat trs
orientPartialRelative :: P.SolverM m => [R.Rule] -> Prob.Strategy -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> m (S.ProofOf ArcticMI)
orientPartialRelative oblrules strat st strict weak sig mp = orientMatrix (partialConstraints oblrules) ua st strict weak sig mp
where ua = usableArgsWhereApplicable False sig st (isUargsOn mp) strat (strict `Trs.union` weak)
orientPartialDp :: P.SolverM m => [R.Rule] -> Prob.Strategy -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> m (S.ProofOf ArcticMI)
orientPartialDp oblrules strat st strict weak sig mp = orientMatrix (partialConstraints oblrules) ua st strict weak sig mp
where ua = usableArgsWhereApplicable True sig st (isUargsOn mp) strat (strict `Trs.union` weak)
orientMatrix :: P.SolverM m => (UsablePositions -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> DioFormula MiniSatLiteral DioVar ArcInt)
-> UsablePositions -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> m (S.ProofOf ArcticMI)
orientMatrix f ua st dps trs sig mp = do theMI <- P.minisatValue addAct mi
return $ case theMI of
Nothing -> Incompatible
Just mv -> Order $ ArcticOrder (fmap (\x -> x n) mv) ua
where addAct :: MiniSat ()
addAct = toFormula (liftM AS.bound cb) (AS.bound n) (f ua st dps trs sig mp) >>= SatSolver.addFormula
mi = abstractInterpretation UnrestrictedMatrix d (sig `F.restrictToSymbols` Trs.functionSymbols (dps `Trs.union` trs)) :: MatrixInter (AS.Size -> ArcInt)
n = bound mp
cb = cbits mp
d = dim mp
partialConstraints :: Eq l => [R.Rule] -> UsablePositions -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> DioFormula l DioVar ArcInt
partialConstraints oblrules = matrixConstraints (MRelative oblrules) MNoDP
relativeConstraints :: Eq l => UsablePositions -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> DioFormula l DioVar ArcInt
relativeConstraints = matrixConstraints MDirect MNoDP
dpConstraints :: Eq l => UsablePositions -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> DioFormula l DioVar ArcInt
dpConstraints = matrixConstraints MDirect MWithDP
matrixConstraints :: Eq l => MatrixRelativity -> MatrixDP -> UsablePositions -> Prob.StartTerms -> Trs.Trs -> Trs.Trs -> F.Signature -> S.TheProcessor ArcticMI -> DioFormula l DioVar ArcInt
matrixConstraints mrel mdp ua st strict weak sig mp = strictChoice mrel absmi strict && weakTrsConstraints absmi weak && otherConstraints absmi
where absmi = abstractInterpretation UnrestrictedMatrix d (sig `F.restrictToSymbols` Trs.functionSymbols (strict `Trs.union` weak)) :: MatrixInter (DioPoly DioVar ArcInt)
d = dim mp
uaOn = isUargsOn mp
otherConstraints mi = dpChoice mdp st uaOn mi
strictChoice MDirect = strictTrsConstraints
strictChoice (MRelative oblrules) = relativeStricterTrsConstraints oblrules
dpChoice MWithDP _ _ = safeRedpairConstraints sig
dpChoice MNoDP Prob.TermAlgebra {} _ = monotoneConstraints sig
dpChoice MNoDP Prob.BasicTerms {} True = uargMonotoneConstraints sig ua
dpChoice MNoDP Prob.BasicTerms {} False = monotoneConstraints sig
uargMonotoneConstraints :: AbstrOrdSemiring a b => F.Signature -> UsablePositions -> MatrixInter a -> b
uargMonotoneConstraints sig uarg mi = unaryConstraints strictUnaryInts && nullaryConstraints nullaryInts && weakMonotoneConstraints weakUnaryInts
where strictUnaryInts = mi{interpretations = Map.filterWithKey (\ f _ -> isUsable f 1 uarg) $ interpretations unaryInts}
weakUnaryInts = mi{interpretations = Map.filterWithKey (\ f _ -> not $ isUsable f 1 uarg) $ interpretations unaryInts}
unaryInts = mi{interpretations = Map.filterWithKey (\ f _ -> F.arity sig f == 1) $ interpretations mi}
nullaryInts = mi{interpretations = Map.filterWithKey (\ f _ -> F.arity sig f == 0) $ interpretations mi}
monotoneConstraints :: AbstrOrdSemiring a b => F.Signature -> MatrixInter a -> b
monotoneConstraints sig mi = unaryConstraints unaryInts && nullaryConstraints nullaryInts
where unaryInts = mi{interpretations = Map.filterWithKey (\ f _ -> F.arity sig f == 1) $ interpretations mi}
nullaryInts = mi{interpretations = Map.filterWithKey (\ f _ -> F.arity sig f == 0) $ interpretations mi}
safeRedpairConstraints :: AbstrOrdSemiring a b => F.Signature -> MatrixInter a -> b
safeRedpairConstraints sig mi = unaryConstraints unaryCompMI && nullaryConstraints nullaryCompMI && weakMonotoneConstraints noncompMI
where splitInterpretations = Map.partitionWithKey isCompound $ interpretations mi
unaryCompMI = mi{interpretations = Map.filterWithKey (\ f _ -> F.arity sig f == 1) $ interpretations compMI}
nullaryCompMI = mi{interpretations = Map.filterWithKey (\ f _ -> F.arity sig f == 0) $ interpretations compMI}
compMI = mi{interpretations = fst splitInterpretations}
noncompMI = mi{interpretations = snd splitInterpretations}
isCompound f _ = F.isCompound sig f
weakMonotoneConstraints :: AbstrOrdSemiring a b => MatrixInter a -> b
weakMonotoneConstraints = bigAnd . Map.map (\ f -> (vEntry 1 (constant f) .>=. SR.one) || (bigOr $ Map.map ((.>=. SR.one) . entry 1 1) $ coefficients f)) . interpretations
unaryConstraints :: AbstrOrdSemiring a b => MatrixInter a -> b
unaryConstraints mi = unaryMats && unaryVecs
where unaryMats = bigAnd $ Map.map (bigAnd . Map.map ((.>=. SR.one) . entry 1 1) . coefficients) $ interpretations mi
unaryVecs = bigAnd $ Map.map (bigAnd . liftVector (map (.==. SR.zero)) . constant) $ interpretations mi
nullaryConstraints :: AbstrOrdSemiring a b => MatrixInter a -> b
nullaryConstraints mi = bigAnd $ Map.map ((.>=. SR.one) . vEntry 1 . constant) $ interpretations mi
checkDirect :: MatrixInter ArcInt -> Trs.Trs -> F.Signature -> Bool
checkDirect mi trs sig = strictTrsConstraints mi trs && monotoneCheck
where monotoneCheck = unaryCheck && nullaryCheck
unaryCheck = unaryMats && unaryVecs
unaryMats = bigAnd $ Map.map (bigAnd . Map.map ((.>=. SR.one) . entry 1 1) . coefficients) unaryInts
unaryVecs = bigAnd $ Map.map (bigAnd . liftVector (map (.==. SR.zero)) . constant) $ unaryInts
unaryInts = Map.filterWithKey (\ f _ -> F.arity sig f == 1) $ interpretations mi
nullaryCheck = bigAnd $ Map.map ((.>=. SR.one) . vEntry 1 . constant) $ nullaryInts
nullaryInts = Map.filterWithKey (\ f _ -> F.arity sig f == 0) $ interpretations mi
strictRules :: MatrixInter ArcInt -> Trs.Trs -> Trs.Trs
strictRules mi = Trs.filterRules $ strictRuleConstraints mi
class AIEntry a
instance AIEntry ArcInt
instance AIEntry (DioPoly DioVar ArcInt)
instance AIEntry (DioFormula l DioVar ArcInt)
instance AIEntry a => AIEntry (Vector a)
instance (AbstrEq a b, AIEntry a) => AbstrEq (Vector a) b where
(Vector vs) .==. (Vector ws) = bigAnd $ zipWith (.==.) vs ws
instance (AbstrOrd a b, AIEntry a) => AbstrOrd (Vector a) b where
(Vector vs) .<. (Vector ws) = bigAnd $ zipWith (.<.) vs ws
(Vector vs) .<=. (Vector ws) = bigAnd $ zipWith (.<=.) vs ws
instance (AbstrEq a b, AIEntry a) => AbstrEq (Matrix a) b where
(Matrix vs) .==. (Matrix ws) = (Vector vs) .==. (Vector ws)
instance (AbstrOrd a b, AIEntry a) => AbstrOrd (Matrix a) b where
(Matrix vs) .<. (Matrix ws) = (Vector vs) .<. (Vector ws)
(Matrix vs) .<=. (Matrix ws) = (Vector vs) .<=. (Vector ws)
instance (AbstrEq a b, AIEntry a) => AbstrEq (LInter a) b where
(LI lcoeffs lconst) .==. (LI rcoeffs rconst) = bigAnd (Map.elems zipmaps) && lconst .==. rconst
where zipmaps = Map.intersectionWith (.==.) lcoeffs rcoeffs
instance (AbstrOrd a b, AIEntry a) => AbstrOrd (LInter a) b where
(LI lcoeffs lconst) .<. (LI rcoeffs rconst) = bigAnd (Map.elems zipmaps) && lconst .<. rconst
where zipmaps = Map.intersectionWith (.<.) lcoeffs rcoeffs
(LI lcoeffs lconst) .<=. (LI rcoeffs rconst) = bigAnd (Map.elems zipmaps) && lconst .<=. rconst
where zipmaps = Map.intersectionWith (.<=.) lcoeffs rcoeffs
instance (Ord l, SatSolver.Solver s l) => MSemiring s l (AS.ArcFormula l) DioVar ArcInt where
plus = AS.mAdd
prod = AS.mTimes
zero = AS.arcToFormula MinusInf
one = AS.arcToFormula $ Fin 0
geq = (AS.mGeq)
grt = (AS.mGrt)
equ = (AS.mEqu)
constToFormula = AS.arcToFormula
formAtom = AS.arcAtomM . AS.Bound
truncFormTo = AS.mTruncTo
padFormTo n f = AS.padBots (max n l - l) f
where l = length $ snd f
instance SatSolver.Decoder (MatrixInter (AS.Size -> ArcInt)) (AS.ArcBZVec DioVar) where
add (AS.InfBit (DioVar y)) mi = case cast y of
Nothing -> mi
Just x -> mi{interpretations = Map.adjust newli fun (interpretations mi)}
where newli li | pos == 0 = li{constant = adjustv newval i (constant li)}
newli li | otherwise = li{coefficients = newli' li}
newli' li = Map.adjust newm (V.Canon pos) (coefficients li)
newm = adjustm newval i j
newval _ _ = MinusInf
fun = varfun x
pos = argpos x
i = varrow x
j = varcol x
add (AS.BZVec (DioVar y) k) mi = case cast y of
Nothing -> mi
Just x -> mi{interpretations = Map.adjust newli fun (interpretations mi)}
where newli li | pos == 0 = li{constant = adjustv newval i (constant li)}
newli li | otherwise = li{coefficients = newli' li}
newli' li = Map.adjust newm (V.Canon pos) (coefficients li)
newm = adjustm newval i j
newval old n = newval' (old n) n
newval' MinusInf _ = MinusInf
newval' (Fin old) n = Fin $ (f k) old (2 ^ ((if r then 1 else AS.bits n) - k))
f k' = if k' == 1 then (Prelude.+) else (Prelude.+)
r = restrict x
fun = varfun x
pos = argpos x
i = varrow x
j = varcol x
| mzini/TcT | source/Tct/Method/Matrix/ArcticMI.hs | gpl-3.0 | 20,450 | 0 | 20 | 6,315 | 5,853 | 3,006 | 2,847 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module NetService.PlotChart
where
import Control.Lens
import Data.Colour
import Data.Colour.Names
import Data.Default.Class
import qualified Data.Maybe as Maybe
import qualified Data.Time as Time
import Graphics.Rendering.Chart
import Graphics.Rendering.Chart.Backend.Cairo
import Lib (tzAsiaTokyo)
import qualified Model
-- |
--
data ChartData = ChartData
{ cSize :: (Int, Int)
, cTitle :: String
, cOhlcvs :: [Model.Ohlcv]
}
-- |
--
chart :: ChartData -> Renderable ()
chart chartData =
toRenderable layout
where
layout = layout_title .~ cTitle chartData
$ layout_background .~ solidFillStyle (withOpacity white 0.9)
$ layout_right_axis_visibility . axis_show_labels .~ True
$ layout_right_axis_visibility . axis_show_line .~ True
$ layout_right_axis_visibility . axis_show_ticks .~ True
$ layout_plots .~ [toPlot candle]
$ def
candle = plot_candle_line_style .~ lineStyle 1 black
$ plot_candle_fill .~ True
$ plot_candle_rise_fill_style .~ solidFillStyle (opaque red)
$ plot_candle_fall_fill_style .~ solidFillStyle (opaque blue)
$ plot_candle_tick_length .~ 0
$ plot_candle_width .~ 2
$ plot_candle_values .~ mapOhlcvs (cOhlcvs chartData)
$ def
mapOhlcvs :: [Model.Ohlcv] -> [Candle Time.LocalTime Double]
mapOhlcvs = Maybe.mapMaybe fromOhlcv
fromOhlcv :: Model.Ohlcv -> Maybe (Candle Time.LocalTime Double)
fromOhlcv Model.Ohlcv{..} = do
candle_x <- Just (Time.utcToLocalTime tzAsiaTokyo ohlcvAt)
candle_low <- ohlcvLow
candle_open <- ohlcvOpen
candle_mid <- Just 0
candle_close<- ohlcvClose
candle_high <- ohlcvHigh
Just Candle{..}
lineStyle n colour = line_width .~ n
$ line_color .~ opaque colour
$ def
-- |
--
plotSVG :: FilePath -> ChartData -> IO (PickFn ())
plotSVG fpath chartData =
renderableToFile (FileOptions (cSize chartData) SVG) fpath $ chart chartData
-- |
--
plotPNG :: FilePath -> ChartData -> IO (PickFn ())
plotPNG fpath chartData =
renderableToFile (FileOptions (cSize chartData) PNG) fpath $ chart chartData
| ak1211/tractor | src/NetService/PlotChart.hs | agpl-3.0 | 2,487 | 0 | 22 | 777 | 614 | 321 | 293 | -1 | -1 |
module Fusc where
fusc :: Int -> Int
fusc 0 = 0
fusc 1 = 1
fusc n
|even n = fusc $ div n 2
|otherwise = (fusc $ div n 2) + (fusc $ 1 + div n 2)
--
| ice1000/OI-codes | codewars/authoring/haskell/Fusc.hs | agpl-3.0 | 155 | 0 | 9 | 50 | 97 | 48 | 49 | 7 | 1 |
module HLol.API.Stats (
getRankedStats,
getSummaries
) where
import HLol.Data.Stats (RankedStatsDto, PlayerStatsSummaryListDto)
import HLol.Network.Rest
getRankedStats :: Int -> IO (Either LolError RankedStatsDto)
getRankedStats summonerId = get $ "/v1.3/stats/by-summoner/" ++ show summonerId ++ "/ranked"
getSummaries :: Int -> IO (Either LolError PlayerStatsSummaryListDto)
getSummaries summonerId = get $ "/v1.3/stats/by-summoner/" ++ show summonerId ++ "/summary"
| tetigi/hlol | src/HLol/API/Stats.hs | agpl-3.0 | 484 | 0 | 8 | 66 | 121 | 65 | 56 | 9 | 1 |
module Main where
import qualified AG.J2SAttrSem as AGS
import System.Environment
import UU.Parsing
import J2s.Parser
import J2s.Scanner
import UU.Scanner.Position
import Data.String.Utils
-- AST generation
{-
main :: IO()
main = do
g <- readJavaFile
putStrLn (show g)
readJavaFile = do
[path] <- getArgs
entrada <- readFile path
let tokens = classify (initPos path) entrada
nameScalaFile = replace ".java" ".scala" path
scalaCode <- parseIO pJ2s tokens
return scalaCode
-}
-- AG Generation
main :: IO()
main = do
g <- readJavaFile
writeScalaFile (snd g) (fst g)
readJavaFile = do
[path] <- getArgs
entrada <- readFile path
let tokens = classify (initPos path) entrada
nameScalaFile = replace ".java" ".scala" path
scalaCode <- parseIO pJ2s tokens
return (scalaCode, nameScalaFile)
writeScalaFile nameFile content = do
writeFile nameFile content
putStrLn (" Writing scala file " ++ nameFile ++ "..... ")
| andreagenso/java2scala | src/Main.hs | apache-2.0 | 1,006 | 0 | 12 | 236 | 205 | 106 | 99 | 22 | 1 |
module Tables.A268978 (a268978) where
import Data.List (genericLength)
import Helpers.Table (triangleByRows)
import Tables.A007318 (a007318_row)
a268978 :: Integer -> Integer
a268978 i = a268978_t n k where
(n, k) = (n' + 1, k' + 1)
(n', k') = triangleByRows (i - 1)
a268978_t :: Integer -> Integer -> Integer
a268978_t n k = genericLength $ filter divisibleByK firstNRows where
firstNRows = concatMap a007318_row [0..n - 1]
divisibleByK i = i `mod` k == 0
| peterokagey/haskellOEIS | src/Tables/A268978.hs | apache-2.0 | 467 | 0 | 9 | 83 | 184 | 101 | 83 | 12 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Hrpg.Framework.Mobs.Mob
( Mob (..)
, mobCombatData
, isMobDead
, spawnMob
) where
import Control.Monad
import Control.Monad.Random
import Data.Text
import Data.UUID
import Hrpg.Framework.Combat.CombatData
import Hrpg.Framework.Items.Item
import Hrpg.Framework.Items.LootTable
import Hrpg.Framework.Equipment
import Hrpg.Framework.Level
import Hrpg.Framework.Mobs.MobType
import Hrpg.Framework.Stats
data Mob = Mob
{ mobSpawnId :: UUID
, mobType :: MobType
, mobLevel :: Level
, mobCurrentHp :: Int
, mobEquipment :: Equipment
, mobInventory :: [Item]
} deriving Show
mobStats :: Mob -> Stats
mobStats m = mobTypeBaseStats (mobType m) + (statsFromEquipment $ mobEquipment m)
mobCombatData :: Mob -> CombatData
mobCombatData m =
CombatData
{ level = mobLevel m
, weapon = equippedWeapon $ mobEquipment m
, stats = mobStats m
}
isMobDead :: Mob -> Bool
isMobDead Mob { mobCurrentHp } = mobCurrentHp <= 0
spawnItems :: MonadRandom m => (Maybe LootTable) -> m [Item]
spawnItems Nothing = return []
spawnItems (Just table) = do
i <- chooseAndCreateItem table
case i of
Nothing -> return []
Just item -> return [item] -- If it is usable the mob should equip!
chooseLevel :: MonadRandom m => Level -> Level -> m Level
chooseLevel (Level min) (Level max) = do
l <- getRandomR (min, max)
return (Level l)
spawnMob :: MonadRandom m => MobType -> m Mob
spawnMob t = do
uuid <- getRandom
level <- chooseLevel (mobTypeMinLevel t) (mobTypeMaxLevel t)
items <- spawnItems $ mobTypeLootTable t
return (Mob
{ mobSpawnId = uuid
, mobType = t
, mobLevel = level
, mobCurrentHp = (mobTypeMaxHp t)
, mobEquipment = noEquippedItems
, mobInventory = items
})
| cwmunn/hrpg | src/Hrpg/Framework/Mobs/Mob.hs | bsd-3-clause | 1,888 | 0 | 12 | 438 | 560 | 306 | 254 | 59 | 2 |
module LambdaQuest.SystemF.Parse where
import LambdaQuest.SystemF.Type
import Text.Parsec
import qualified Text.Parsec.Token as PT
import Data.List (elemIndex)
import Data.Foldable (foldl')
import Data.Void
import qualified LambdaQuest.Common.Parse as CP
type Parser = Parsec String ()
class ExtraTypeParser x where
extraSimpleTypeExpr :: Parser (TypeT x)
defaultType :: Parser (TypeT x)
extraSimpleTypeExpr = parserZero
defaultType = parserZero
instance ExtraTypeParser Void
data NameBinding = NVarBind String
| NAnonymousBind
| NTyVarBind String
deriving (Eq,Show)
builtinFunctions :: [(String,PrimValue)]
builtinFunctions = [("negateInt",PVBuiltinUnary BNegateInt)
,("negateReal",PVBuiltinUnary BNegateReal)
,("intToReal",PVBuiltinUnary BIntToReal)
,("addInt",PVBuiltinBinary BAddInt)
,("subInt",PVBuiltinBinary BSubInt)
,("mulInt",PVBuiltinBinary BMulInt)
,("ltInt",PVBuiltinBinary BLtInt)
,("leInt",PVBuiltinBinary BLeInt)
,("equalInt",PVBuiltinBinary BEqualInt)
,("addReal",PVBuiltinBinary BAddReal)
,("subReal",PVBuiltinBinary BSubReal)
,("mulReal",PVBuiltinBinary BMulReal)
,("divReal",PVBuiltinBinary BDivReal)
,("ltReal",PVBuiltinBinary BLtReal)
,("leReal",PVBuiltinBinary BLeReal)
,("equalReal",PVBuiltinBinary BEqualReal)
,("unit",PVUnit)
]
langDef = PT.LanguageDef { PT.commentStart = ""
, PT.commentEnd = ""
, PT.commentLine = ""
, PT.nestedComments = False
, PT.identStart = letter <|> char '_'
, PT.identLetter = alphaNum <|> char '_'
, PT.opStart = oneOf ":!#$%&*+./<=>?@\\^|-~"
, PT.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~"
, PT.reservedNames = ["if","then","else","True","False","forall","as","Int","Real","Bool","let","in"] ++ map fst builtinFunctions
, PT.reservedOpNames = []
, PT.caseSensitive = True
}
tokenParser = PT.makeTokenParser langDef
identifier = PT.identifier tokenParser :: Parser String
reserved = PT.reserved tokenParser :: String -> Parser ()
operator = PT.operator tokenParser :: Parser String
reservedOp = PT.reservedOp tokenParser :: String -> Parser ()
naturalOrFloat = CP.naturalOrFloat tokenParser :: Parser (Either Integer Double)
symbol = PT.symbol tokenParser :: String -> Parser String
parens = PT.parens tokenParser
braces = PT.braces tokenParser
brackets = PT.brackets tokenParser
whiteSpace = PT.whiteSpace tokenParser
simpleTypeExpr :: (ExtraTypeParser a) => [NameBinding] -> Parser (TypeT a)
simpleTypeExpr ctx = (reserved "Int" >> return TyInt)
<|> (reserved "Real" >> return TyReal)
<|> (reserved "Bool" >> return TyBool)
<|> (reserved "Unit" >> return TyUnit)
<|> parens (typeExpr ctx)
<|> (do name <- identifier <?> "type variable"
case NTyVarBind name `elemIndex` ctx of
Just i -> return (TyRef i name)
Nothing -> fail ("undefined type variable: " ++ name))
<|> extraSimpleTypeExpr
<?> "simple type expression"
arrTypeExpr :: (ExtraTypeParser a) => [NameBinding] -> Parser (TypeT a)
arrTypeExpr ctx = do a <- simpleTypeExpr ctx
(reservedOp "->" >> (TyArr a <$> arrTypeExpr (NAnonymousBind : ctx)))
<|> return a
<?> "type expression"
typeExpr :: (ExtraTypeParser a) => [NameBinding] -> Parser (TypeT a)
typeExpr ctx = forallExpr <|> arrTypeExpr ctx
<?> "type expression"
where forallExpr = do reserved "forall"
name <- identifier <?> "type variable"
reservedOp "."
t <- typeExpr (NTyVarBind name : ctx)
return (TyAll name t)
simpleTerm :: (ExtraTypeParser a) => [NameBinding] -> Parser (TermT a)
simpleTerm ctx = (reserved "True" >> return (TPrimValue $ PVBool True))
<|> (reserved "False" >> return (TPrimValue $ PVBool False))
<|> (either (TPrimValue . PVInt) (TPrimValue . PVReal) <$> naturalOrFloat <?> "number")
<|> parens (term ctx)
<|> choice [reserved name >> return (TPrimValue v) | (name,v) <- builtinFunctions]
<|> (do name <- identifier <?> "variable"
case NVarBind name `elemIndex` ctx of
Just i -> return (TRef i name)
Nothing -> fail ("undefined variable: " ++ name))
<?> "simple expression"
-- function application / type application
appTerm :: (ExtraTypeParser a) => [NameBinding] -> Parser (TermT a)
appTerm ctx = do x <- simpleTerm ctx
xs <- many ((flip TApp <$> simpleTerm ctx)
<|> (flip TTyApp <$> brackets (typeExpr ctx)))
return (foldl' (flip ($)) x xs)
term :: (ExtraTypeParser a) => [NameBinding] -> Parser (TermT a)
term ctx = lambdaAbstraction
<|> typeAbstraction
<|> letIn
<|> ifThenElse
<|> appTerm ctx
<?> "expression"
where lambdaAbstraction = do reservedOp "\\"
name <- identifier
varType <- (reservedOp ":" >> typeExpr ctx) <|> defaultType
reservedOp "."
body <- term (NVarBind name : ctx)
return (TAbs name varType body)
typeAbstraction = do reservedOp "?"
name <- identifier
reservedOp "."
body <- term (NTyVarBind name : ctx)
return (TTyAbs name body)
letIn = do reserved "let"
name <- identifier
reservedOp "="
definition <- term ctx
reserved "in"
body <- term (NVarBind name : ctx)
return $ TLet name definition body
ifThenElse = do reserved "if"
cond <- term ctx
reserved "then"
thenExpr <- term ctx
reserved "else"
elseExpr <- term ctx
return (TIf cond thenExpr elseExpr)
parseType :: SourceName -> String -> Either ParseError Type
parseType name input = parse wholeParser name input
where wholeParser = do
whiteSpace
t <- typeExpr []
eof
return t
parseTerm :: SourceName -> String -> Either ParseError Term
parseTerm name input = parse wholeParser name input
where wholeParser = do
whiteSpace
t <- term []
eof
return t
| minoki/LambdaQuest | src/LambdaQuest/SystemF/Parse.hs | bsd-3-clause | 7,340 | 0 | 16 | 2,738 | 1,959 | 992 | 967 | 146 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module CacheDNS.APP.CmdParser
( parseConfigOptions
) where
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import Control.Applicative
import Control.Exception (Exception, IOException, catch)
import Data.Monoid ((<>))
import Prelude hiding (id)
import Data.Maybe
import qualified Data.ByteString.Lazy as L
import Data.Aeson (decode', FromJSON(..), Value(..), (.:),(.:?) )
import Options.Applicative
import CacheDNS.APP.Types
data Options = Options
{ _config :: Maybe String
} deriving (Show)
instance FromJSON DNSServer where
parseJSON (Object v) = DNSServer <$> v .: "host"
<*> v .: "port"
<*> v .:? "method"
<*> v .:? "password"
parseJSON _ = empty
instance FromJSON GlobalConfig where
parseJSON (Object v) = GlobalConfig <$> v .: "server"
<*> v .: "stype"
<*> v .:? "nserver"
<*> v .:? "cserver"
<*> v .:? "chinese"
parseJSON _ = empty
readConfig :: FilePath -> IO (Maybe GlobalConfig)
readConfig fp = decode' <$> L.readFile fp
configOptions :: Parser Options
configOptions = Options
<$> optional (strOption (long "config" <> short 'c' <> metavar "CONFIG"
<> help "path to config file"))
parseConfigOptions :: IO (Maybe GlobalConfig)
parseConfigOptions = do
o <- execParser $ info (helper <*> configOptions)
(fullDesc <> header "CacheDNS - a fast DNS Cache")
let configFile = fromMaybe "CacheDNS.json" (_config o)
mconfig <- readConfig configFile `catch` \(e :: IOException) ->
hPutStrLn stderr ("ERROR: Failed to load " <> show e) >> exitFailure
return mconfig | DavidAlphaFox/CacheDNS | app/CacheDNS/APP/CmdParser.hs | bsd-3-clause | 1,945 | 0 | 15 | 607 | 508 | 275 | 233 | 45 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import System.IO
import Text.XML.Pipe
import Network
import Network.PeyoTLS.ReadFile
import Network.XmlPush.HttpPull.Tls.Client
import TestPusher
main :: IO ()
main = do
h <- connectTo "localhost" $ PortNumber 443
ca <- readCertificateStore ["certs/cacert.sample_pem"]
k <- readKey "certs/yoshikuni.sample_key"
c <- readCertificateChain ["certs/yoshikuni.sample_crt"]
testPusher (undefined :: HttpPullTlsCl Handle) (One h) (HttpPullTlsClArgs
(HttpPullClArgs "localhost" 443 "/" gtPth mkPoll
pendingQ (Just 10000000) drtn)
(TlsArgs "localhost" True (const Nothing)
["TLS_RSA_WITH_AES_128_CBC_SHA"] ca [(k, c)]) )
mkPoll :: IO XmlNode
mkPoll = return $ XmlNode (nullQ "poll") [] [] []
pendingQ :: XmlNode -> Bool
pendingQ (XmlNode (_, "nothing") _ [] []) = False
pendingQ _ = True
drtn :: XmlNode -> Maybe Int
drtn (XmlNode (_, "slow") _ [] []) = Just 20000000
drtn (XmlNode (_, "medium") _ [] []) = Just 10000000
drtn (XmlNode (_, "fast") _ [] []) = Just 5000000
drtn (XmlNode (_, "very_fast") _ [] []) = Just 1000000
drtn (XmlNode (_, "fastest") _ [] []) = Just 100000
drtn _ = Nothing
gtPth :: XmlNode -> FilePath
gtPth (XmlNode (_, "father") _ [] []) = "family"
gtPth _ = "others"
| YoshikuniJujo/xml-push | examples/httpPullTlsCl.hs | bsd-3-clause | 1,240 | 8 | 13 | 202 | 519 | 269 | 250 | 33 | 1 |
module Main where
import System.Environment (getArgs, getProgName)
import Control.Exception (bracketOnError)
import System.IO (openTempFile, Handle, hClose, hPutStr, hFlush, stdout)
import System.Directory (removeFile, renameFile, doesFileExist, createDirectoryIfMissing, getHomeDirectory)
import Data.List (delete)
import Control.Monad (liftM, join, unless)
import System.FilePath ((</>), takeDirectory)
import Safe (readMay, atMay)
import System.Exit (exitSuccess)
import Control.Applicative ((<$>), (<*>))
-- TODO: There's a whole lot of file IO with no exception handling in sight!
------------ Config ------------
-- | Change this to Just a filepath to specify the location of your todo list
-- files. Leave as Nothing to default to ~/Dropbox/Apps/TaskAgent
customListDirectory :: Maybe FilePath
customListDirectory = Nothing
------- Type definitions -------
type List = [Item]
data Item = Complete { body :: String }
| Incomplete { body :: String }
deriving (Eq)
instance Show Item where
show (Complete str) = "x " ++ str
show (Incomplete str) = "- " ++ str
------------ Logic ------------
parseItem :: String -> Maybe Item
parseItem ('-':' ':xs) = Just (Incomplete xs)
parseItem ('x':' ':xs) = Just (Complete xs)
parseItem _ = Nothing
-- TODO: Ignore empty lines
parseList :: String -> Maybe List
parseList = mapM parseItem . lines
numberList :: List -> String
numberList = unlines . zipWith (\n i -> show n ++ " " ++ body i) ([1..]::[Int]) . filter isIncomplete
serialiseList :: List -> String
serialiseList = unlines . map show
checkOffItem :: List -> Int -> Maybe List
checkOffItem list n = liftM (\i -> Complete (body i) : delete i list) (atMay (filter isIncomplete list) n)
isIncomplete :: Item -> Bool
isIncomplete (Incomplete _) = True
isIncomplete (Complete _) = False
usageText :: IO String
usageText = do
name <- getProgName
return $ unlines [ "Usage: " ++ name ++ " [new] [NUM]"
, ""
, name ++ " - list items"
, name ++ " new - create new item"
, name ++ " NUM - check-off item NUM"
, name ++ " -v - show version info"
]
versionText :: String
versionText = unlines [ "Todo 0.1 - a TaskAgent-compatible todo list manager"
, "(c) 2013 Alex Sayers; licence: BSD 3-Clause." ]
------------- IO --------------
main :: IO ()
main = do
args <- getArgs
defaultList >>= doesFileExist >>= flip unless (promptToCreate >> exitSuccess)
case args of
[] -> putStr . numberList =<< loadList =<< defaultList
["new"] -> join $ addTodo <$> defaultList <*> getLine
["-v"] -> putStr versionText
[n] -> case readMay n :: Maybe Int of
Just n' -> completeTodo n' =<< defaultList
Nothing -> putStr =<< usageText
_ -> putStr =<< usageText
promptToCreate :: IO ()
promptToCreate = do
path <- defaultList
response <- query $ "No list found at " ++ path ++ ". Create one? [Yn] "
unless (response == "n") $ do
createDirectoryIfMissing True $ takeDirectory path
writeFile path ""
loadList :: FilePath -> IO List
loadList path = do
file <- readFile path
case parseList file of
Nothing -> error "Couldn't parse list"
Just list -> return list
addTodo :: FilePath -> String -> IO ()
addTodo path item = appendFile path $ show (Incomplete item) ++ "\n"
-- TODO: Perhaps switch to strict IO so dropbox doesn't start synching temporary files
-- TODO: Print item which was checked off
completeTodo :: Int -> FilePath -> IO ()
completeTodo n path = do
list <- loadList path
case checkOffItem list (n-1) of
Nothing -> error "Item not found"
Just list' -> do
tempName <- withTempFile "todo-" $ \handle ->
hPutStr handle $ serialiseList list'
removeFile path
renameFile tempName path
------- Path resolution --------
defaultList :: IO FilePath
defaultList = do
path <- listDirectory
return $ path </> "todo.txt"
listDirectory :: IO FilePath
listDirectory = case customListDirectory of
Nothing -> defaultListDirectory
Just path -> return path
defaultListDirectory :: IO FilePath
defaultListDirectory = do
home <- getHomeDirectory
return $ home </> "Dropbox" </> "Apps" </> "TaskAgent"
----------- Helpers ------------
-- | Creates a file in the working directory, named by suffixing str with a
-- random number. Its handle is passed to fn. If there is an exception, the
-- file is closed and deleted. Returns the name of the created file.
withTempFile :: String -> (Handle -> IO ()) -> IO FilePath
withTempFile str fn = do
dir <- listDirectory
bracketOnError (openTempFile dir str)
(\(n,h) -> hClose h >> removeFile n)
(\(n,h) -> fn h >> hClose h >> return n)
query :: String -> IO String
query q = do
putStr q
hFlush stdout
getLine
| asayers/TaskAgent | todo.hs | bsd-3-clause | 4,973 | 0 | 16 | 1,206 | 1,382 | 712 | 670 | 107 | 6 |
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.UI.SDL.Framerate
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-----------------------------------------------------------------------------
module Graphics.UI.SDL.Framerate
( new
, init
, set
, get
, delay
, FPSManager
) where
import Foreign as Foreign hiding (new)
import Foreign.C
import Prelude hiding (init)
data FPSManagerStruct
type FPSManager = ForeignPtr FPSManagerStruct
sizeOfManager :: Int
sizeOfManager = 16
new :: IO FPSManager
new = do manager <- Foreign.mallocBytes sizeOfManager >>= newForeignPtr finalizerFree
init manager
return manager
-- void SDL_initFramerate(FPSmanager * manager);
foreign import ccall unsafe "SDL_initFramerate" sdlInitFramerate :: Ptr FPSManagerStruct -> IO ()
init :: FPSManager -> IO ()
init manager
= withForeignPtr manager sdlInitFramerate
-- int SDL_setFramerate(FPSmanager * manager, int rate);
foreign import ccall unsafe "SDL_setFramerate" sdlSetFramerate :: Ptr FPSManagerStruct -> Int -> IO Int
set :: FPSManager -> Int -> IO Bool
set manager hz
= withForeignPtr manager $ \fpsPtr ->
do ret <- sdlSetFramerate fpsPtr hz
case ret of
(-1) -> return False
_ -> return True
-- int SDL_getFramerate(FPSmanager * manager);
foreign import ccall unsafe "SDL_getFramerate" sdlGetFramerate :: Ptr FPSManagerStruct -> IO Int
get :: FPSManager -> IO Int
get manager = withForeignPtr manager sdlGetFramerate
-- void SDL_framerateDelay(FPSmanager * manager);
foreign import ccall unsafe "SDL_framerateDelay" sdlFramerateDelay :: Ptr FPSManagerStruct -> IO ()
delay :: FPSManager -> IO ()
delay manager = withForeignPtr manager sdlFramerateDelay
| joelburget/sdl2-gfx | Graphics/UI/SDL/Framerate.hs | bsd-3-clause | 1,926 | 0 | 13 | 363 | 397 | 211 | 186 | -1 | -1 |
module Math.LinearAlgebra.Sparse.Algorithms
(
-- ** Staircase form
module Math.LinearAlgebra.Sparse.Algorithms.Staircase
-- ** Diagonal form
, module Math.LinearAlgebra.Sparse.Algorithms.Diagonal
-- ** Solving linear systems (in integer domain)
, module Math.LinearAlgebra.Sparse.Algorithms.SolveLinear
)
where
import Math.LinearAlgebra.Sparse.Algorithms.Staircase
import Math.LinearAlgebra.Sparse.Algorithms.Diagonal
import Math.LinearAlgebra.Sparse.Algorithms.SolveLinear
| laughedelic/sparse-lin-alg | Math/LinearAlgebra/Sparse/Algorithms.hs | bsd-3-clause | 477 | 0 | 5 | 38 | 64 | 49 | 15 | 8 | 0 |
{-#LANGUAGE TypeSynonymInstances#-}
-----------------------------------------------------------------------------
--
-- Module : Language.Haskell.Pretty.AnnotatedPretty
-- Copyright :
-- License : AllRightsReserved
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- | Pretty Printting for the annotated abstract Syntax
--
-----------------------------------------------------------------------------
module Haskell.Pretty.AnnotatedPretty where
import Haskell.Syntax.AnnotatedSyntax
import Haskell.Syntax.Syntax (list_tycon, SrcLoc(..))
import Haskell.Pretty.PrettyUtils
------------------------- Pretty-Print a Module --------------------
instance Pretty AHsModule where
pretty (AHsModule pos m mbExports imp decls) =
markLine pos $
topLevel (ppHsModuleHeader m mbExports)
(map pretty imp ++
map pretty decls)
-------------------------- Module Header ------------------------------
ppHsModuleHeader :: AModule -> Maybe [AHsExportSpec] -> Doc
ppHsModuleHeader m mbExportList = mySep [ text "module", pretty m,
maybePP (parenList . map pretty) mbExportList,
text "where" ]
instance Pretty AModule where
pretty (AModule modName) = text modName
instance Pretty AHsExportSpec where
pretty (AHsEVar name) = pretty name
pretty (AHsEAbs name) = pretty name
pretty (AHsEThingAll name) = pretty name <> text "(..)"
pretty (AHsEThingWith name nameList) =
pretty name <> (parenList . map pretty $ nameList)
pretty (AHsEModuleContents m) = text "module" <+> pretty m
instance Pretty AHsImportDecl where
pretty (AHsImportDecl pos m qual mbName mbSpecs) =
markLine pos $
mySep [text "import",
if qual then text "qualified" else empty,
pretty m,
maybePP (\m' -> text "as" <+> pretty m') mbName,
maybePP exports mbSpecs]
where
exports (b,specList) =
if b then text "hiding" <+> specs else specs
where specs = parenList . map pretty $ specList
instance Pretty AHsImportSpec where
pretty (AHsIVar name) = pretty name
pretty (AHsIAbs name) = pretty name
pretty (AHsIThingAll name) = pretty name <> text "(..)"
pretty (AHsIThingWith name nameList) =
pretty name <> (parenList . map pretty $ nameList)
------------------------- Declarations ------------------------------
instance Pretty AHsDecl where
pretty (AHsTypeDecl loc name nameList htype) =
blankline $
markLine loc $
mySep ( [text "type", pretty name]
++ map pretty nameList
++ [equals, pretty htype])
pretty (AHsDataDecl loc context name nameList constrList derives) =
blankline $
markLine loc $
mySep ( [text "data", ppHsContext context, pretty name]
++ map pretty nameList)
<+> (myVcat (zipWith (<+>) (equals : repeat (char '|'))
(map pretty constrList))
$$$ ppHsDeriving derives)
pretty (AHsNewTypeDecl pos context name nameList constr derives) =
blankline $
markLine pos $
mySep ( [text "newtype", ppHsContext context, pretty name]
++ map pretty nameList)
<+> equals <+> (pretty constr $$$ ppHsDeriving derives)
--m{spacing=False}
-- special case for empty class declaration
pretty (AHsClassDecl pos context name nameList []) =
blankline $
markLine pos $
mySep ( [text "class", ppHsContext context, pretty name]
++ map pretty nameList)
pretty (AHsClassDecl pos context name nameList declList) =
blankline $
markLine pos $
mySep ( [text "class", ppHsContext context, pretty name]
++ map pretty nameList ++ [text "where"])
$$$ ppBody classIndent (map pretty declList)
-- m{spacing=False}
-- special case for empty instance declaration
pretty (AHsInstDecl pos context name args []) =
blankline $
markLine pos $
mySep ( [text "instance", ppHsContext context, pretty name]
++ map ppHsAType args)
pretty (AHsInstDecl pos context name args declList) =
blankline $
markLine pos $
mySep ( [text "instance", ppHsContext context, pretty name]
++ map ppHsAType args ++ [text "where"])
$$$ ppBody classIndent (map pretty declList)
pretty (AHsDefaultDecl pos htypes) =
blankline $
markLine pos $
text "default" <+> parenList (map pretty htypes)
pretty (AHsTypeSig pos nameList qualType) =
blankline $
markLine pos $
mySep ((punctuate comma . map pretty $ nameList)
++ [text "::", pretty qualType])
pretty (AHsFunBind matches) =
ppBindings (map pretty matches)
pretty (AHsPatBind pos pat rhs whereDecls) =
markLine pos $
myFsep [pretty pat, pretty rhs] $$$ ppWhere whereDecls
pretty (AHsInfixDecl pos assoc prec opList) =
blankline $
markLine pos $
mySep ([pretty assoc, int prec]
++ (punctuate comma . map pretty $ opList))
instance Pretty AHsAssoc where
pretty AHsAssocNone = text "infix"
pretty AHsAssocLeft = text "infixl"
pretty AHsAssocRight = text "infixr"
instance Pretty AHsMatch where
pretty (AHsMatch pos f ps rhs whereDecls) =
markLine pos $
myFsep (lhs ++ [pretty rhs])
$$$ ppWhere whereDecls
where
lhs = case ps of
l:r:ps' | isSymbolName f ->
let hd = [pretty l, pretty f, pretty r] in
if null ps' then hd
else parens (myFsep hd) : map (prettyPrec 2) ps'
_ -> pretty f : map (prettyPrec 2) ps
ppWhere :: [AHsDecl] -> Doc
ppWhere [] = empty
ppWhere l = nest 2 (text "where" $$$ ppBody whereIndent (map pretty l))
------------------------- Data & Newtype Bodies -------------------------
instance Pretty AHsConDecl where
pretty (AHsRecDecl _pos name fieldList) =
pretty name <> (braceList . map ppField $ fieldList)
pretty (AHsConDecl _pos name [l, r]) | isSymbolName name =
myFsep [prettyPrec prec_btype l, pretty name,
prettyPrec prec_btype r]
pretty (AHsConDecl _pos name typeList) =
mySep $ pretty name : map (prettyPrec prec_atype) typeList
ppField :: ([AHsName],AHsBangType) -> Doc
ppField (names, ty) =
myFsepSimple $ (punctuate comma . map pretty $ names) ++
[text "::", pretty ty]
instance Pretty AHsBangType where
prettyPrec _ (AHsBangedTy ty) = char '!' <> ppHsAType ty
prettyPrec p (AHsUnBangedTy ty) = prettyPrec p ty
ppHsDeriving :: [AHsName] -> Doc
ppHsDeriving [] = empty
ppHsDeriving [d] = text "deriving" <+> ppHsQName d
ppHsDeriving ds = text "deriving" <+> parenList (map ppHsQName ds)
------------------------- Types -------------------------
instance Pretty AHsQualType where
pretty (AHsQualType context htype) =
myFsep [ppHsContext context, pretty htype]
ppHsBType :: AHsType -> Doc
ppHsBType = prettyPrec prec_btype
ppHsAType :: AHsType -> Doc
ppHsAType = prettyPrec prec_atype
-- precedences for types
prec_btype, prec_atype :: Int
prec_btype = 1 -- left argument of -> ,
-- or either argument of an infix data constructor
prec_atype = 2 -- argument of type or data constructor, or of a class
instance Pretty AHsType where
prettyPrec p (AHsTyFun a b) = parensIf (p > 0) $
myFsep [ppHsBType a, text "->", pretty b]
prettyPrec _ (AHsTyTuple l) = parenList . map pretty $ l
prettyPrec p (AHsTyApp a b)
| a == alist_tycon = brackets $ pretty b -- special case
| otherwise = parensIf (p > prec_btype) $
myFsep [pretty a, ppHsAType b]
prettyPrec _ (AHsTyVar name) = pretty name
prettyPrec _ (AHsTyCon name) = pretty name
------------------------- Expressions -------------------------
instance Pretty AHsRhs where
pretty (AHsUnGuardedRhs e) = equals <+> pretty e
pretty (AHsGuardedRhss guardList) = myVcat . map pretty $ guardList
instance Pretty AHsGuardedRhs where
pretty (AHsGuardedRhs _pos guard body) =
myFsep [char '|', pretty guard, equals, pretty body]
instance Pretty AHsLiteral where
pretty (AHsInt i) = integer i
pretty (AHsChar c) = text (show c)
pretty (AHsString s) = text (show s)
pretty (AHsFrac r) = double (fromRational r)
-- GHC unboxed literals:
pretty (AHsCharPrim c) = text (show c) <> char '#'
pretty (AHsStringPrim s) = text (show s) <> char '#'
pretty (AHsIntPrim i) = integer i <> char '#'
pretty (AHsFloatPrim r) = float (fromRational r) <> char '#'
pretty (AHsDoublePrim r) = double (fromRational r) <> text "##"
instance Pretty AHsExp where
pretty (AHsLit l) = pretty l
-- lambda stuff
pretty (AHsInfixApp a op b) = myFsep [pretty a, pretty op, pretty b]
pretty (AHsNegApp e) = myFsep [char '-', pretty e]
pretty (AHsApp a b) = myFsep [pretty a, pretty b]
pretty (AHsLambda _loc expList body) = myFsep $
char '\\' : map pretty expList ++ [text "->", pretty body]
-- keywords
pretty (AHsLet expList letBody) =
myFsep [text "let" <+> ppBody letIndent (map pretty expList),
text "in", pretty letBody]
pretty (AHsIf cond thenexp elsexp) =
myFsep [text "if", pretty cond,
text "then", pretty thenexp,
text "else", pretty elsexp]
pretty (AHsCase cond altList) =
myFsep [text "case", pretty cond, text "of"]
$$$ ppBody caseIndent (map pretty altList)
pretty (AHsDo stmtList) =
text "do" $$$ ppBody doIndent (map pretty stmtList)
-- Constructors & Vars
pretty (AHsVar name) = pretty name
pretty (AHsCon name) = pretty name
pretty (AHsTuple expList) = parenList . map pretty $ expList
-- weird stuff
pretty (AHsParen e) = parens . pretty $ e
pretty (AHsLeftSection e op) = parens (pretty e <+> pretty op)
pretty (AHsRightSection op e) = parens (pretty op <+> pretty e)
pretty (AHsRecConstr c fieldList) =
pretty c <> (braceList . map pretty $ fieldList)
pretty (AHsRecUpdate e fieldList) =
pretty e <> (braceList . map pretty $ fieldList)
-- patterns
-- special case that would otherwise be buggy
pretty (AHsAsPat name (AHsIrrPat e)) =
myFsep [pretty name <> char '@', char '~' <> pretty e]
pretty (AHsAsPat name e) = hcat [pretty name, char '@', pretty e]
pretty AHsWildCard = char '_'
pretty (AHsIrrPat e) = char '~' <> pretty e
-- Lists
pretty (AHsList list) =
bracketList . punctuate comma . map pretty $ list
pretty (AHsEnumFrom e) =
bracketList [pretty e, text ".."]
pretty (AHsEnumFromTo from to) =
bracketList [pretty from, text "..", pretty to]
pretty (AHsEnumFromThen from thenE) =
bracketList [pretty from <> comma, pretty thenE, text ".."]
pretty (AHsEnumFromThenTo from thenE to) =
bracketList [pretty from <> comma, pretty thenE,
text "..", pretty to]
pretty (AHsListComp e stmtList) =
bracketList ([pretty e, char '|']
++ (punctuate comma . map pretty $ stmtList))
pretty (AHsExpTypeSig _pos e ty) =
myFsep [pretty e, text "::", pretty ty]
------------------------- Patterns -----------------------------
instance Pretty AHsPat where
prettyPrec _ (AHsPVar name) = pretty name
prettyPrec _ (AHsPLit lit) = pretty lit
prettyPrec _ (AHsPNeg p) = myFsep [char '-', pretty p]
prettyPrec p (AHsPInfixApp a op b) = parensIf (p > 0) $
myFsep [pretty a, pretty (AHsQConOp op), pretty b]
prettyPrec p (AHsPApp n ps) = parensIf (p > 1) $
myFsep (pretty n : map pretty ps)
prettyPrec _ (AHsPTuple ps) = parenList . map pretty $ ps
prettyPrec _ (AHsPList ps) =
bracketList . punctuate comma . map pretty $ ps
prettyPrec _ (AHsPParen p) = parens . pretty $ p
prettyPrec _ (AHsPRec c fields) =
pretty c <> (braceList . map pretty $ fields)
-- special case that would otherwise be buggy
prettyPrec _ (AHsPAsPat name (AHsPIrrPat pat)) =
myFsep [pretty name <> char '@', char '~' <> pretty pat]
prettyPrec _ (AHsPAsPat name pat) =
hcat [pretty name, char '@', pretty pat]
prettyPrec _ AHsPWildCard = char '_'
prettyPrec _ (AHsPIrrPat pat) = char '~' <> pretty pat
instance Pretty AHsPatField where
pretty (AHsPFieldPat name pat) =
myFsep [pretty name, equals, pretty pat]
------------------------- Case bodies -------------------------
instance Pretty AHsAlt where
pretty (AHsAlt _pos e gAlts decls) =
myFsep [pretty e, pretty gAlts] $$$ ppWhere decls
instance Pretty AHsGuardedAlts where
pretty (AHsUnGuardedAlt e) = text "->" <+> pretty e
pretty (AHsGuardedAlts altList) = myVcat . map pretty $ altList
instance Pretty AHsGuardedAlt where
pretty (AHsGuardedAlt _pos e body) =
myFsep [char '|', pretty e, text "->", pretty body]
------------------------- Statements in monads & list comprehensions -----
instance Pretty AHsStmt where
pretty (AHsGenerator _loc e from) =
pretty e <+> text "<-" <+> pretty from
pretty (AHsQualifier e) = pretty e
pretty (AHsLetStmt declList) =
text "let" $$$ ppBody letIndent (map pretty declList)
------------------------- Record updates
instance Pretty AHsFieldUpdate where
pretty (AHsFieldUpdate name e) =
myFsep [pretty name, equals, pretty e]
------------------------- Names ------------------------- AQUI
instance Pretty AHsOp where
pretty (AHsQVarOp n) = ppHsQNameInfix n
pretty (AHsQConOp n) = ppHsQNameInfix n
ppHsQNameInfix :: AHsName -> Doc
ppHsQNameInfix name
| isSymbolName name = ppHsQName name
| otherwise = char '`' <> ppHsQName name <> char '`'
instance Pretty AHsName where
pretty name = parensIf (isSymbolName name) (ppHsQName name)
ppHsQName :: AHsName -> Doc
ppHsQName (AUnQual name) = pretty name
ppHsQName (AQual m name) = pretty m <> char '.' <> pretty name
ppHsQName (AHsSpecial s) = pretty s
instance Pretty AHsIdentifier where
pretty (AHsIdent n) = text n
pretty (AHsSymbol n) = text n
instance Pretty AHsCName where
pretty (AHsVarName n) = pretty n
pretty (AHsConName n) = pretty n
isSymbolName :: AHsName -> Bool
isSymbolName n = case getName n of
Left n -> isSymbolId n
Right _ -> False
isSymbolId :: AHsIdentifier -> Bool
isSymbolId (AHsIdent _) = False
isSymbolId _ = True
getName :: AHsName -> Either AHsIdentifier AHsSpecialCon
getName (AQual _ n) = Left n
getName (AUnQual n) = Left n
getName (AHsSpecial s) = Right s
instance Pretty AHsSpecialCon where
pretty = text . specialName
specialName :: AHsSpecialCon -> String
specialName AHsUnitCon = "()"
specialName AHsListCon = "[]"
specialName AHsFunCon = "->"
specialName (AHsTupleCon n) = "(" ++ replicate (n-1) ',' ++ ")"
specialName AHsCons = ":"
ppHsContext :: AHsContext -> Doc
ppHsContext [] = empty
ppHsContext context = mySep [parenList (map ppHsAsst context), text "=>"]
-- hacked for multi-parameter type classes
instance Pretty AHsAsst where
pretty = ppHsAsst
ppHsAsst :: AHsAsst -> Doc
ppHsAsst (a,ts) = myFsep (ppHsQName a : map ppHsAType ts)
| emcardoso/CTi | src/Haskell/Pretty/AnnotatedPretty.hs | bsd-3-clause | 14,573 | 198 | 18 | 3,095 | 5,343 | 2,621 | 2,722 | 312 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Text.Md.ParseUtils (
spaceChar
, skipSpaces
, newlineQuote
, blankline
, blanklines
)
where
import Data.Maybe
import Debug.Trace
import Control.Monad
import Text.Parsec (Stream, ParsecT, (<|>))
import qualified Text.Parsec as P
import qualified Text.ParserCombinators.Parsec as P hiding (runParser, try)
import Text.Md.MdParserDef
-- | Parse one character of ' ' or '\t'.
spaceChar :: Stream s m Char => ParsecT s ParseContext m Char
spaceChar = P.char ' ' <|> P.char '\t'
-- | Skip ' ' or '\t' more than zero times.
skipSpaces :: Stream s m Char => ParsecT s ParseContext m ()
skipSpaces = P.skipMany spaceChar
-- | Parse a newline.
-- This function also handles quote marks at the beginning of lines and update the parser state.
newlineQuote :: Stream s m Char => ParsecT s ParseContext m Char
newlineQuote = do
c <- lineStart <$> P.getState
level <- quoteLevel <$> P.getState
nl <- P.newline
-- `P.optionMaybe (P.try (P.count level xxx))` parses no input if xxx does not occurs `level` times.
isQuoted <- isJust <$> P.optionMaybe (P.try (P.count level (P.char c <* P.optional spaceChar)))
-- consume quotes when `quote` does not occur `level` times
unless isQuoted (void (P.many (P.char c <* P.optional spaceChar)))
P.modifyState (\context -> context { isLastNewLineQuoted = isQuoted })
return nl
-- | Parse a blank line.
blankline :: Stream s m Char => ParsecT s ParseContext m Char
blankline = skipSpaces >> newlineQuote
-- | Parse blank lines.
blanklines :: Stream s m Char => ParsecT s ParseContext m String
blanklines = P.many1 blankline
| tiqwab/md-parser | src/Text/Md/ParseUtils.hs | bsd-3-clause | 1,642 | 0 | 17 | 309 | 433 | 230 | 203 | 31 | 1 |
module DeepBanana.Layer.CUDA.Numeric (
llog
, inv
, lexp
, scale
, scaleByCst
, scaleByCst_
, multiply
, add
, add_
) where
import DeepBanana.Device
import DeepBanana.Layer
import DeepBanana.Layer.CUDA.Monad
import DeepBanana.Prelude
import DeepBanana.Tensor
-- elementwise log (useful for cost fct)
llog :: (Device d, MonadCudaError m, Shape s, TensorScalar a)
=> Layer m a '[] (Tensor d s a) (Tensor d s a)
llog = combinePasses' fwdlog bwdlog
where fwdlog inp = return $ liftFixed1 log inp
bwdlog inp _ = return $ \upgrad ->
unsafeRunCudaError $ liftFixed2 (*) upgrad (liftFixed1 recip inp)
inv :: (Device d, MonadCudaError m, Shape s, TensorScalar a)
=> Layer m a '[] (Tensor d s a) (Tensor d s a)
inv = combinePasses' fwdInv bwdInv
where fwdInv inp = return $ liftFixed1 recip inp
bwdInv inp invinp = return $ \upgrad ->
unsafeRunCudaError $ liftFixed2 (\dy y -> dy * (-(y*y))) upgrad invinp
-- elementwise exponential
lexp :: (Device d, MonadCudaError m, Shape s, TensorScalar a)
=> Layer m a '[] (Tensor d s a) (Tensor d s a)
lexp = combinePasses' fwdExp bwdExp
where fwdExp inp = return $ liftFixed1 exp inp
bwdExp inp einp = return $ \upgrad ->
unsafeRunCudaError $ liftFixed2 (*) upgrad einp
scale :: (Device d, MonadCudaError m, Shape s, TensorScalar a)
=> Layer m a '[] (a, Tensor d s a) (Tensor d s a)
scale = combinePasses' fwdscale bwdscale
where fwdscale (x,y) = return $ liftFixed1 (x *^) y
bwdscale (x,y) _ = return $ \upgrad -> unsafeRunCudaError $ do
case toAnyFixed $ shape y of
AnyFixed fshp -> do
fy <- shapeConvert fshp y
fdy <- shapeConvert fshp upgrad
withValidUniqueDevice (device y) $ \dev' -> do
dfy <- deviceConvert dev' fy
dfdy <- deviceConvert dev' fdy
return (dfy <.> dfdy, liftFixed1 (x *^) upgrad)
scaleByCst :: (Device d, MonadCudaError m, Shape s, TensorScalar a)
=> a -> Layer m a '[] (Tensor d s a) (Tensor d s a)
scaleByCst c = Layer $ \_ x -> do
(y, bwd) <- forwardBackward scale (W Z) (c,x)
return (y, \dy -> let (_,(_,dx)) = bwd dy in (W Z, dx))
scaleByCst_ :: (Monad m, VectorSpace t)
=> Scalar t -> Layer m (Scalar t) '[] t t
scaleByCst_ c = combinePasses' fwdScaleByCst bwdScaleByCst
where fwdScaleByCst t = return $ c *^ t
bwdScaleByCst _ _ = return $ \dy -> c *^ dy
multiply :: (Device d, MonadCudaError m, Shape s, TensorScalar a)
=> Layer m a '[] (Tensor d s a, Tensor d s a) (Tensor d s a)
multiply = combinePasses' fwdMul bwdMul
where fwdMul (x1,x2) = liftFixed2 (*) x1 x2
bwdMul (x1,x2) _ = return $ \upgrad ->
unsafeRunCudaError
$ pure (,)
<*> liftFixed2 (*) x2 upgrad
<*> liftFixed2 (*) x1 upgrad
add :: (Device d, MonadCudaError m, Shape s, TensorScalar a)
=> Layer m a '[] (Tensor d s a, Tensor d s a) (Tensor d s a)
add = combinePasses' fwdadd bwdadd
where fwdadd (x,y) = liftFixed2 (+) x y
bwdadd (x,y) _ = return $ \upgrad -> (upgrad, upgrad)
add_ :: (Monad m, VectorSpace t)
=> Layer m (Scalar t) '[] (t,t) t
add_ = combinePasses' fwdadd bwdadd
where fwdadd (x,y) = return $ x ^+^ y
bwdadd _ _ = return $ \upgrad -> (upgrad, upgrad)
| alexisVallet/deep-banana | src/DeepBanana/Layer/CUDA/Numeric.hs | bsd-3-clause | 3,346 | 0 | 24 | 898 | 1,436 | 748 | 688 | -1 | -1 |
module Lava.Stable where
import Lava.Signal
import Lava.Operators
import Lava.Generic
import Lava.Sequent
import Lava.Ref
import Lava.MyST
( STRef
, newSTRef
, readSTRef
, writeSTRef
, runST
, unsafeInterleaveST
)
import Data.List
( isPrefixOf
)
----------------------------------------------------------------
-- stable analysis
stable :: Generic a => a -> Signal Bool
stable inp =
runST
( do table <- tableST
stableRef <- newSTRef []
let gather (Symbol sym) =
do ms <- findST table sym
case ms of
Just () -> do return ()
Nothing -> do extendST table sym ()
mmap gather (deref sym)
define (Symbol sym) (deref sym)
define out (DelayBool _ inn) =
do addStable (out <==> inn)
define out (DelayInt _ inn) =
do addStable (out <==> inn)
define _ _ =
do return ()
addStable x =
do stables <- readSTRef stableRef
writeSTRef stableRef (x:stables)
in mmap gather (struct inp)
stables <- readSTRef stableRef
return (andl stables)
)
----------------------------------------------------------------
-- the end.
| dfordivam/lava | Lava/Stable.hs | bsd-3-clause | 1,318 | 0 | 22 | 471 | 381 | 185 | 196 | 39 | 4 |
module A
where
aString :: String
aString = "test string"
| 23Skidoo/ghc-parmake | tests/data/executable/A.hs | bsd-3-clause | 65 | 0 | 4 | 18 | 14 | 9 | 5 | 3 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.ShaderAtomicCounters
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/shader_atomic_counters.txt ARB_shader_atomic_counters> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.ShaderAtomicCounters (
-- * Enums
gl_ACTIVE_ATOMIC_COUNTER_BUFFERS,
gl_ATOMIC_COUNTER_BUFFER,
gl_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS,
gl_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES,
gl_ATOMIC_COUNTER_BUFFER_BINDING,
gl_ATOMIC_COUNTER_BUFFER_DATA_SIZE,
gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER,
gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER,
gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER,
gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER,
gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER,
gl_ATOMIC_COUNTER_BUFFER_SIZE,
gl_ATOMIC_COUNTER_BUFFER_START,
gl_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS,
gl_MAX_ATOMIC_COUNTER_BUFFER_SIZE,
gl_MAX_COMBINED_ATOMIC_COUNTERS,
gl_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS,
gl_MAX_FRAGMENT_ATOMIC_COUNTERS,
gl_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS,
gl_MAX_GEOMETRY_ATOMIC_COUNTERS,
gl_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS,
gl_MAX_TESS_CONTROL_ATOMIC_COUNTERS,
gl_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS,
gl_MAX_TESS_EVALUATION_ATOMIC_COUNTERS,
gl_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS,
gl_MAX_VERTEX_ATOMIC_COUNTERS,
gl_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS,
gl_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX,
gl_UNSIGNED_INT_ATOMIC_COUNTER,
-- * Functions
glGetActiveAtomicCounterBufferiv
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/ShaderAtomicCounters.hs | bsd-3-clause | 2,006 | 0 | 4 | 172 | 133 | 96 | 37 | 33 | 0 |
{-# language CPP #-}
-- No documentation found for Chapter "PipelineCacheCreateFlagBits"
module Vulkan.Core10.Enums.PipelineCacheCreateFlagBits ( PipelineCacheCreateFlags
, PipelineCacheCreateFlagBits( PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
, ..
)
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
type PipelineCacheCreateFlags = PipelineCacheCreateFlagBits
-- | VkPipelineCacheCreateFlagBits - Bitmask specifying the behavior of the
-- pipeline cache
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_pipeline_creation_cache_control VK_EXT_pipeline_creation_cache_control>,
-- 'PipelineCacheCreateFlags'
newtype PipelineCacheCreateFlagBits = PipelineCacheCreateFlagBits Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
-- | 'PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT' specifies that all
-- commands that modify the created 'Vulkan.Core10.Handles.PipelineCache'
-- will be
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-threadingbehavior externally synchronized>.
-- When set, the implementation /may/ skip any unnecessary processing
-- needed to support simultaneous modification from multiple threads where
-- allowed.
pattern PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = PipelineCacheCreateFlagBits 0x00000001
conNamePipelineCacheCreateFlagBits :: String
conNamePipelineCacheCreateFlagBits = "PipelineCacheCreateFlagBits"
enumPrefixPipelineCacheCreateFlagBits :: String
enumPrefixPipelineCacheCreateFlagBits = "PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT"
showTablePipelineCacheCreateFlagBits :: [(PipelineCacheCreateFlagBits, String)]
showTablePipelineCacheCreateFlagBits = [(PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT, "")]
instance Show PipelineCacheCreateFlagBits where
showsPrec = enumShowsPrec enumPrefixPipelineCacheCreateFlagBits
showTablePipelineCacheCreateFlagBits
conNamePipelineCacheCreateFlagBits
(\(PipelineCacheCreateFlagBits x) -> x)
(\x -> showString "0x" . showHex x)
instance Read PipelineCacheCreateFlagBits where
readPrec = enumReadPrec enumPrefixPipelineCacheCreateFlagBits
showTablePipelineCacheCreateFlagBits
conNamePipelineCacheCreateFlagBits
PipelineCacheCreateFlagBits
| expipiplus1/vulkan | src/Vulkan/Core10/Enums/PipelineCacheCreateFlagBits.hs | bsd-3-clause | 3,080 | 1 | 10 | 684 | 338 | 205 | 133 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.PrettyPrint.Annotated.HughesPJClass
-- Copyright : (c) Trevor Elliott <[email protected]> 2015
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : David Terei <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- Pretty printing class, simlar to 'Show' but nicer looking.
--
-- Note that the precedence level is a 'Rational' so there is an unlimited
-- number of levels. This module re-exports
-- 'Text.PrettyPrint.Annotated.HughesPJ'.
--
-----------------------------------------------------------------------------
module Text.PrettyPrint.Annotated.HughesPJClass (
-- * Pretty typeclass
Pretty(..),
PrettyLevel(..), prettyNormal,
prettyShow, prettyParen,
-- re-export HughesPJ
module Text.PrettyPrint.Annotated.HughesPJ
) where
import qualified Data.ListLike as LL
import Text.PrettyPrint.Annotated.HughesPJ
-- | Level of detail in the pretty printed output. Level 0 is the least
-- detail.
newtype PrettyLevel = PrettyLevel Int
deriving (Eq, Ord, Show)
-- | The "normal" (Level 0) of detail.
prettyNormal :: PrettyLevel
prettyNormal = PrettyLevel 0
-- | Pretty printing class. The precedence level is used in a similar way as in
-- the 'Show' class. Minimal complete definition is either 'pPrintPrec' or
-- 'pPrint'.
class Pretty a where
pPrintPrec :: PrettyLevel -> Rational -> a -> Doc ann
pPrintPrec _ _ = pPrint
pPrint :: a -> Doc ann
pPrint = pPrintPrec prettyNormal 0
pPrintList :: PrettyLevel -> [a] -> Doc ann
pPrintList l = brackets . fsep . punctuate comma . map (pPrintPrec l 0)
#if __GLASGOW_HASKELL__ >= 708
{-# MINIMAL pPrintPrec | pPrint #-}
#endif
-- | Pretty print a value with the 'prettyNormal' level.
prettyShow :: (Pretty a) => a -> String
prettyShow = (LL.fromListLike :: AString -> String) . render . pPrint
pPrint0 :: (Pretty a) => PrettyLevel -> a -> Doc ann
pPrint0 l = pPrintPrec l 0
appPrec :: Rational
appPrec = 10
-- | Parenthesize an value if the boolean is true.
{-# DEPRECATED prettyParen "Please use 'maybeParens' instead" #-}
prettyParen :: Bool -> Doc ann -> Doc ann
prettyParen = maybeParens
-- Various Pretty instances
instance Pretty Int where pPrint = int
instance Pretty Integer where pPrint = integer
instance Pretty Float where pPrint = float
instance Pretty Double where pPrint = double
instance Pretty () where pPrint _ = text "()"
instance Pretty Bool where pPrint = text . show
instance Pretty Ordering where pPrint = text . show
instance Pretty Char where
pPrint = char
pPrintList _ = text . show
instance (Pretty a) => Pretty (Maybe a) where
pPrintPrec _ _ Nothing = text "Nothing"
pPrintPrec l p (Just x) =
prettyParen (p > appPrec) $ text "Just" <+> pPrintPrec l (appPrec+1) x
instance (Pretty a, Pretty b) => Pretty (Either a b) where
pPrintPrec l p (Left x) =
prettyParen (p > appPrec) $ text "Left" <+> pPrintPrec l (appPrec+1) x
pPrintPrec l p (Right x) =
prettyParen (p > appPrec) $ text "Right" <+> pPrintPrec l (appPrec+1) x
instance (Pretty a) => Pretty [a] where
pPrintPrec l _ = pPrintList l
instance (Pretty a, Pretty b) => Pretty (a, b) where
pPrintPrec l _ (a, b) =
parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b]
instance (Pretty a, Pretty b, Pretty c) => Pretty (a, b, c) where
pPrintPrec l _ (a, b, c) =
parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b, pPrint0 l c]
instance (Pretty a, Pretty b, Pretty c, Pretty d) => Pretty (a, b, c, d) where
pPrintPrec l _ (a, b, c, d) =
parens $ fsep $ punctuate comma
[pPrint0 l a, pPrint0 l b, pPrint0 l c, pPrint0 l d]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e) => Pretty (a, b, c, d, e) where
pPrintPrec l _ (a, b, c, d, e) =
parens $ fsep $ punctuate comma
[pPrint0 l a, pPrint0 l b, pPrint0 l c, pPrint0 l d, pPrint0 l e]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e, Pretty f) => Pretty (a, b, c, d, e, f) where
pPrintPrec l _ (a, b, c, d, e, f) =
parens $ fsep $ punctuate comma
[pPrint0 l a, pPrint0 l b, pPrint0 l c,
pPrint0 l d, pPrint0 l e, pPrint0 l f]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e, Pretty f, Pretty g) =>
Pretty (a, b, c, d, e, f, g) where
pPrintPrec l _ (a, b, c, d, e, f, g) =
parens $ fsep $ punctuate comma
[pPrint0 l a, pPrint0 l b, pPrint0 l c,
pPrint0 l d, pPrint0 l e, pPrint0 l f, pPrint0 l g]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e, Pretty f, Pretty g, Pretty h) =>
Pretty (a, b, c, d, e, f, g, h) where
pPrintPrec l _ (a, b, c, d, e, f, g, h) =
parens $ fsep $ punctuate comma
[pPrint0 l a, pPrint0 l b, pPrint0 l c,
pPrint0 l d, pPrint0 l e, pPrint0 l f, pPrint0 l g, pPrint0 l h]
| ddssff/pretty-listlike | src/Text/PrettyPrint/Annotated/HughesPJClass.hs | bsd-3-clause | 4,886 | 0 | 10 | 1,059 | 1,698 | 919 | 779 | 79 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module DragonCurve (
main
, benchDiagram
) where
import Diagrams.Backend.SVG.CmdLine
import Diagrams.Prelude
import Diagrams.TwoD.Vector
data Tok = F | P | M | X | Y deriving (Eq, Show)
rewriteFunction :: Tok -> [Tok]
rewriteFunction X = [X, P, Y, F, P]
rewriteFunction Y = [M, F, X, M, Y]
rewriteFunction t = [t]
gens :: [[Tok]]
gens = iterate (concatMap rewriteFunction) [F, X]
toks2offsets :: [Tok] -> [R2]
toks2offsets xs = [v | (Just v, _) <- scanl f (Nothing, unitX) xs] where
f (_, dir) F = (Just dir, dir)
f (_, dir) P = (Nothing, perp dir)
f (_, dir) M = (Nothing, negate $ perp dir)
f (_, dir) _ = (Nothing, dir)
genDiagram :: Renderable (Path R2) b => Int -> Diagram b R2
genDiagram = lwL 0.5 . strokeLine . lineFromOffsets . toks2offsets . (!!) gens
benchDiagram :: Renderable (Path R2) b => Diagram b R2
benchDiagram = genDiagram 16
main :: IO ()
main = defaultMain $ genDiagram 16
| diagrams/diagrams-bench | examples/DragonCurve.hs | bsd-3-clause | 977 | 0 | 9 | 218 | 435 | 244 | 191 | 26 | 4 |
{-# LANGUAGE TypeFamilies, QuasiQuotes, OverloadedStrings, PackageImports #-}
import System.IO
import Control.Arrow
import Text.Papillon
import Data.Char
import "monads-tf" Control.Monad.State
type TagIO = StateT ([Xml], [(Name, Attrs)]) IO
readHandle :: Handle -> TagIO [Xml]
readHandle h = do
c <- liftIO $ hGetChar h
case c of
'<' -> do
readHandleTag h
_ -> error "not implemented"
readHandleTail :: Handle -> TagIO [Xml]
readHandleTail h = do
-- get >>= liftIO . print
tgs <- gets snd
ret <- if null tgs then return [] else do
c <- liftIO $ hGetChar h
case c of
'<' -> readHandleTag h
_ -> do tx <- readUntil (== '<') h
(++) <$> readString (c : init tx)
<*> readHandleTag h
-- liftIO $ print ret
return ret
readHandleTag :: Handle -> TagIO [Xml]
readHandleTag h = do
-- get >>= liftIO . print
-- liftIO $ hGetChar h >>= print
tg <- readUntil (== '>') h
(++) <$> readString ('<' : tg) <*> readHandleTail h
readUntil :: (Char -> Bool) -> Handle -> TagIO String
readUntil p h = do
c <- liftIO $ hGetChar h
if p c then return [c] else (c :) <$> readUntil p h
readString :: String -> TagIO [Xml]
readString "" = gets $ reverse . fst
readString tg@('<' : _) = case readTag tg of
Just (OpenTag n as) -> do
modify $ second ((n, as) :)
readString (tail $ dropWhile (/= '>') tg)
Just (CloseTag cn) -> do
ts@((n, as) : _) <- gets snd
let m = case ts of
(on, _) : _ -> cn == on
_ -> False
if not m then error "tag not match" else do
xmls <- gets fst
modify . first $ const []
modify $ second tail
(Node n as (reverse xmls) :) <$>
readString (tail $ dropWhile (/= '>') tg)
_ -> error $ "bad tag: " ++ tg
readString strtg = do
modify $ first (Text str :)
readString tg
where
(str, tg) = span (/= '<') strtg
type Name = (Maybe String, String)
type Attrs = [((Maybe String, String), String)]
data Xml = Node Name Attrs [Xml] | Text String deriving Show
data Tag = OpenTag Name Attrs | CloseTag Name deriving Show
match :: Tag -> Tag -> Bool
match (OpenTag otn _) (CloseTag ctn) = otn == ctn
match _ _ = False
readTag :: String -> Maybe Tag
readTag src = case runError $ tag $ parse src of
Right (t, _) -> Just t
_ -> Nothing
{-
testAttr :: String -> Maybe (String, String)
testAttr src = case runError $ attr $ parse src of
Right (t, _) -> Just t
_ -> Nothing
-}
testString :: String -> Maybe String
testString src = case runError $ string $ parse src of
Right (t, _) -> Just t
_ -> Nothing
[papillon|
tag :: Tag = ot:openTag { ot } / ct:closeTag { ct }
openTag :: Tag
= '<' _:spaces n:name _:spaces as:attrs '>'
{ OpenTag n as }
closeTag :: Tag
= '<' '/' _:spaces n:name '>'
{ CloseTag n }
name :: (Maybe String, String)
= qn:(n:<isAlpha>+ ':' { n })? n:<isAlpha>+
{ (qn, n) }
attrs :: [((Maybe String, String), String)]
= a:attr _:spaces as:attrs { a : as }
/ { [] }
attr :: ((Maybe String, String), String) = n:name '=' s:string { (n, s) }
string :: String
= '"' s:<(/= '"')>* '"' { s }
/ '\'' s:<(/= '\'')>* '\'' { s }
spaces :: () = _:<isSpace>*
|]
| YoshikuniJujo/forest | subprojects/xml/testXml.hs | bsd-3-clause | 3,077 | 4 | 21 | 724 | 1,038 | 530 | 508 | 71 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.PackageDescription.Parse
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This defined parsers and partial pretty printers for the @.cabal@ format.
-- Some of the complexity in this module is due to the fact that we have to be
-- backwards compatible with old @.cabal@ files, so there's code to translate
-- into the newer structure.
module Distribution.PackageDescription.Parse (
-- * Package descriptions
readPackageDescription,
writePackageDescription,
parsePackageDescription,
showPackageDescription,
-- ** Parsing
ParseResult(..),
FieldDescr(..),
LineNo,
-- ** Supplementary build information
readHookedBuildInfo,
parseHookedBuildInfo,
writeHookedBuildInfo,
showHookedBuildInfo,
pkgDescrFieldDescrs,
libFieldDescrs,
executableFieldDescrs,
binfoFieldDescrs,
sourceRepoFieldDescrs,
testSuiteFieldDescrs,
flagFieldDescrs
) where
import Distribution.ParseUtils hiding (parseFields)
import Distribution.PackageDescription
import Distribution.PackageDescription.Utils
import Distribution.Package
import Distribution.ModuleName
import Distribution.Version
import Distribution.Verbosity
import Distribution.Compiler
import Distribution.PackageDescription.Configuration
import Distribution.Simple.Utils
import Distribution.Text
import Distribution.Compat.ReadP hiding (get)
import Data.Char (isSpace)
import Data.Maybe (listToMaybe, isJust)
import Data.List (nub, unfoldr, partition, (\\))
import Control.Monad (liftM, foldM, when, unless, ap)
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid (Monoid(..))
import Control.Applicative (Applicative(..))
#endif
import Control.Arrow (first)
import System.Directory (doesFileExist)
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
import Text.PrettyPrint
-- -----------------------------------------------------------------------------
-- The PackageDescription type
pkgDescrFieldDescrs :: [FieldDescr PackageDescription]
pkgDescrFieldDescrs =
[ simpleField "name"
disp parse
packageName (\name pkg -> pkg{package=(package pkg){pkgName=name}})
, simpleField "version"
disp parse
packageVersion (\ver pkg -> pkg{package=(package pkg){pkgVersion=ver}})
, simpleField "cabal-version"
(either disp disp) (liftM Left parse +++ liftM Right parse)
specVersionRaw (\v pkg -> pkg{specVersionRaw=v})
, simpleField "build-type"
(maybe empty disp) (fmap Just parse)
buildType (\t pkg -> pkg{buildType=t})
, simpleField "license"
disp parseLicenseQ
license (\l pkg -> pkg{license=l})
-- We have both 'license-file' and 'license-files' fields.
-- Rather than declaring license-file to be deprecated, we will continue
-- to allow both. The 'license-file' will continue to only allow single
-- tokens, while 'license-files' allows multiple. On pretty-printing, we
-- will use 'license-file' if there's just one, and use 'license-files'
-- otherwise.
, simpleField "license-file"
showFilePath parseFilePathQ
(\pkg -> case licenseFiles pkg of
[x] -> x
_ -> "")
(\l pkg -> pkg{licenseFiles=licenseFiles pkg ++ [l]})
, listField "license-files"
showFilePath parseFilePathQ
(\pkg -> case licenseFiles pkg of
[_] -> []
xs -> xs)
(\ls pkg -> pkg{licenseFiles=ls})
, simpleField "copyright"
showFreeText parseFreeText
copyright (\val pkg -> pkg{copyright=val})
, simpleField "maintainer"
showFreeText parseFreeText
maintainer (\val pkg -> pkg{maintainer=val})
, simpleField "stability"
showFreeText parseFreeText
stability (\val pkg -> pkg{stability=val})
, simpleField "homepage"
showFreeText parseFreeText
homepage (\val pkg -> pkg{homepage=val})
, simpleField "package-url"
showFreeText parseFreeText
pkgUrl (\val pkg -> pkg{pkgUrl=val})
, simpleField "bug-reports"
showFreeText parseFreeText
bugReports (\val pkg -> pkg{bugReports=val})
, simpleField "synopsis"
showFreeText parseFreeText
synopsis (\val pkg -> pkg{synopsis=val})
, simpleField "description"
showFreeText parseFreeText
description (\val pkg -> pkg{description=val})
, simpleField "category"
showFreeText parseFreeText
category (\val pkg -> pkg{category=val})
, simpleField "author"
showFreeText parseFreeText
author (\val pkg -> pkg{author=val})
, listField "tested-with"
showTestedWith parseTestedWithQ
testedWith (\val pkg -> pkg{testedWith=val})
, listFieldWithSep vcat "data-files"
showFilePath parseFilePathQ
dataFiles (\val pkg -> pkg{dataFiles=val})
, simpleField "data-dir"
showFilePath parseFilePathQ
dataDir (\val pkg -> pkg{dataDir=val})
, listFieldWithSep vcat "extra-source-files"
showFilePath parseFilePathQ
extraSrcFiles (\val pkg -> pkg{extraSrcFiles=val})
, listFieldWithSep vcat "extra-tmp-files"
showFilePath parseFilePathQ
extraTmpFiles (\val pkg -> pkg{extraTmpFiles=val})
, listFieldWithSep vcat "extra-doc-files"
showFilePath parseFilePathQ
extraDocFiles (\val pkg -> pkg{extraDocFiles=val})
]
-- | Store any fields beginning with "x-" in the customFields field of
-- a PackageDescription. All other fields will generate a warning.
storeXFieldsPD :: UnrecFieldParser PackageDescription
storeXFieldsPD (f@('x':'-':_),val) pkg =
Just pkg{ customFieldsPD =
customFieldsPD pkg ++ [(f,val)]}
storeXFieldsPD _ _ = Nothing
-- ---------------------------------------------------------------------------
-- The Library type
libFieldDescrs :: [FieldDescr Library]
libFieldDescrs =
[ listFieldWithSep vcat "exposed-modules" disp parseModuleNameQ
exposedModules (\mods lib -> lib{exposedModules=mods})
, commaListFieldWithSep vcat "reexported-modules" disp parse
reexportedModules (\mods lib -> lib{reexportedModules=mods})
, listFieldWithSep vcat "required-signatures" disp parseModuleNameQ
requiredSignatures (\mods lib -> lib{requiredSignatures=mods})
, boolField "exposed"
libExposed (\val lib -> lib{libExposed=val})
] ++ map biToLib binfoFieldDescrs
where biToLib = liftField libBuildInfo (\bi lib -> lib{libBuildInfo=bi})
storeXFieldsLib :: UnrecFieldParser Library
storeXFieldsLib (f@('x':'-':_), val) l@(Library { libBuildInfo = bi }) =
Just $ l {libBuildInfo =
bi{ customFieldsBI = customFieldsBI bi ++ [(f,val)]}}
storeXFieldsLib _ _ = Nothing
-- ---------------------------------------------------------------------------
-- The Executable type
executableFieldDescrs :: [FieldDescr Executable]
executableFieldDescrs =
[ -- note ordering: configuration must come first, for
-- showPackageDescription.
simpleField "executable"
showToken parseTokenQ
exeName (\xs exe -> exe{exeName=xs})
, simpleField "main-is"
showFilePath parseFilePathQ
modulePath (\xs exe -> exe{modulePath=xs})
]
++ map biToExe binfoFieldDescrs
where biToExe = liftField buildInfo (\bi exe -> exe{buildInfo=bi})
storeXFieldsExe :: UnrecFieldParser Executable
storeXFieldsExe (f@('x':'-':_), val) e@(Executable { buildInfo = bi }) =
Just $ e {buildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}}
storeXFieldsExe _ _ = Nothing
-- ---------------------------------------------------------------------------
-- The TestSuite type
-- | An intermediate type just used for parsing the test-suite stanza.
-- After validation it is converted into the proper 'TestSuite' type.
data TestSuiteStanza = TestSuiteStanza {
testStanzaTestType :: Maybe TestType,
testStanzaMainIs :: Maybe FilePath,
testStanzaTestModule :: Maybe ModuleName,
testStanzaBuildInfo :: BuildInfo
}
emptyTestStanza :: TestSuiteStanza
emptyTestStanza = TestSuiteStanza Nothing Nothing Nothing mempty
testSuiteFieldDescrs :: [FieldDescr TestSuiteStanza]
testSuiteFieldDescrs =
[ simpleField "type"
(maybe empty disp) (fmap Just parse)
testStanzaTestType (\x suite -> suite { testStanzaTestType = x })
, simpleField "main-is"
(maybe empty showFilePath) (fmap Just parseFilePathQ)
testStanzaMainIs (\x suite -> suite { testStanzaMainIs = x })
, simpleField "test-module"
(maybe empty disp) (fmap Just parseModuleNameQ)
testStanzaTestModule (\x suite -> suite { testStanzaTestModule = x })
]
++ map biToTest binfoFieldDescrs
where
biToTest = liftField testStanzaBuildInfo
(\bi suite -> suite { testStanzaBuildInfo = bi })
storeXFieldsTest :: UnrecFieldParser TestSuiteStanza
storeXFieldsTest (f@('x':'-':_), val) t@(TestSuiteStanza { testStanzaBuildInfo = bi }) =
Just $ t {testStanzaBuildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}}
storeXFieldsTest _ _ = Nothing
validateTestSuite :: LineNo -> TestSuiteStanza -> ParseResult TestSuite
validateTestSuite line stanza =
case testStanzaTestType stanza of
Nothing -> return $
emptyTestSuite { testBuildInfo = testStanzaBuildInfo stanza }
Just tt@(TestTypeUnknown _ _) ->
return emptyTestSuite {
testInterface = TestSuiteUnsupported tt,
testBuildInfo = testStanzaBuildInfo stanza
}
Just tt | tt `notElem` knownTestTypes ->
return emptyTestSuite {
testInterface = TestSuiteUnsupported tt,
testBuildInfo = testStanzaBuildInfo stanza
}
Just tt@(TestTypeExe ver) ->
case testStanzaMainIs stanza of
Nothing -> syntaxError line (missingField "main-is" tt)
Just file -> do
when (isJust (testStanzaTestModule stanza)) $
warning (extraField "test-module" tt)
return emptyTestSuite {
testInterface = TestSuiteExeV10 ver file,
testBuildInfo = testStanzaBuildInfo stanza
}
Just tt@(TestTypeLib ver) ->
case testStanzaTestModule stanza of
Nothing -> syntaxError line (missingField "test-module" tt)
Just module_ -> do
when (isJust (testStanzaMainIs stanza)) $
warning (extraField "main-is" tt)
return emptyTestSuite {
testInterface = TestSuiteLibV09 ver module_,
testBuildInfo = testStanzaBuildInfo stanza
}
where
missingField name tt = "The '" ++ name ++ "' field is required for the "
++ display tt ++ " test suite type."
extraField name tt = "The '" ++ name ++ "' field is not used for the '"
++ display tt ++ "' test suite type."
-- ---------------------------------------------------------------------------
-- The Benchmark type
-- | An intermediate type just used for parsing the benchmark stanza.
-- After validation it is converted into the proper 'Benchmark' type.
data BenchmarkStanza = BenchmarkStanza {
benchmarkStanzaBenchmarkType :: Maybe BenchmarkType,
benchmarkStanzaMainIs :: Maybe FilePath,
benchmarkStanzaBenchmarkModule :: Maybe ModuleName,
benchmarkStanzaBuildInfo :: BuildInfo
}
emptyBenchmarkStanza :: BenchmarkStanza
emptyBenchmarkStanza = BenchmarkStanza Nothing Nothing Nothing mempty
benchmarkFieldDescrs :: [FieldDescr BenchmarkStanza]
benchmarkFieldDescrs =
[ simpleField "type"
(maybe empty disp) (fmap Just parse)
benchmarkStanzaBenchmarkType
(\x suite -> suite { benchmarkStanzaBenchmarkType = x })
, simpleField "main-is"
(maybe empty showFilePath) (fmap Just parseFilePathQ)
benchmarkStanzaMainIs
(\x suite -> suite { benchmarkStanzaMainIs = x })
]
++ map biToBenchmark binfoFieldDescrs
where
biToBenchmark = liftField benchmarkStanzaBuildInfo
(\bi suite -> suite { benchmarkStanzaBuildInfo = bi })
storeXFieldsBenchmark :: UnrecFieldParser BenchmarkStanza
storeXFieldsBenchmark (f@('x':'-':_), val)
t@(BenchmarkStanza { benchmarkStanzaBuildInfo = bi }) =
Just $ t {benchmarkStanzaBuildInfo =
bi{ customFieldsBI = (f,val):customFieldsBI bi}}
storeXFieldsBenchmark _ _ = Nothing
validateBenchmark :: LineNo -> BenchmarkStanza -> ParseResult Benchmark
validateBenchmark line stanza =
case benchmarkStanzaBenchmarkType stanza of
Nothing -> return $
emptyBenchmark { benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza }
Just tt@(BenchmarkTypeUnknown _ _) ->
return emptyBenchmark {
benchmarkInterface = BenchmarkUnsupported tt,
benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza
}
Just tt | tt `notElem` knownBenchmarkTypes ->
return emptyBenchmark {
benchmarkInterface = BenchmarkUnsupported tt,
benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza
}
Just tt@(BenchmarkTypeExe ver) ->
case benchmarkStanzaMainIs stanza of
Nothing -> syntaxError line (missingField "main-is" tt)
Just file -> do
when (isJust (benchmarkStanzaBenchmarkModule stanza)) $
warning (extraField "benchmark-module" tt)
return emptyBenchmark {
benchmarkInterface = BenchmarkExeV10 ver file,
benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza
}
where
missingField name tt = "The '" ++ name ++ "' field is required for the "
++ display tt ++ " benchmark type."
extraField name tt = "The '" ++ name ++ "' field is not used for the '"
++ display tt ++ "' benchmark type."
-- ---------------------------------------------------------------------------
-- The BuildInfo type
binfoFieldDescrs :: [FieldDescr BuildInfo]
binfoFieldDescrs =
[ boolField "buildable"
buildable (\val binfo -> binfo{buildable=val})
, commaListField "build-tools"
disp parseBuildTool
buildTools (\xs binfo -> binfo{buildTools=xs})
, commaListFieldWithSep vcat "build-depends"
disp parse
targetBuildDepends (\xs binfo -> binfo{targetBuildDepends=xs})
, spaceListField "cpp-options"
showToken parseTokenQ'
cppOptions (\val binfo -> binfo{cppOptions=val})
, spaceListField "cc-options"
showToken parseTokenQ'
ccOptions (\val binfo -> binfo{ccOptions=val})
, spaceListField "ld-options"
showToken parseTokenQ'
ldOptions (\val binfo -> binfo{ldOptions=val})
, commaListField "pkgconfig-depends"
disp parsePkgconfigDependency
pkgconfigDepends (\xs binfo -> binfo{pkgconfigDepends=xs})
, listField "frameworks"
showToken parseTokenQ
frameworks (\val binfo -> binfo{frameworks=val})
, listField "extra-framework-dirs"
showToken parseFilePathQ
extraFrameworkDirs (\val binfo -> binfo{extraFrameworkDirs=val})
, listFieldWithSep vcat "c-sources"
showFilePath parseFilePathQ
cSources (\paths binfo -> binfo{cSources=paths})
, listFieldWithSep vcat "js-sources"
showFilePath parseFilePathQ
jsSources (\paths binfo -> binfo{jsSources=paths})
, simpleField "default-language"
(maybe empty disp) (option Nothing (fmap Just parseLanguageQ))
defaultLanguage (\lang binfo -> binfo{defaultLanguage=lang})
, listField "other-languages"
disp parseLanguageQ
otherLanguages (\langs binfo -> binfo{otherLanguages=langs})
, listField "default-extensions"
disp parseExtensionQ
defaultExtensions (\exts binfo -> binfo{defaultExtensions=exts})
, listField "other-extensions"
disp parseExtensionQ
otherExtensions (\exts binfo -> binfo{otherExtensions=exts})
, listField "extensions"
disp parseExtensionQ
oldExtensions (\exts binfo -> binfo{oldExtensions=exts})
, listFieldWithSep vcat "extra-libraries"
showToken parseTokenQ
extraLibs (\xs binfo -> binfo{extraLibs=xs})
, listFieldWithSep vcat "extra-ghci-libraries"
showToken parseTokenQ
extraGHCiLibs (\xs binfo -> binfo{extraGHCiLibs=xs})
, listField "extra-lib-dirs"
showFilePath parseFilePathQ
extraLibDirs (\xs binfo -> binfo{extraLibDirs=xs})
, listFieldWithSep vcat "includes"
showFilePath parseFilePathQ
includes (\paths binfo -> binfo{includes=paths})
, listFieldWithSep vcat "install-includes"
showFilePath parseFilePathQ
installIncludes (\paths binfo -> binfo{installIncludes=paths})
, listField "include-dirs"
showFilePath parseFilePathQ
includeDirs (\paths binfo -> binfo{includeDirs=paths})
, listField "hs-source-dirs"
showFilePath parseFilePathQ
hsSourceDirs (\paths binfo -> binfo{hsSourceDirs=paths})
, listFieldWithSep vcat "other-modules"
disp parseModuleNameQ
otherModules (\val binfo -> binfo{otherModules=val})
, optsField "ghc-prof-options" GHC
profOptions (\val binfo -> binfo{profOptions=val})
, optsField "ghcjs-prof-options" GHCJS
profOptions (\val binfo -> binfo{profOptions=val})
, optsField "ghc-shared-options" GHC
sharedOptions (\val binfo -> binfo{sharedOptions=val})
, optsField "ghcjs-shared-options" GHCJS
sharedOptions (\val binfo -> binfo{sharedOptions=val})
, optsField "ghc-options" GHC
options (\path binfo -> binfo{options=path})
, optsField "ghcjs-options" GHCJS
options (\path binfo -> binfo{options=path})
, optsField "jhc-options" JHC
options (\path binfo -> binfo{options=path})
-- NOTE: Hugs and NHC are not supported anymore, but these fields are kept
-- around for backwards compatibility.
, optsField "hugs-options" Hugs
options (const id)
, optsField "nhc98-options" NHC
options (const id)
]
storeXFieldsBI :: UnrecFieldParser BuildInfo
storeXFieldsBI (f@('x':'-':_),val) bi = Just bi{ customFieldsBI = (f,val):customFieldsBI bi }
storeXFieldsBI _ _ = Nothing
------------------------------------------------------------------------------
flagFieldDescrs :: [FieldDescr Flag]
flagFieldDescrs =
[ simpleField "description"
showFreeText parseFreeText
flagDescription (\val fl -> fl{ flagDescription = val })
, boolField "default"
flagDefault (\val fl -> fl{ flagDefault = val })
, boolField "manual"
flagManual (\val fl -> fl{ flagManual = val })
]
------------------------------------------------------------------------------
sourceRepoFieldDescrs :: [FieldDescr SourceRepo]
sourceRepoFieldDescrs =
[ simpleField "type"
(maybe empty disp) (fmap Just parse)
repoType (\val repo -> repo { repoType = val })
, simpleField "location"
(maybe empty showFreeText) (fmap Just parseFreeText)
repoLocation (\val repo -> repo { repoLocation = val })
, simpleField "module"
(maybe empty showToken) (fmap Just parseTokenQ)
repoModule (\val repo -> repo { repoModule = val })
, simpleField "branch"
(maybe empty showToken) (fmap Just parseTokenQ)
repoBranch (\val repo -> repo { repoBranch = val })
, simpleField "tag"
(maybe empty showToken) (fmap Just parseTokenQ)
repoTag (\val repo -> repo { repoTag = val })
, simpleField "subdir"
(maybe empty showFilePath) (fmap Just parseFilePathQ)
repoSubdir (\val repo -> repo { repoSubdir = val })
]
------------------------------------------------------------------------------
setupBInfoFieldDescrs :: [FieldDescr SetupBuildInfo]
setupBInfoFieldDescrs =
[ commaListFieldWithSep vcat "setup-depends"
disp parse
setupDepends (\xs binfo -> binfo{setupDepends=xs})
]
-- ---------------------------------------------------------------
-- Parsing
-- | Given a parser and a filename, return the parse of the file,
-- after checking if the file exists.
readAndParseFile :: (FilePath -> (String -> IO a) -> IO a)
-> (String -> ParseResult a)
-> Verbosity
-> FilePath -> IO a
readAndParseFile withFileContents' parser verbosity fpath = do
exists <- doesFileExist fpath
unless exists
(die $ "Error Parsing: file \"" ++ fpath ++ "\" doesn't exist. Cannot continue.")
withFileContents' fpath $ \str -> case parser str of
ParseFailed e -> do
let (line, message) = locatedErrorMsg e
dieWithLocation fpath line message
ParseOk warnings x -> do
mapM_ (warn verbosity . showPWarning fpath) $ reverse warnings
return x
readHookedBuildInfo :: Verbosity -> FilePath -> IO HookedBuildInfo
readHookedBuildInfo =
readAndParseFile withFileContents parseHookedBuildInfo
-- |Parse the given package file.
readPackageDescription :: Verbosity -> FilePath -> IO GenericPackageDescription
readPackageDescription =
readAndParseFile withUTF8FileContents parsePackageDescription
stanzas :: [Field] -> [[Field]]
stanzas [] = []
stanzas (f:fields) = (f:this) : stanzas rest
where
(this, rest) = break isStanzaHeader fields
isStanzaHeader :: Field -> Bool
isStanzaHeader (F _ f _) = f == "executable"
isStanzaHeader _ = False
------------------------------------------------------------------------------
mapSimpleFields :: (Field -> ParseResult Field) -> [Field]
-> ParseResult [Field]
mapSimpleFields f = mapM walk
where
walk fld@F{} = f fld
walk (IfBlock l c fs1 fs2) = do
fs1' <- mapM walk fs1
fs2' <- mapM walk fs2
return (IfBlock l c fs1' fs2')
walk (Section ln n l fs1) = do
fs1' <- mapM walk fs1
return (Section ln n l fs1')
-- prop_isMapM fs = mapSimpleFields return fs == return fs
-- names of fields that represents dependencies
-- TODO: maybe build-tools should go here too?
constraintFieldNames :: [String]
constraintFieldNames = ["build-depends"]
-- Possible refactoring would be to have modifiers be explicit about what
-- they add and define an accessor that specifies what the dependencies
-- are. This way we would completely reuse the parsing knowledge from the
-- field descriptor.
parseConstraint :: Field -> ParseResult [Dependency]
parseConstraint (F l n v)
| n `elem` constraintFieldNames = runP l n (parseCommaList parse) v
parseConstraint f = userBug $ "Constraint was expected (got: " ++ show f ++ ")"
{-
headerFieldNames :: [String]
headerFieldNames = filter (\n -> not (n `elem` constraintFieldNames))
. map fieldName $ pkgDescrFieldDescrs
-}
libFieldNames :: [String]
libFieldNames = map fieldName libFieldDescrs
++ buildInfoNames ++ constraintFieldNames
-- exeFieldNames :: [String]
-- exeFieldNames = map fieldName executableFieldDescrs
-- ++ buildInfoNames
buildInfoNames :: [String]
buildInfoNames = map fieldName binfoFieldDescrs
++ map fst deprecatedFieldsBuildInfo
-- A minimal implementation of the StateT monad transformer to avoid depending
-- on the 'mtl' package.
newtype StT s m a = StT { runStT :: s -> m (a,s) }
instance Functor f => Functor (StT s f) where
fmap g (StT f) = StT $ fmap (first g) . f
#if __GLASGOW_HASKELL__ >= 710
instance (Monad m) => Applicative (StT s m) where
#else
instance (Monad m, Functor m) => Applicative (StT s m) where
#endif
pure a = StT (\s -> return (a,s))
(<*>) = ap
instance Monad m => Monad (StT s m) where
#if __GLASGOW_HASKELL__ < 710
return a = StT (\s -> return (a,s))
#endif
StT f >>= g = StT $ \s -> do
(a,s') <- f s
runStT (g a) s'
get :: Monad m => StT s m s
get = StT $ \s -> return (s, s)
modify :: Monad m => (s -> s) -> StT s m ()
modify f = StT $ \s -> return ((),f s)
lift :: Monad m => m a -> StT s m a
lift m = StT $ \s -> m >>= \a -> return (a,s)
evalStT :: Monad m => StT s m a -> s -> m a
evalStT st s = liftM fst $ runStT st s
-- Our monad for parsing a list/tree of fields.
--
-- The state represents the remaining fields to be processed.
type PM a = StT [Field] ParseResult a
-- return look-ahead field or nothing if we're at the end of the file
peekField :: PM (Maybe Field)
peekField = liftM listToMaybe get
-- Unconditionally discard the first field in our state. Will error when it
-- reaches end of file. (Yes, that's evil.)
skipField :: PM ()
skipField = modify tail
--FIXME: this should take a ByteString, not a String. We have to be able to
-- decode UTF8 and handle the BOM.
-- | Parses the given file into a 'GenericPackageDescription'.
--
-- In Cabal 1.2 the syntax for package descriptions was changed to a format
-- with sections and possibly indented property descriptions.
parsePackageDescription :: String -> ParseResult GenericPackageDescription
parsePackageDescription file = do
-- This function is quite complex because it needs to be able to parse
-- both pre-Cabal-1.2 and post-Cabal-1.2 files. Additionally, it contains
-- a lot of parser-related noise since we do not want to depend on Parsec.
--
-- If we detect an pre-1.2 file we implicitly convert it to post-1.2
-- style. See 'sectionizeFields' below for details about the conversion.
fields0 <- readFields file `catchParseError` \err ->
let tabs = findIndentTabs file in
case err of
-- In case of a TabsError report them all at once.
TabsError tabLineNo -> reportTabsError
-- but only report the ones including and following
-- the one that caused the actual error
[ t | t@(lineNo',_) <- tabs
, lineNo' >= tabLineNo ]
_ -> parseFail err
let cabalVersionNeeded =
head $ [ minVersionBound versionRange
| Just versionRange <- [ simpleParse v
| F _ "cabal-version" v <- fields0 ] ]
++ [Version [0] []]
minVersionBound versionRange =
case asVersionIntervals versionRange of
[] -> Version [0] []
((LowerBound version _, _):_) -> version
handleFutureVersionParseFailure cabalVersionNeeded $ do
let sf = sectionizeFields fields0 -- ensure 1.2 format
-- figure out and warn about deprecated stuff (warnings are collected
-- inside our parsing monad)
fields <- mapSimpleFields deprecField sf
-- Our parsing monad takes the not-yet-parsed fields as its state.
-- After each successful parse we remove the field from the state
-- ('skipField') and move on to the next one.
--
-- Things are complicated a bit, because fields take a tree-like
-- structure -- they can be sections or "if"/"else" conditionals.
flip evalStT fields $ do
-- The header consists of all simple fields up to the first section
-- (flag, library, executable).
header_fields <- getHeader []
-- Parses just the header fields and stores them in a
-- 'PackageDescription'. Note that our final result is a
-- 'GenericPackageDescription'; for pragmatic reasons we just store
-- the partially filled-out 'PackageDescription' inside the
-- 'GenericPackageDescription'.
pkg <- lift $ parseFields pkgDescrFieldDescrs
storeXFieldsPD
emptyPackageDescription
header_fields
-- 'getBody' assumes that the remaining fields only consist of
-- flags, lib and exe sections.
(repos, flags, mcsetup, libs, exes, tests, bms) <- getBody pkg
warnIfRest -- warn if getBody did not parse up to the last field.
-- warn about using old/new syntax with wrong cabal-version:
maybeWarnCabalVersion (not $ oldSyntax fields0) pkg
checkForUndefinedFlags flags libs exes tests
return $ GenericPackageDescription
pkg { sourceRepos = repos, setupBuildInfo = mcsetup }
flags libs exes tests bms
where
oldSyntax = all isSimpleField
reportTabsError tabs =
syntaxError (fst (head tabs)) $
"Do not use tabs for indentation (use spaces instead)\n"
++ " Tabs were used at (line,column): " ++ show tabs
maybeWarnCabalVersion newsyntax pkg
| newsyntax && specVersion pkg < Version [1,2] []
= lift $ warning $
"A package using section syntax must specify at least\n"
++ "'cabal-version: >= 1.2'."
maybeWarnCabalVersion newsyntax pkg
| not newsyntax && specVersion pkg >= Version [1,2] []
= lift $ warning $
"A package using 'cabal-version: "
++ displaySpecVersion (specVersionRaw pkg)
++ "' must use section syntax. See the Cabal user guide for details."
where
displaySpecVersion (Left version) = display version
displaySpecVersion (Right versionRange) =
case asVersionIntervals versionRange of
[] {- impossible -} -> display versionRange
((LowerBound version _, _):_) -> display (orLaterVersion version)
maybeWarnCabalVersion _ _ = return ()
handleFutureVersionParseFailure cabalVersionNeeded parseBody =
(unless versionOk (warning message) >> parseBody)
`catchParseError` \parseError -> case parseError of
TabsError _ -> parseFail parseError
_ | versionOk -> parseFail parseError
| otherwise -> fail message
where versionOk = cabalVersionNeeded <= cabalVersion
message = "This package requires at least Cabal version "
++ display cabalVersionNeeded
-- "Sectionize" an old-style Cabal file. A sectionized file has:
--
-- * all global fields at the beginning, followed by
--
-- * all flag declarations, followed by
--
-- * an optional library section, and an arbitrary number of executable
-- sections (in any order).
--
-- The current implementation just gathers all library-specific fields
-- in a library section and wraps all executable stanzas in an executable
-- section.
sectionizeFields :: [Field] -> [Field]
sectionizeFields fs
| oldSyntax fs =
let
-- "build-depends" is a local field now. To be backwards
-- compatible, we still allow it as a global field in old-style
-- package description files and translate it to a local field by
-- adding it to every non-empty section
(hdr0, exes0) = break ((=="executable") . fName) fs
(hdr, libfs0) = partition (not . (`elem` libFieldNames) . fName) hdr0
(deps, libfs) = partition ((== "build-depends") . fName)
libfs0
exes = unfoldr toExe exes0
toExe [] = Nothing
toExe (F l e n : r)
| e == "executable" =
let (efs, r') = break ((=="executable") . fName) r
in Just (Section l "executable" n (deps ++ efs), r')
toExe _ = cabalBug "unexpected input to 'toExe'"
in
hdr ++
(if null libfs then []
else [Section (lineNo (head libfs)) "library" "" (deps ++ libfs)])
++ exes
| otherwise = fs
isSimpleField F{} = True
isSimpleField _ = False
-- warn if there's something at the end of the file
warnIfRest :: PM ()
warnIfRest = do
s <- get
case s of
[] -> return ()
_ -> lift $ warning "Ignoring trailing declarations." -- add line no.
-- all simple fields at the beginning of the file are (considered) header
-- fields
getHeader :: [Field] -> PM [Field]
getHeader acc = peekField >>= \mf -> case mf of
Just f@F{} -> skipField >> getHeader (f:acc)
_ -> return (reverse acc)
--
-- body ::= { repo | flag | library | executable | test }+
--
-- The body consists of an optional sequence of declarations of flags and
-- an arbitrary number of libraries/executables/tests.
getBody :: PackageDescription
-> PM ([SourceRepo], [Flag]
,Maybe SetupBuildInfo
,[(String, CondTree ConfVar [Dependency] Library)]
,[(String, CondTree ConfVar [Dependency] Executable)]
,[(String, CondTree ConfVar [Dependency] TestSuite)]
,[(String, CondTree ConfVar [Dependency] Benchmark)])
getBody pkg = peekField >>= \mf -> case mf of
Just (Section line_no sec_type sec_label sec_fields)
| sec_type == "executable" -> do
when (null sec_label) $ lift $ syntaxError line_no
"'executable' needs one argument (the executable's name)"
exename <- lift $ runP line_no "executable" parseTokenQ sec_label
flds <- collectFields parseExeFields sec_fields
skipField
(repos, flags, csetup, lib, exes, tests, bms) <- getBody pkg
return (repos, flags, csetup, lib, (exename, flds): exes, tests, bms)
| sec_type == "test-suite" -> do
when (null sec_label) $ lift $ syntaxError line_no
"'test-suite' needs one argument (the test suite's name)"
testname <- lift $ runP line_no "test" parseTokenQ sec_label
flds <- collectFields (parseTestFields line_no) sec_fields
-- Check that a valid test suite type has been chosen. A type
-- field may be given inside a conditional block, so we must
-- check for that before complaining that a type field has not
-- been given. The test suite must always have a valid type, so
-- we need to check both the 'then' and 'else' blocks, though
-- the blocks need not have the same type.
let checkTestType ts ct =
let ts' = mappend ts $ condTreeData ct
-- If a conditional has only a 'then' block and no
-- 'else' block, then it cannot have a valid type
-- in every branch, unless the type is specified at
-- a higher level in the tree.
checkComponent (_, _, Nothing) = False
-- If a conditional has a 'then' block and an 'else'
-- block, both must specify a test type, unless the
-- type is specified higher in the tree.
checkComponent (_, t, Just e) =
checkTestType ts' t && checkTestType ts' e
-- Does the current node specify a test type?
hasTestType = testInterface ts'
/= testInterface emptyTestSuite
-- If the current level of the tree specifies a type,
-- then we are done. If not, then one of the conditional
-- branches below the current node must specify a type.
-- Each node may have multiple immediate children; we
-- only one need one to specify a type because the
-- configure step uses 'mappend' to join together the
-- results of flag resolution.
in hasTestType || any checkComponent (condTreeComponents ct)
if checkTestType emptyTestSuite flds
then do
skipField
(repos, flags, csetup, lib, exes, tests, bms) <- getBody pkg
return (repos, flags, csetup, lib, exes,
(testname, flds) : tests, bms)
else lift $ syntaxError line_no $
"Test suite \"" ++ testname
++ "\" is missing required field \"type\" or the field "
++ "is not present in all conditional branches. The "
++ "available test types are: "
++ intercalate ", " (map display knownTestTypes)
| sec_type == "benchmark" -> do
when (null sec_label) $ lift $ syntaxError line_no
"'benchmark' needs one argument (the benchmark's name)"
benchname <- lift $ runP line_no "benchmark" parseTokenQ sec_label
flds <- collectFields (parseBenchmarkFields line_no) sec_fields
-- Check that a valid benchmark type has been chosen. A type
-- field may be given inside a conditional block, so we must
-- check for that before complaining that a type field has not
-- been given. The benchmark must always have a valid type, so
-- we need to check both the 'then' and 'else' blocks, though
-- the blocks need not have the same type.
let checkBenchmarkType ts ct =
let ts' = mappend ts $ condTreeData ct
-- If a conditional has only a 'then' block and no
-- 'else' block, then it cannot have a valid type
-- in every branch, unless the type is specified at
-- a higher level in the tree.
checkComponent (_, _, Nothing) = False
-- If a conditional has a 'then' block and an 'else'
-- block, both must specify a benchmark type, unless the
-- type is specified higher in the tree.
checkComponent (_, t, Just e) =
checkBenchmarkType ts' t && checkBenchmarkType ts' e
-- Does the current node specify a benchmark type?
hasBenchmarkType = benchmarkInterface ts'
/= benchmarkInterface emptyBenchmark
-- If the current level of the tree specifies a type,
-- then we are done. If not, then one of the conditional
-- branches below the current node must specify a type.
-- Each node may have multiple immediate children; we
-- only one need one to specify a type because the
-- configure step uses 'mappend' to join together the
-- results of flag resolution.
in hasBenchmarkType || any checkComponent (condTreeComponents ct)
if checkBenchmarkType emptyBenchmark flds
then do
skipField
(repos, flags, csetup, lib, exes, tests, bms) <- getBody pkg
return (repos, flags, csetup, lib, exes,
tests, (benchname, flds) : bms)
else lift $ syntaxError line_no $
"Benchmark \"" ++ benchname
++ "\" is missing required field \"type\" or the field "
++ "is not present in all conditional branches. The "
++ "available benchmark types are: "
++ intercalate ", " (map display knownBenchmarkTypes)
| sec_type == "library" -> do
libname <- if null sec_label
then return (unPackageName (packageName pkg))
-- TODO: relax this parsing so that scoping is handled
-- correctly
else lift $ runP line_no "library" parseTokenQ sec_label
flds <- collectFields parseLibFields sec_fields
skipField
(repos, flags, csetup, libs, exes, tests, bms) <- getBody pkg
return (repos, flags, csetup, (libname, flds) : libs, exes, tests, bms)
| sec_type == "flag" -> do
when (null sec_label) $ lift $
syntaxError line_no "'flag' needs one argument (the flag's name)"
flag <- lift $ parseFields
flagFieldDescrs
warnUnrec
(MkFlag (FlagName (lowercase sec_label)) "" True False)
sec_fields
skipField
(repos, flags, csetup, lib, exes, tests, bms) <- getBody pkg
return (repos, flag:flags, csetup, lib, exes, tests, bms)
| sec_type == "source-repository" -> do
when (null sec_label) $ lift $ syntaxError line_no $
"'source-repository' needs one argument, "
++ "the repo kind which is usually 'head' or 'this'"
kind <- case simpleParse sec_label of
Just kind -> return kind
Nothing -> lift $ syntaxError line_no $
"could not parse repo kind: " ++ sec_label
repo <- lift $ parseFields
sourceRepoFieldDescrs
warnUnrec
SourceRepo {
repoKind = kind,
repoType = Nothing,
repoLocation = Nothing,
repoModule = Nothing,
repoBranch = Nothing,
repoTag = Nothing,
repoSubdir = Nothing
}
sec_fields
skipField
(repos, flags, csetup, lib, exes, tests, bms) <- getBody pkg
return (repo:repos, flags, csetup, lib, exes, tests, bms)
| sec_type == "custom-setup" -> do
unless (null sec_label) $ lift $
syntaxError line_no "'setup' expects no argument"
flds <- lift $ parseFields
setupBInfoFieldDescrs
warnUnrec
mempty
sec_fields
skipField
(repos, flags, csetup0, lib, exes, tests, bms) <- getBody pkg
when (isJust csetup0) $ lift $ syntaxError line_no
"There can only be one 'custom-setup' section in a package description."
return (repos, flags, Just flds, lib, exes, tests, bms)
| otherwise -> do
lift $ warning $ "Ignoring unknown section type: " ++ sec_type
skipField
getBody pkg
Just f@(F {}) -> do
_ <- lift $ syntaxError (lineNo f) $
"Plain fields are not allowed in between stanzas: " ++ show f
skipField
getBody pkg
Just f@(IfBlock {}) -> do
_ <- lift $ syntaxError (lineNo f) $
"If-blocks are not allowed in between stanzas: " ++ show f
skipField
getBody pkg
Nothing -> return ([], [], Nothing, [], [], [], [])
-- Extracts all fields in a block and returns a 'CondTree'.
--
-- We have to recurse down into conditionals and we treat fields that
-- describe dependencies specially.
collectFields :: ([Field] -> PM a) -> [Field]
-> PM (CondTree ConfVar [Dependency] a)
collectFields parser allflds = do
let simplFlds = [ F l n v | F l n v <- allflds ]
condFlds = [ f | f@IfBlock{} <- allflds ]
sections = [ s | s@Section{} <- allflds ]
mapM_
(\(Section l n _ _) -> lift . warning $
"Unexpected section '" ++ n ++ "' on line " ++ show l)
sections
a <- parser simplFlds
-- Dependencies must be treated specially: when we
-- parse into a CondTree, not only do we parse them into
-- the targetBuildDepends/etc field inside the
-- PackageDescription, but we also have to put the
-- combined dependencies into CondTree.
--
-- This information is, in principle, redundant, but
-- putting it here makes it easier for the constraint
-- solver to pick a flag assignment which supports
-- all of the dependencies (because it only has
-- to check the CondTree, rather than grovel everywhere
-- inside the conditional bits).
deps <- liftM concat
. mapM (lift . parseConstraint)
. filter isConstraint
$ simplFlds
ifs <- mapM processIfs condFlds
return (CondNode a deps ifs)
where
isConstraint (F _ n _) = n `elem` constraintFieldNames
isConstraint _ = False
processIfs (IfBlock l c t e) = do
cnd <- lift $ runP l "if" parseCondition c
t' <- collectFields parser t
e' <- case e of
[] -> return Nothing
es -> do fs <- collectFields parser es
return (Just fs)
return (cnd, t', e')
processIfs _ = cabalBug "processIfs called with wrong field type"
parseLibFields :: [Field] -> PM Library
parseLibFields = lift . parseFields libFieldDescrs storeXFieldsLib emptyLibrary
-- Note: we don't parse the "executable" field here, hence the tail hack.
parseExeFields :: [Field] -> PM Executable
parseExeFields = lift . parseFields (tail executableFieldDescrs)
storeXFieldsExe emptyExecutable
parseTestFields :: LineNo -> [Field] -> PM TestSuite
parseTestFields line fields = do
x <- lift $ parseFields testSuiteFieldDescrs storeXFieldsTest
emptyTestStanza fields
lift $ validateTestSuite line x
parseBenchmarkFields :: LineNo -> [Field] -> PM Benchmark
parseBenchmarkFields line fields = do
x <- lift $ parseFields benchmarkFieldDescrs storeXFieldsBenchmark
emptyBenchmarkStanza fields
lift $ validateBenchmark line x
checkForUndefinedFlags ::
[Flag] ->
[(String, CondTree ConfVar [Dependency] Library)] ->
[(String, CondTree ConfVar [Dependency] Executable)] ->
[(String, CondTree ConfVar [Dependency] TestSuite)] ->
PM ()
checkForUndefinedFlags flags libs exes tests = do
let definedFlags = map flagName flags
mapM_ (checkCondTreeFlags definedFlags . snd) libs
mapM_ (checkCondTreeFlags definedFlags . snd) exes
mapM_ (checkCondTreeFlags definedFlags . snd) tests
checkCondTreeFlags :: [FlagName] -> CondTree ConfVar c a -> PM ()
checkCondTreeFlags definedFlags ct = do
let fv = nub $ freeVars ct
unless (all (`elem` definedFlags) fv) $
fail $ "These flags are used without having been defined: "
++ intercalate ", " [ n | FlagName n <- fv \\ definedFlags ]
-- | Parse a list of fields, given a list of field descriptions,
-- a structure to accumulate the parsed fields, and a function
-- that can decide what to do with fields which don't match any
-- of the field descriptions.
parseFields :: [FieldDescr a] -- ^ descriptions of fields we know how to
-- parse
-> UnrecFieldParser a -- ^ possibly do something with
-- unrecognized fields
-> a -- ^ accumulator
-> [Field] -- ^ fields to be parsed
-> ParseResult a
parseFields descrs unrec ini fields =
do (a, unknowns) <- foldM (parseField descrs unrec) (ini, []) fields
unless (null unknowns) $ warning $ render $
text "Unknown fields:" <+>
commaSep (map (\(l,u) -> u ++ " (line " ++ show l ++ ")")
(reverse unknowns))
$+$
text "Fields allowed in this section:" $$
nest 4 (commaSep $ map fieldName descrs)
return a
where
commaSep = fsep . punctuate comma . map text
parseField :: [FieldDescr a] -- ^ list of parseable fields
-> UnrecFieldParser a -- ^ possibly do something with
-- unrecognized fields
-> (a,[(Int,String)]) -- ^ accumulated result and warnings
-> Field -- ^ the field to be parsed
-> ParseResult (a, [(Int,String)])
parseField (FieldDescr name _ parser : fields) unrec (a, us) (F line f val)
| name == f = parser line val a >>= \a' -> return (a',us)
| otherwise = parseField fields unrec (a,us) (F line f val)
parseField [] unrec (a,us) (F l f val) = return $
case unrec (f,val) a of -- no fields matched, see if the 'unrec'
Just a' -> (a',us) -- function wants to do anything with it
Nothing -> (a, (l,f):us)
parseField _ _ _ _ = cabalBug "'parseField' called on a non-field"
deprecatedFields :: [(String,String)]
deprecatedFields =
deprecatedFieldsPkgDescr ++ deprecatedFieldsBuildInfo
deprecatedFieldsPkgDescr :: [(String,String)]
deprecatedFieldsPkgDescr = [ ("other-files", "extra-source-files") ]
deprecatedFieldsBuildInfo :: [(String,String)]
deprecatedFieldsBuildInfo = [ ("hs-source-dir","hs-source-dirs") ]
-- Handle deprecated fields
deprecField :: Field -> ParseResult Field
deprecField (F line fld val) = do
fld' <- case lookup fld deprecatedFields of
Nothing -> return fld
Just newName -> do
warning $ "The field \"" ++ fld
++ "\" is deprecated, please use \"" ++ newName ++ "\""
return newName
return (F line fld' val)
deprecField _ = cabalBug "'deprecField' called on a non-field"
parseHookedBuildInfo :: String -> ParseResult HookedBuildInfo
parseHookedBuildInfo inp = do
fields <- readFields inp
let (mLibFields:rest) = stanzas fields
mLib <- parseLib mLibFields
foldM parseStanza mLib rest
where
-- For backwards compatibility, if you have a bare stanza,
-- we assume it's part of the public library. We don't
-- know what the name is, so the people using the HookedBuildInfo
-- have to handle this carefully.
parseLib :: [Field] -> ParseResult [(ComponentName, BuildInfo)]
parseLib (bi@(F _ inFieldName _:_))
| lowercase inFieldName /= "executable" &&
lowercase inFieldName /= "library" &&
lowercase inFieldName /= "benchmark" &&
lowercase inFieldName /= "test-suite"
= liftM (\bis -> [(CLibName "", bis)]) (parseBI bi)
parseLib _ = return []
parseStanza :: HookedBuildInfo -> [Field] -> ParseResult HookedBuildInfo
parseStanza bis (F line inFieldName mName:bi)
| Just k <- case lowercase inFieldName of
"executable" -> Just CExeName
"library" -> Just CLibName
"benchmark" -> Just CBenchName
"test-suite" -> Just CTestName
_ -> Nothing
= do bi' <- parseBI bi
return ((k mName, bi'):bis)
| otherwise
= syntaxError line $
"expecting 'executable', 'library', 'benchmark' or 'test-suite' " ++
"at top of stanza, but got '" ++ inFieldName ++ "'"
parseStanza _ (_:_) = cabalBug "`parseStanza' called on a non-field"
parseStanza _ [] = syntaxError 0 "error in parsing buildinfo file. Expected stanza"
parseBI st = parseFields binfoFieldDescrs storeXFieldsBI emptyBuildInfo st
-- ---------------------------------------------------------------------------
-- Pretty printing
writePackageDescription :: FilePath -> PackageDescription -> IO ()
writePackageDescription fpath pkg = writeUTF8File fpath (showPackageDescription pkg)
--TODO: make this use section syntax
-- add equivalent for GenericPackageDescription
showPackageDescription :: PackageDescription -> String
showPackageDescription pkg = render $
ppPackage pkg
$$ ppCustomFields (customFieldsPD pkg)
$$ vcat [ space $$ ppLibrary lib | lib <- libraries pkg ]
$$ vcat [ space $$ ppExecutable exe | exe <- executables pkg ]
where
ppPackage = ppFields pkgDescrFieldDescrs
ppLibrary = ppFields libFieldDescrs
ppExecutable = ppFields executableFieldDescrs
ppCustomFields :: [(String,String)] -> Doc
ppCustomFields flds = vcat (map ppCustomField flds)
ppCustomField :: (String,String) -> Doc
ppCustomField (name,val) = text name <> colon <+> showFreeText val
writeHookedBuildInfo :: FilePath -> HookedBuildInfo -> IO ()
writeHookedBuildInfo fpath = writeFileAtomic fpath . BS.Char8.pack
. showHookedBuildInfo
showHookedBuildInfo :: HookedBuildInfo -> String
showHookedBuildInfo bis = render $
vcat [ space
$$ ppName name
$$ ppBuildInfo bi
| (name, bi) <- bis ]
where
ppName (CLibName name) = text "library:" <+> text name
ppName (CExeName name) = text "executable:" <+> text name
ppName (CTestName name) = text "test-suite:" <+> text name
ppName (CBenchName name) = text "benchmark:" <+> text name
ppBuildInfo bi = ppFields binfoFieldDescrs bi
$$ ppCustomFields (customFieldsBI bi)
-- replace all tabs used as indentation with whitespace, also return where
-- tabs were found
findIndentTabs :: String -> [(Int,Int)]
findIndentTabs = concatMap checkLine
. zip [1..]
. lines
where
checkLine (lineno, l) =
let (indent, _content) = span isSpace l
tabCols = map fst . filter ((== '\t') . snd) . zip [0..]
addLineNo = map (\col -> (lineno,col))
in addLineNo (tabCols indent)
--test_findIndentTabs = findIndentTabs $ unlines $
-- [ "foo", " bar", " \t baz", "\t biz\t", "\t\t \t mib" ]
| kolmodin/cabal | Cabal/Distribution/PackageDescription/Parse.hs | bsd-3-clause | 55,753 | 333 | 19 | 17,366 | 11,589 | 6,276 | 5,313 | 883 | 26 |
module Yawn.Configuration (
Configuration,
port,
host,
defaultIndexFile,
requestTimeOut,
keepAliveTimeOut,
socketBufSize,
maxClients,
showIndex,
defaultMimeType,
serverName,
serverVersion,
mimeFile,
logRoot,
publicRoot,
loadConfig
) where
import System.IO (hPutStrLn, stderr)
import Yawn.Util.DictionaryParser (Dictionary, parseDictionary)
import Yawn.Util.List (find)
import qualified System.IO.Error as IOError (try)
data Configuration = Configuration {
port :: Integer,
host :: String,
root :: FilePath,
defaultIndexFile :: String,
requestTimeOut :: Int,
keepAliveTimeOut :: Int,
socketBufSize :: Int,
maxClients :: Int,
showIndex :: Bool,
defaultMimeType :: String,
serverName :: String,
serverVersion :: String
} deriving (Show, Eq)
mimeFile :: Configuration -> FilePath
mimeFile conf = root conf ++ "/conf/mime.types"
logRoot :: Configuration -> FilePath
logRoot conf = root conf ++ "/log/"
publicRoot :: Configuration -> FilePath
publicRoot conf = root conf ++ "/public/"
loadConfig :: FilePath -> IO (Maybe Configuration)
loadConfig appRoot = IOError.try (readFile (appRoot ++ "/conf/yawn.conf")) >>= \d -> case d of
Left e -> printError e >> return Nothing
Right content -> parseConfig content appRoot
parseConfig :: String -> String -> IO (Maybe Configuration)
parseConfig content appRoot = parseConfiguration appRoot content >>= \c -> case c of
Nothing -> return Nothing
Just config -> return $ Just config
parseConfiguration :: FilePath -> String -> IO (Maybe Configuration)
parseConfiguration appRoot s = case parseDictionary "yawn.conf" s of
Left e -> printError e >> return Nothing
Right pairs -> return $ Just $ makeConfig appRoot pairs
makeConfig :: FilePath -> Dictionary -> Configuration
makeConfig appRoot xs = Configuration (read $ find "port" "9000" xs)
(find "host" "127.0.0.1" xs)
appRoot
(find "defaultIndexFile" "index.html" xs)
(read $ find "requestTimeout" "300" xs)
(read $ find "keepAliveTimeout" "15" xs)
(read $ find "socketBufSize" "2048" xs)
(read $ find "maxClients" "100" xs)
(read $ find "showIndex" "True" xs)
(find "defaultMimeType" "text/html" xs)
(find "serverName" "YAWN" xs)
(find "serverVersion" "0.1" xs)
printError :: Show a => a -> IO ()
printError e = hPutStrLn stderr $ "Unable to load configuration file " ++ show e
| ameingast/yawn | src/Yawn/Configuration.hs | bsd-3-clause | 2,844 | 0 | 11 | 894 | 744 | 394 | 350 | 68 | 2 |
--
-- Adapted from K-Means sample from "Parallel and Concurrent Programming in
-- Haskell", (c) Simon Marlow, 2013.
--
module TestCore where
import Data.List
import Data.Word
-- -----------------------------------------------------------------------------
-- Points
type Point = (Double, Double)
zeroPoint :: Point
zeroPoint = (0,0)
-----------------------------------------------------------------------------
-- Clusters
type Cluster = (Word32, Point)
makeCluster :: Int -> [Point] -> Cluster
makeCluster clid points
= ( fromIntegral clid
, (a / fromIntegral count, b / fromIntegral count))
where
(a,b) = foldl' addPoint zeroPoint points
count = length points
addPoint :: Point -> Point -> Point
addPoint (x,y) (u,v) = (x+u,y+v)
| tmcdonell/accelerate-kmeans | test/TestCore.hs | bsd-3-clause | 767 | 0 | 8 | 131 | 195 | 115 | 80 | 15 | 1 |
module Tests where
| maoe/text-keepalived | tests/Tests.hs | bsd-3-clause | 22 | 0 | 2 | 6 | 4 | 3 | 1 | 1 | 0 |
module FruitShopKata.Day4 (process) where
type Bill = (Money, [Product])
type Money = Int
type Product = String
process :: [Product] -> [Money]
-- process = map fst . tail . scanl addProduct (0, [])
process products = map fst (tail (scanl addProduct (0, []) products))
where
addProduct :: Bill -> Product -> Bill
addProduct (total, products) product = (total + findPrice product - discounts product, product:products)
where
findPrice :: Product -> Money
findPrice product
| product == "Pommes" = 100
| product == "Cerises" = 75
| product == "Bananes" = 150
discounts :: Product -> Money
discounts product =
case lookup product specials of
Just (discount, m) -> ((applyDiscount discount) . (== 0) . (`mod` m) . length . filter ((==) product)) (product:products)
Nothing -> 0
applyDiscount :: Money -> Bool -> Money
applyDiscount discount True = discount
applyDiscount _ _ = 0
specials = [("Cerises", (20, 2)), ("Bananes", (150, 2))]
| Alex-Diez/haskell-tdd-kata | old-katas/src/FruitShopKata/Day4.hs | bsd-3-clause | 1,349 | 0 | 19 | 569 | 372 | 205 | 167 | 22 | 3 |
main = let
x =
y = 3
in 4 | roberth/uu-helium | test/parser/PositionInsertedBrace2.hs | gpl-3.0 | 37 | 1 | 9 | 21 | 23 | 10 | 13 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Text.XmlHtml.XML.Parse where
import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Text.XmlHtml.Common
import Text.XmlHtml.TextParser
import qualified Text.Parsec as P
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text as T
------------------------------------------------------------------------------
-- | This is my best guess as to the best rule for handling document fragments
-- for processing. It is essentially modeled after document, but allowing
-- multiple nodes.
docFragment :: Encoding -> Parser Document
docFragment e = do
(dt, nodes1) <- prolog
nodes2 <- content
return $ XmlDocument e dt (nodes1 ++ nodes2)
------------------------------------------------------------------------------
-- Everything from here forward is translated from the XML specification. --
------------------------------------------------------------------------------
{-
Map from numbered productions in the XML specification to symbols here:
PROD SPEC NAME PARSER NAME NOTES
-----|------------------|---------------------|-------
[1] document document
[2] Char {2}
[3] S whiteSpace
[4] NameStartChar isNameStartChar {1}
[4a] NameChar isNameChar {1}
[5] Name name
[6] Names names
[7] Nmtoken nmtoken
[8] Nmtokens nmtokens
[9] EntityValue {4}
[10] AttValue attrValue
[11] SystemLiteral systemLiteral
[12] PubidLiteral pubIdLiteral
[13] PubidChar isPubIdChar {1}
[14] CharData charData
[15] Comment comment
[16] PI processingInstruction
[17] PITarget piTarget
[18] CDSect cdSect
[19] CDStart cdSect {3}
[20] CData cdSect {3}
[21] CDEnd cdSect {3}
[22] prolog prolog
[23] XMLDecl xmlDecl
[24] VersionInfo versionInfo
[25] Eq eq
[26] VersionNum versionInfo {3}
[27] Misc misc
[28] doctypedecl docTypeDecl
[28a] DeclSep {4}
[28b] intSubset {4}
[29] markupdecl {4}
[30] extSubset {4}
[31] extSubsetDecl {4}
[32] SDDecl sdDecl
[39] element element
[40] STag emptyOrStartTag
[41] Attribute attribute
[42] ETag endTag
[43] content content
[44] EmptyElemTag emptyOrStartTag
[45] elementDecl {4}
[46] contentSpec {4}
[47] children {4}
[48] cp {4}
[49] choice {4}
[50] seq {4}
[51] Mixed {4}
[52] AttlistDecl {4}
[53] AttDef {4}
[54] AttType {4}
[55] StringType {4}
[56] TokenizedType {4}
[57] EnumeratedType {4}
[58] NotationType {4}
[59] Enumeration {4}
[60] DefaultDecl {4}
[61] conditionalSect {4}
[62] includeSect {4}
[63] ignoreSect {4}
[64] ignoreSectContents {4}
[65] Ignore {4}
[66] CharRef charRef
[67] Reference reference
[68] EntityRef entityRef
[69] PEReference {4}
[70] EntityDecl {4}
[71] GEDecl {4}
[72] PEDecl {4}
[73] EntityDef {4}
[74] PEDef {4}
[75] ExternalID externalID
[76] NDataDecl {4}
[77] TextDecl textDecl
[78] extParsedEnt extParsedEnt
[80] EncodingDecl encodingDecl
[81] EncName encodingDecl {3}
[82] NotationDecl {4}
[83] PublicID {4}
[84] Letter {5}
[85] BaseChar {5}
[86] Ideographic {5}
[87] CombiningChar {5}
[88] Digit {5}
[89] Extender {5}
Notes:
{1} - These productions match single characters, and so are
implemented as predicates instead of parsers.
{3} - Denotes a production which is not exposed as a top-level symbol
because it is trivial and included in another definition.
{4} - This module does not contain a parser for the DTD subsets, so
grammar that occurs only in DTD subsets is not defined.
{5} - These are orphaned productions for character classes.
-}
------------------------------------------------------------------------------
whiteSpace :: Parser ()
whiteSpace = some (P.satisfy (`elem` [' ','\t','\r','\n'])) *> return ()
------------------------------------------------------------------------------
isNameStartChar :: Char -> Bool
isNameStartChar c | c == ':' = True
| c == '_' = True
| c >= 'a' && c <= 'z' = True
| c >= 'A' && c <= 'Z' = True
| c >= '\xc0' && c <= '\xd6' = True
| c >= '\xd8' && c <= '\xf6' = True
| c >= '\xf8' && c <= '\x2ff' = True
| c >= '\x370' && c <= '\x37d' = True
| c >= '\x37f' && c <= '\x1fff' = True
| c >= '\x200c' && c <= '\x200d' = True
| c >= '\x2070' && c <= '\x218f' = True
| c >= '\x2c00' && c <= '\x2fef' = True
| c >= '\x3001' && c <= '\xd7ff' = True
| c >= '\xf900' && c <= '\xfdcf' = True
| c >= '\xfdf0' && c <= '\xfffd' = True
| c >= '\x10000' && c <= '\xeffff' = True
| otherwise = False
------------------------------------------------------------------------------
isNameChar :: Char -> Bool
isNameChar c | isNameStartChar c = True
| c == '-' = True
| c == '.' = True
| c == '\xb7' = True
| c >= '0' && c <= '9' = True
| c >= '\x300' && c <= '\x36f' = True
| c >= '\x203f' && c <= '\x2040' = True
| otherwise = False
------------------------------------------------------------------------------
name :: Parser Text
name = do
c <- P.satisfy isNameStartChar
r <- takeWhile0 isNameChar
return $ T.cons c r
------------------------------------------------------------------------------
attrValue :: Parser Text
attrValue = fmap T.concat (singleQuoted <|> doubleQuoted)
where
singleQuoted = P.char '\'' *> refTill ['<','&','\''] <* P.char '\''
doubleQuoted = P.char '"' *> refTill ['<','&','"'] <* P.char '"'
refTill end = many (takeWhile1 (not . (`elem` end)) <|> reference)
------------------------------------------------------------------------------
systemLiteral :: Parser Text
systemLiteral = singleQuoted <|> doubleQuoted
where
singleQuoted = do
_ <- P.char '\''
x <- takeWhile0 (not . (== '\''))
_ <- P.char '\''
return x
doubleQuoted = do
_ <- P.char '\"'
x <- takeWhile0 (not . (== '\"'))
_ <- P.char '\"'
return x
------------------------------------------------------------------------------
pubIdLiteral :: Parser Text
pubIdLiteral = singleQuoted <|> doubleQuoted
where
singleQuoted = do
_ <- P.char '\''
x <- takeWhile0 (\c -> isPubIdChar c && c /= '\'')
_ <- P.char '\''
return x
doubleQuoted = do
_ <- P.char '\"'
x <- takeWhile0 isPubIdChar
_ <- P.char '\"'
return x
------------------------------------------------------------------------------
isPubIdChar :: Char -> Bool
isPubIdChar c | c >= 'a' && c <= 'z' = True
| c >= 'A' && c <= 'Z' = True
| c >= '0' && c <= '9' = True
| c `elem` otherChars = True
| otherwise = False
where
otherChars = " \r\n-\'()+,./:=?;!*#@$_%" :: [Char]
------------------------------------------------------------------------------
-- | The requirement to not contain "]]>" is for SGML compatibility. We
-- deliberately choose to not enforce it. This makes the parser accept
-- strictly more documents than a standards-compliant parser.
charData :: Parser Node
charData = TextNode <$> takeWhile1 (not . (`elem` ['<','&']))
------------------------------------------------------------------------------
comment :: Parser (Maybe Node)
comment = text "<!--" *> (Just <$> Comment <$> commentText) <* text "-->"
where
commentText = fmap T.concat $ many $
nonDash <|> P.try (T.cons <$> P.char '-' <*> nonDash)
nonDash = takeWhile1 (not . (== '-'))
------------------------------------------------------------------------------
-- | Always returns Nothing since there's no representation for a PI in the
-- document tree.
processingInstruction :: Parser (Maybe Node)
processingInstruction = do
_ <- text "<?"
_ <- piTarget
_ <- emptyEnd <|> contentEnd
return Nothing
where
emptyEnd = P.try (P.string "?>")
contentEnd = P.try $ do
_ <- whiteSpace
P.manyTill P.anyChar (P.try $ text "?>")
------------------------------------------------------------------------------
piTarget :: Parser ()
piTarget = do
n <- name
when (T.map toLower n == "xml") $ fail "xml declaration can't occur here"
------------------------------------------------------------------------------
cdata :: [Char] -> Parser a -> Parser Node
cdata cs end = TextNode <$> T.concat <$> P.manyTill part end
where part = takeWhile1 (not . (`elem` cs))
<|> T.singleton <$> P.anyChar
------------------------------------------------------------------------------
cdSect :: Parser (Maybe Node)
cdSect = Just <$> do
_ <- text "<![CDATA["
cdata "]" (text "]]>")
------------------------------------------------------------------------------
prolog :: Parser (Maybe DocType, [Node])
prolog = do
_ <- optional xmlDecl
nodes1 <- many misc
rest <- optional $ do
dt <- docTypeDecl
nodes2 <- many misc
return (dt, nodes2)
case rest of
Nothing -> return (Nothing, catMaybes nodes1)
Just (dt, nodes2) -> return (Just dt, catMaybes (nodes1 ++ nodes2))
------------------------------------------------------------------------------
-- | Return value is the encoding, if present.
xmlDecl :: Parser (Maybe Text)
xmlDecl = do
_ <- text "<?xml"
_ <- versionInfo
e <- optional encodingDecl
_ <- optional sdDecl
_ <- optional whiteSpace
_ <- text "?>"
return e
------------------------------------------------------------------------------
versionInfo :: Parser ()
versionInfo = do
whiteSpace *> text "version" *> eq *> (singleQuoted <|> doubleQuoted)
where
singleQuoted = P.char '\'' *> versionNum <* P.char '\''
doubleQuoted = P.char '\"' *> versionNum <* P.char '\"'
versionNum = do
_ <- text "1."
_ <- some (P.satisfy (\c -> c >= '0' && c <= '9'))
return ()
------------------------------------------------------------------------------
eq :: Parser ()
eq = optional whiteSpace *> P.char '=' *> optional whiteSpace *> return ()
------------------------------------------------------------------------------
misc :: Parser (Maybe Node)
misc = comment <|> processingInstruction <|> (whiteSpace *> return Nothing)
------------------------------------------------------------------------------
-- | Internal subset is parsed, but ignored since we don't have data types to
-- store it.
docTypeDecl :: Parser DocType
docTypeDecl = do
_ <- text "<!DOCTYPE"
whiteSpace
tag <- name
_ <- optional whiteSpace
extid <- externalID
_ <- optional whiteSpace
intsub <- internalDoctype
_ <- P.char '>'
return (DocType tag extid intsub)
------------------------------------------------------------------------------
-- | States for the DOCTYPE internal subset state machine.
data InternalDoctypeState = IDSStart
| IDSScanning Int
| IDSInQuote Int Char
| IDSCommentS1 Int
| IDSCommentS2 Int
| IDSCommentS3 Int
| IDSComment Int
| IDSCommentD1 Int
| IDSCommentE1 Int
------------------------------------------------------------------------------
-- | Internal DOCTYPE subset. We don't actually parse this; just scan through
-- and look for the end, and store it in a block of text.
internalDoctype :: Parser InternalSubset
internalDoctype = InternalText <$> T.pack <$> scanText (dfa IDSStart)
<|> return NoInternalSubset
where dfa IDSStart '[' = ScanNext (dfa (IDSScanning 0))
dfa IDSStart _ = ScanFail "Not a DOCTYPE internal subset"
dfa (IDSInQuote n c) d
| c == d = ScanNext (dfa (IDSScanning n))
| otherwise = ScanNext (dfa (IDSInQuote n c))
dfa (IDSScanning n) '[' = ScanNext (dfa (IDSScanning (n+1)))
dfa (IDSScanning 0) ']' = ScanFinish
dfa (IDSScanning n) ']' = ScanNext (dfa (IDSScanning (n-1)))
dfa (IDSScanning n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
dfa (IDSScanning n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
dfa (IDSScanning n) '<' = ScanNext (dfa (IDSCommentS1 n))
dfa (IDSScanning n) _ = ScanNext (dfa (IDSScanning n))
dfa (IDSCommentS1 n) '[' = ScanNext (dfa (IDSScanning (n+1)))
dfa (IDSCommentS1 0) ']' = ScanFinish
dfa (IDSCommentS1 n) ']' = ScanNext (dfa (IDSScanning (n-1)))
dfa (IDSCommentS1 n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
dfa (IDSCommentS1 n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
dfa (IDSCommentS1 n) '!' = ScanNext (dfa (IDSCommentS2 n))
dfa (IDSCommentS1 n) _ = ScanNext (dfa (IDSScanning n))
dfa (IDSCommentS2 n) '[' = ScanNext (dfa (IDSScanning (n+1)))
dfa (IDSCommentS2 0) ']' = ScanFinish
dfa (IDSCommentS2 n) ']' = ScanNext (dfa (IDSScanning (n-1)))
dfa (IDSCommentS2 n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
dfa (IDSCommentS2 n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
dfa (IDSCommentS2 n) '-' = ScanNext (dfa (IDSCommentS3 n))
dfa (IDSCommentS2 n) _ = ScanNext (dfa (IDSScanning n))
dfa (IDSCommentS3 n) '[' = ScanNext (dfa (IDSScanning (n+1)))
dfa (IDSCommentS3 0) ']' = ScanFinish
dfa (IDSCommentS3 n) ']' = ScanNext (dfa (IDSScanning (n-1)))
dfa (IDSCommentS3 n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
dfa (IDSCommentS3 n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
dfa (IDSCommentS3 n) '-' = ScanNext (dfa (IDSComment n))
dfa (IDSCommentS3 n) _ = ScanNext (dfa (IDSScanning n))
dfa (IDSComment n) '-' = ScanNext (dfa (IDSCommentD1 n))
dfa (IDSComment n) _ = ScanNext (dfa (IDSComment n))
dfa (IDSCommentD1 n) '-' = ScanNext (dfa (IDSCommentE1 n))
dfa (IDSCommentD1 n) _ = ScanNext (dfa (IDSComment n))
dfa (IDSCommentE1 n) '>' = ScanNext (dfa (IDSScanning n))
dfa (IDSCommentE1 _) _ = ScanFail "Poorly formatted comment"
------------------------------------------------------------------------------
sdDecl :: Parser ()
sdDecl = do
_ <- P.try $ whiteSpace *> text "standalone"
eq
_ <- single <|> double
return ()
where
single = P.char '\'' *> yesno <* P.char '\''
double = P.char '\"' *> yesno <* P.char '\"'
yesno = text "yes" <|> text "no"
------------------------------------------------------------------------------
element :: Parser Node
element = do
(t,a,b) <- emptyOrStartTag
if b then return (Element t a [])
else nonEmptyElem t a
where
nonEmptyElem t a = do
c <- content
endTag t
return (Element t a c)
------------------------------------------------------------------------------
-- | Results are (tag name, attributes, isEmpty)
emptyOrStartTag :: Parser (Text, [(Text, Text)], Bool)
emptyOrStartTag = do
t <- P.try $ P.char '<' *> name
a <- many $ P.try $ do
whiteSpace
attribute
when (hasDups a) $ fail "Duplicate attribute names in element"
_ <- optional whiteSpace
e <- optional (P.char '/')
_ <- P.char '>'
return (t, a, isJust e)
where
hasDups a = length (nub (map fst a)) < length a
------------------------------------------------------------------------------
attribute :: Parser (Text, Text)
attribute = do
n <- name
eq
v <- attrValue
return (n,v)
------------------------------------------------------------------------------
endTag :: Text -> Parser ()
endTag s = do
_ <- text "</"
t <- name
when (s /= t) $ fail $ "mismatched tags: </" ++ T.unpack t ++
"> found inside <" ++ T.unpack s ++ "> tag"
_ <- optional whiteSpace
_ <- text ">"
return ()
------------------------------------------------------------------------------
content :: Parser [Node]
content = do
n <- optional charData
ns <- fmap concat $ many $ do
s <- ((Just <$> TextNode <$> reference)
<|> cdSect
<|> processingInstruction
<|> comment
<|> fmap Just element)
t <- optional charData
return [s,t]
return $ coalesceText $ catMaybes (n:ns)
where
coalesceText (TextNode s : TextNode t : ns)
= coalesceText (TextNode (T.append s t) : ns)
coalesceText (n:ns)
= n : coalesceText ns
coalesceText []
= []
------------------------------------------------------------------------------
charRef :: Parser Text
charRef = hexCharRef <|> decCharRef
where
decCharRef = do
_ <- text "&#"
ds <- some digit
_ <- P.char ';'
let c = chr $ foldl' (\a b -> 10 * a + b) 0 ds
when (not (isValidChar c)) $ fail $
"Reference is not a valid character"
return $ T.singleton c
where
digit = do
d <- P.satisfy (\c -> c >= '0' && c <= '9')
return (ord d - ord '0')
hexCharRef = do
_ <- text "&#x"
ds <- some digit
_ <- P.char ';'
let c = chr $ foldl' (\a b -> 16 * a + b) 0 ds
when (not (isValidChar c)) $ fail $
"Reference is not a valid character"
return $ T.singleton c
where
digit = num <|> upper <|> lower
num = do
d <- P.satisfy (\c -> c >= '0' && c <= '9')
return (ord d - ord '0')
upper = do
d <- P.satisfy (\c -> c >= 'A' && c <= 'F')
return (10 + ord d - ord 'A')
lower = do
d <- P.satisfy (\c -> c >= 'a' && c <= 'f')
return (10 + ord d - ord 'a')
------------------------------------------------------------------------------
reference :: Parser Text
reference = charRef <|> entityRef
------------------------------------------------------------------------------
entityRef :: Parser Text
entityRef = do
_ <- P.char '&'
n <- name
_ <- P.char ';'
case M.lookup n entityRefLookup of
Nothing -> fail $ "Unknown entity reference: " ++ T.unpack n
Just t -> return t
where
entityRefLookup :: Map Text Text
entityRefLookup = M.fromList [
("amp", "&"),
("lt", "<"),
("gt", ">"),
("apos", "\'"),
("quot", "\"")
]
------------------------------------------------------------------------------
externalID :: Parser ExternalID
externalID = systemID <|> publicID <|> return NoExternalID
where
systemID = do
_ <- text "SYSTEM"
whiteSpace
fmap System systemLiteral
publicID = do
_ <- text "PUBLIC"
whiteSpace
pid <- pubIdLiteral
whiteSpace
sid <- systemLiteral
return (Public pid sid)
------------------------------------------------------------------------------
encodingDecl :: Parser Text
encodingDecl = do
_ <- P.try $ whiteSpace *> text "encoding"
_ <- eq
singleQuoted <|> doubleQuoted
where
singleQuoted = P.char '\'' *> encName <* P.char '\''
doubleQuoted = P.char '\"' *> encName <* P.char '\"'
encName = do
c <- P.satisfy isEncStart
cs <- takeWhile0 isEnc
return (T.cons c cs)
isEncStart c | c >= 'A' && c <= 'Z' = True
| c >= 'a' && c <= 'z' = True
| otherwise = False
isEnc c | c >= 'A' && c <= 'Z' = True
| c >= 'a' && c <= 'z' = True
| c >= '0' && c <= '9' = True
| c `elem` ['.','_','-'] = True
| otherwise = False
| 23Skidoo/xmlhtml | src/Text/XmlHtml/XML/Parse.hs | bsd-3-clause | 22,675 | 0 | 19 | 8,010 | 5,380 | 2,642 | 2,738 | 356 | 37 |
-- |
-- Module : Data.Hourglass.Internal.Unix
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- Time lowlevel helpers for the unix operating system
--
-- depend on localtime_r and gmtime_r.
-- Some obscure unix system might not support them.
--
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE EmptyDataDecls #-}
module Data.Hourglass.Internal.Unix
( dateTimeFromUnixEpochP
, dateTimeFromUnixEpoch
, systemGetTimezone
, systemGetElapsed
, systemGetElapsedP
) where
import Control.Applicative
import Foreign.C.Types
import Foreign.Storable
import Foreign.Marshal.Alloc
import Foreign.Ptr
import Data.Hourglass.Types
import System.IO.Unsafe
-- | convert a unix epoch precise to DateTime
dateTimeFromUnixEpochP :: ElapsedP -> DateTime
dateTimeFromUnixEpochP (ElapsedP e ns) = fromCP ns $ rawGmTime e
-- | convert a unix epoch to DateTime
dateTimeFromUnixEpoch :: Elapsed -> DateTime
dateTimeFromUnixEpoch e = fromC $ rawGmTime e
-- | return the timezone offset in minutes
systemGetTimezone :: IO TimezoneOffset
systemGetTimezone = TimezoneOffset . fromIntegral . flip div 60 <$> localTime 0
----------------------------------------------------------------------------------------
-- | return the current elapsedP
systemGetElapsedP :: IO ElapsedP
systemGetElapsedP = allocaBytesAligned sofTimespec 8 $ \ptr -> do
c_clock_get ptr
toElapsedP <$> peek (castPtr ptr) <*> peekByteOff (castPtr ptr) sofCTime
where sofTimespec = sofCTime + sofCLong
sofCTime = sizeOf (0 :: CTime)
sofCLong = sizeOf (0 :: CLong)
#if (MIN_VERSION_base(4,5,0))
toElapsedP :: CTime -> CLong -> ElapsedP
toElapsedP (CTime sec) nsec = ElapsedP (Elapsed $ Seconds (fromIntegral sec)) (fromIntegral nsec)
#else
toElapsedP :: CLong -> CLong -> ElapsedP
toElapsedP sec nsec = ElapsedP (Elapsed $ Seconds (fromIntegral sec)) (fromIntegral nsec)
#endif
-- | return the current elapsed
systemGetElapsed :: IO Elapsed
systemGetElapsed = allocaBytesAligned sofTimespec 8 $ \ptr -> do
c_clock_get ptr
toElapsed <$> peek (castPtr ptr)
where sofTimespec = sizeOf (0 :: CTime) + sizeOf (0 :: CLong)
#if (MIN_VERSION_base(4,5,0))
toElapsed :: CTime -> Elapsed
toElapsed (CTime sec) = Elapsed $ Seconds (fromIntegral sec)
#else
toElapsed :: CLong -> Elapsed
toElapsed sec = Elapsed $ Seconds (fromIntegral sec)
#endif
foreign import ccall unsafe "hourglass_clock_calendar"
c_clock_get :: Ptr CLong -> IO ()
#if (MIN_VERSION_base(4,5,0))
foreign import ccall unsafe "gmtime_r"
c_gmtime_r :: Ptr CTime -> Ptr CTm -> IO (Ptr CTm)
foreign import ccall unsafe "localtime_r"
c_localtime_r :: Ptr CTime -> Ptr CTm -> IO (Ptr CTm)
#else
foreign import ccall unsafe "gmtime_r"
c_gmtime_r :: Ptr CLong -> Ptr CTm -> IO (Ptr CTm)
foreign import ccall unsafe "localtime_r"
c_localtime_r :: Ptr CLong -> Ptr CTm -> IO (Ptr CTm)
#endif
-- | Return a global time's struct tm based on the number of elapsed second since unix epoch.
rawGmTime :: Elapsed -> CTm
rawGmTime (Elapsed (Seconds s)) = unsafePerformIO callTime
where callTime =
alloca $ \ctmPtr -> do
alloca $ \ctimePtr -> do
poke ctimePtr ctime
r <- c_gmtime_r ctimePtr ctmPtr
if r == nullPtr
then error "gmTime failed"
else peek ctmPtr
ctime = fromIntegral s
{-# NOINLINE rawGmTime #-}
-- | Return a local time's gmtoff (seconds east of UTC)
--
-- use the ill defined gmtoff (at offset 40) that might or might not be
-- available for your platform. worst case scenario it's not initialized
-- properly.
localTime :: Elapsed -> IO CLong
localTime (Elapsed (Seconds s)) = callTime
where callTime =
alloca $ \ctmPtr -> do
alloca $ \ctimePtr -> do
poke ctimePtr ctime
r <- c_localtime_r ctimePtr ctmPtr
if r == nullPtr
then error "localTime failed"
else peekByteOff ctmPtr 40
ctime = fromIntegral s
-- | Represent the beginning of struct tm
data CTm = CTm
{ ctmSec :: CInt
, ctmMin :: CInt
, ctmHour :: CInt
, ctmMDay :: CInt
, ctmMon :: CInt
, ctmYear :: CInt
} deriving (Show,Eq)
-- | Convert a C structure to a DateTime structure
fromC :: CTm -> DateTime
fromC ctm = DateTime date time
where date = Date
{ dateYear = fromIntegral $ ctmYear ctm + 1900
, dateMonth = toEnum $ fromIntegral $ ctmMon ctm
, dateDay = fromIntegral $ ctmMDay ctm
}
time = TimeOfDay
{ todHour = fromIntegral $ ctmHour ctm
, todMin = fromIntegral $ ctmMin ctm
, todSec = fromIntegral $ ctmSec ctm
, todNSec = 0
}
-- | Similar to 'fromC' except with nanosecond precision
fromCP :: NanoSeconds -> CTm -> DateTime
fromCP ns ctm = DateTime d (t { todNSec = ns })
where (DateTime d t) = fromC ctm
instance Storable CTm where
alignment _ = 8
sizeOf _ = 60 -- account for 9 ints, alignment + 2 unsigned long at end.
peek ptr = do
CTm <$> peekByteOff intPtr 0
<*> peekByteOff intPtr 4
<*> peekByteOff intPtr 8
<*> peekByteOff intPtr 12
<*> peekByteOff intPtr 16
<*> peekByteOff intPtr 20
where intPtr = castPtr ptr
poke ptr (CTm f0 f1 f2 f3 f4 f5) = do
mapM_ (uncurry (pokeByteOff intPtr))
[(0,f0), (4,f1), (8,f2), (12,f3), (16,f4), (20,f5)]
--pokeByteOff (castPtr ptr) 36 f9
where intPtr = castPtr ptr
| ppelleti/hs-hourglass | Data/Hourglass/Internal/Unix.hs | bsd-3-clause | 5,804 | 0 | 16 | 1,533 | 1,244 | 666 | 578 | 104 | 2 |
module Language.Ava.TypeCheck.Composable where
class (Composeable a) where
comp :: a -> a -> Bool
| owainlewis/ava | src/Language/Ava/TypeCheck/Composable.hs | bsd-3-clause | 101 | 2 | 7 | 17 | 28 | 17 | 11 | 3 | 0 |
{-# LANGUAGE BangPatterns #-}
module Common.World
( World(..)
, advanceWorld)
where
import Common.Body
import qualified Data.Vector.Unboxed as V
data World
= World
{ -- | Bodies in the simulation.
worldBodies :: !(V.Vector Body)
-- | Number of steps taken in the simulation so far.
, worldSteps :: !Int }
-- | Advance the world forward in time.
advanceWorld
:: (V.Vector MassPoint -> V.Vector Accel)
-- ^ Fn to compute accelerations of each point.
-> Double -- ^ Time step.
-> World
-> World
advanceWorld calcAccels timeStep world
= let
-- Calculate the accelerations on each body.
accels = calcAccels
$ V.map massPointOfBody
$ worldBodies world
-- Apply the accelerations to the bodies and advance them.
bodies' = V.zipWith
(\body (ax, ay)
-> advanceBody timeStep
(setAccelOfBody (-ax, -ay) body))
(worldBodies world)
accels
-- Update the world.
steps' = worldSteps world + 1
in world { worldBodies = bodies'
, worldSteps = steps' }
| mainland/dph | dph-examples/examples/real/NBody/Common/World.hs | bsd-3-clause | 1,002 | 50 | 16 | 220 | 272 | 155 | 117 | 33 | 1 |
{-# LANGUAGE StrictData #-}
--------------------------------------------------------------------------------
-- |
-- Module : HEP.Data.HepMC.Type
-- Copyright : (c) 2017 Chan Beom Park
-- License : BSD-style
-- Maintainer : Chan Beom Park <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Types for HepMC event data.
--
-- See <http://hepmc.web.cern.ch/hepmc/releases/HepMC2_user_manual.pdf HepMC 2 user manual>.
--
--------------------------------------------------------------------------------
module HEP.Data.HepMC.Type where
import Data.ByteString.Char8 (ByteString)
import HEP.Kinematics (HasFourMomentum (..))
import HEP.Kinematics.Vector.LorentzVector (setXYZT)
type Version = ByteString
data GenEvent = GenEvent { -- | event number
eventNumber :: Int
-- | number of multi paricle interactions
, numMultiParticleInt :: Int
-- | event scale
, eventScale :: Double
-- | \alpha_{QCD}
, alphaQCD :: Double
-- | \alpha_{QED}
, alphaQED :: Double
-- | signal process id
, signalProcId :: Int
-- | barcode for signal process vertex
, signalProcVertex :: Int
-- | number of vertices in this event
, numVertex :: Int
-- | barcode for beam particles (1, 2)
, beamParticles :: (Int, Int)
-- | random state list (may be zero)
, randomStateList :: Maybe (Int, [Int])
-- | weight list (may be zero)
, weightList :: Maybe (Int, [Double])
, eventHeader :: EventHeader
, vertices :: [GenVertex]
} deriving Show
data EventHeader = EventHeader { weightInfo :: Maybe WeightNames
, unitInfo :: Maybe MomentumPositionUnit
, crossSectionInfo :: Maybe GenCrossSection
, heavyIonInfo :: Maybe HeavyIon
, pdfInfo :: Maybe PdfInfo
} deriving Show
data WeightNames = WeightNames { -- | number of entries in weight name list
numEntries :: Int
-- | list of weight names enclosed in quotes
, weightNames :: [ByteString]
} deriving Show
data MomentumUnit = GeV | MeV deriving (Eq, Show)
data LengthUnit = MM | CM deriving (Eq, Show)
data MomentumPositionUnit = MomentumPositionUnit
{ -- | momentum units (MEV or GEV)
momentumUnit :: MomentumUnit
-- | length units (MM or CM)
, lengthUnit :: LengthUnit
} deriving (Eq, Show)
data GenCrossSection = GenCrossSection
{ -- | cross section in pb
xsec :: Double
-- | error associated with this cross section in pb
, errorXsec :: Double
} deriving Show
data HeavyIon = HeavyIon { -- | Number of hard scatterings
numHardScattering :: Int
-- | Number of projectile participants
, numProjectileParticipants :: Int
-- | Number of target participants
, numTargetParticipants :: Int
-- | Number of NN (nucleon-nucleon) collisions
, numNNCollisions :: Int
-- | Number of spectator neutrons
, numSpectatorNeutrons :: Int
-- | Number of spectator protons
, numSpectatorProtons :: Int
-- | Number of N-Nwounded collisions
, numNNwoundedCollisions :: Int
-- | Number of Nwounded-N collisons
, numNwoundedNCollisions :: Int
-- | Number of Nwounded-Nwounded collisions
, numNwoundedNwoundedCollisions :: Int
-- | Impact Parameter(fm) of collision
, impactParamCollision :: Double
-- | Azimuthal angle of event plane
, eventPlaneAngle :: Double
-- | eccentricity of participating nucleons
-- in the transverse plane
, eccentricity :: Double
-- | nucleon-nucleon inelastic cross-section
, inelasticXsecNN :: Double
} deriving Show
data PdfInfo = PdfInfo { -- | flavour code of first and second partons
flavor :: (Int, Int)
-- | fraction of beam momentum carried by first and second partons
, beamMomentumFrac :: (Double, Double)
-- | Q-scale used in evaluation of PDF’s (in GeV)
, scaleQPDF :: Double
-- | x * f(x)
, xfx :: (Double, Double)
-- | LHAPDF set id of first and second partons (zero by default)
, idLHAPDF :: (Int, Int)
} deriving Show
data GenVertex = GenVertex { -- | barcode
vbarcode :: Int
-- | id
, vid :: Int
-- | (x, y, z, c\tau)
, vposition :: (Double, Double, Double, Double)
-- | number of ”orphan” incoming particles
, numOrphan :: Int
-- | number of outgoing particles
, numOutgoing :: Int
-- | list of weights (may be zero)
, vWeightList :: Maybe (Int, [Double])
, particles :: [GenParticle]
} deriving Show
data GenParticle = GenParticle { -- | barcode
pbarcode :: Int
-- | PDG id
, pdgID :: Int
-- | (px, py, pz, energy)
, pMomentum :: (Double, Double, Double, Double)
-- | generated mass
, pMass :: Double
-- | status code
, statusCode :: Int
-- | (\theta, \phi) of polarization
, polarization :: (Double, Double)
-- | barcode for vertex that has this particle
-- as an incoming particle
, vbarcodeThisIncoming :: Int
-- | flow list (may be zero)
, flows :: Maybe (Int, [(Int, Int)])
} deriving Show
instance HasFourMomentum GenParticle where
-- fourMomentum :: GenParticle -> FourMomentum
fourMomentum GenParticle { pMomentum = (x, y, z, e) } = setXYZT x y z e
{-# INLINE fourMomentum #-}
pt GenParticle { pMomentum = (x, y, _, _) } = sqrt (x * x + y * y)
{-# INLINE pt #-}
mass GenParticle { pMass = m } = m
{-# INLINE mass #-}
epxpypz GenParticle { pMomentum = (x, y, z, e) } = (e, x, y, z)
{-# INLINE epxpypz #-}
pxpypz GenParticle { pMomentum = (x, y, z, _) } = (x, y, z)
{-# INLINE pxpypz #-}
pxpy GenParticle { pMomentum = (x, y, _, _) } = (x, y)
{-# INLINE pxpy #-}
px GenParticle { pMomentum = (x, _, _, _) } = x
{-# INLINE px #-}
py GenParticle { pMomentum = (_, y, _, _) } = y
{-# INLINE py #-}
pz GenParticle { pMomentum = (_, _, z, _) } = z
{-# INLINE pz #-}
energy GenParticle { pMomentum = (_, _, _, e) } = e
{-# INLINE energy #-}
| cbpark/hep-kinematics | src/HEP/Data/HepMC/Type.hs | bsd-3-clause | 8,986 | 0 | 12 | 4,498 | 1,106 | 710 | 396 | 103 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Haddock
-- Copyright : (c) Andrea Vezzosi 2009
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- Interfacing with Haddock
--
-----------------------------------------------------------------------------
module Distribution.Client.Haddock
(
regenerateHaddockIndex
)
where
import Data.Maybe (listToMaybe)
import Data.List (maximumBy)
import Control.Monad (guard)
import System.Directory (createDirectoryIfMissing, doesFileExist,
renameFile)
import System.FilePath ((</>), splitFileName, isAbsolute)
import Distribution.Package
( Package(..), packageVersion )
import Distribution.Simple.Program (haddockProgram, ProgramConfiguration
, rawSystemProgram, requireProgramVersion)
import Distribution.Version (Version(Version), orLaterVersion)
import Distribution.Verbosity (Verbosity)
import Distribution.Text (display)
import Distribution.Simple.PackageIndex
( PackageIndex, allPackagesByName )
import Distribution.Simple.Utils
( comparing, intercalate, debug
, installDirectoryContents, withTempDirectory )
import Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo
, InstalledPackageInfo_(haddockHTMLs, haddockInterfaces, exposed) )
regenerateHaddockIndex :: Verbosity -> PackageIndex -> ProgramConfiguration -> FilePath -> IO ()
regenerateHaddockIndex verbosity pkgs conf index = do
(paths,warns) <- haddockPackagePaths pkgs'
case warns of
Nothing -> return ()
Just m -> debug verbosity m
(confHaddock, _, _) <-
requireProgramVersion verbosity haddockProgram
(orLaterVersion (Version [0,6] [])) conf
createDirectoryIfMissing True destDir
withTempDirectory verbosity destDir "tmphaddock" $ \tempDir -> do
let flags = [ "--gen-contents"
, "--gen-index"
, "--odir=" ++ tempDir
, "--title=Haskell modules on this system" ]
++ [ "--read-interface=" ++ html ++ "," ++ interface
| (interface, html) <- paths ]
rawSystemProgram verbosity confHaddock flags
renameFile (tempDir </> "index.html") (tempDir </> destFile)
installDirectoryContents verbosity tempDir destDir
where
(destDir,destFile) = splitFileName index
pkgs' = [ maximumBy (comparing packageVersion) pkgvers'
| (_pname, pkgvers) <- allPackagesByName pkgs
, let pkgvers' = filter exposed pkgvers
, not (null pkgvers') ]
haddockPackagePaths :: [InstalledPackageInfo]
-> IO ([(FilePath, FilePath)], Maybe String)
haddockPackagePaths pkgs = do
interfaces <- sequence
[ case interfaceAndHtmlPath pkg of
Just (interface, html) -> do
exists <- doesFileExist interface
if exists
then return (pkgid, Just (interface, html))
else return (pkgid, Nothing)
Nothing -> return (pkgid, Nothing)
| pkg <- pkgs, let pkgid = packageId pkg ]
let missing = [ pkgid | (pkgid, Nothing) <- interfaces ]
warning = "The documentation for the following packages are not "
++ "installed. No links will be generated to these packages: "
++ intercalate ", " (map display missing)
flags = [ x | (_, Just x) <- interfaces ]
return (flags, if null missing then Nothing else Just warning)
where
interfaceAndHtmlPath pkg = do
interface <- listToMaybe (InstalledPackageInfo.haddockInterfaces pkg)
html <- fmap fixFileUrl
(listToMaybe (InstalledPackageInfo.haddockHTMLs pkg))
guard (not . null $ html)
return (interface, html)
-- the 'haddock-html' field in the hc-pkg output is often set as a
-- native path, but we need it as a URL.
-- See https://github.com/haskell/cabal/issues/1064
fixFileUrl f | isAbsolute f = "file://" ++ f
| otherwise = f
| jwiegley/ghc-release | libraries/Cabal/cabal-install/Distribution/Client/Haddock.hs | gpl-3.0 | 4,208 | 2 | 19 | 1,084 | 939 | 511 | 428 | 75 | 4 |
module Settings.Builders.Ghc (ghcBuilderArgs, haddockGhcArgs) where
import Hadrian.Haskell.Cabal
import Hadrian.Haskell.Cabal.Type
import Flavour
import Packages
import Settings.Builders.Common
import Settings.Warnings
ghcBuilderArgs :: Args
ghcBuilderArgs = mconcat [compileAndLinkHs, compileC, findHsDependencies]
compileAndLinkHs :: Args
compileAndLinkHs = (builder (Ghc CompileHs) ||^ builder (Ghc LinkHs)) ? do
mconcat [ arg "-Wall"
, commonGhcArgs
, splitObjects <$> flavour ? arg "-split-objs"
, ghcLinkArgs
, defaultGhcWarningsArgs
, builder (Ghc CompileHs) ? arg "-c"
, getInputs
, arg "-o", arg =<< getOutput ]
compileC :: Args
compileC = builder (Ghc CompileCWithGhc) ? do
way <- getWay
let ccArgs = [ getContextData ccOpts
, getStagedSettingList ConfCcArgs
, cIncludeArgs
, Dynamic `wayUnit` way ? pure [ "-fPIC", "-DDYNAMIC" ] ]
mconcat [ arg "-Wall"
, ghcLinkArgs
, commonGhcArgs
, mconcat (map (map ("-optc" ++) <$>) ccArgs)
, defaultGhcWarningsArgs
, arg "-c"
, getInputs
, arg "-o"
, arg =<< getOutput ]
ghcLinkArgs :: Args
ghcLinkArgs = builder (Ghc LinkHs) ? do
way <- getWay
pkg <- getPackage
libs <- pkg == hp2ps ? pure ["m"]
intLib <- getIntegerPackage
gmpLibs <- notStage0 ? intLib == integerGmp ? pure ["gmp"]
mconcat [ (Dynamic `wayUnit` way) ?
pure [ "-shared", "-dynamic", "-dynload", "deploy" ]
, arg "-no-auto-link-packages"
, nonHsMainPackage pkg ? arg "-no-hs-main"
, not (nonHsMainPackage pkg) ? arg "-rtsopts"
, pure [ "-optl-l" ++ lib | lib <- libs ++ gmpLibs ]
]
findHsDependencies :: Args
findHsDependencies = builder (Ghc FindHsDependencies) ? do
ways <- getLibraryWays
mconcat [ arg "-M"
, commonGhcArgs
, arg "-include-pkg-deps"
, arg "-dep-makefile", arg =<< getOutput
, pure $ concat [ ["-dep-suffix", wayPrefix w] | w <- ways ]
, getInputs ]
haddockGhcArgs :: Args
haddockGhcArgs = mconcat [ commonGhcArgs, getContextData hcOpts ]
-- | Common GHC command line arguments used in 'ghcBuilderArgs',
-- 'ghcCBuilderArgs', 'ghcMBuilderArgs' and 'haddockGhcArgs'.
commonGhcArgs :: Args
commonGhcArgs = do
way <- getWay
path <- getBuildPath
ghcVersion <- expr ghcVersionH
mconcat [ arg "-hisuf", arg $ hisuf way
, arg "-osuf" , arg $ osuf way
, arg "-hcsuf", arg $ hcsuf way
, wayGhcArgs
, packageGhcArgs
, includeGhcArgs
-- When compiling RTS for Stage1 or Stage2 we do not have it (yet)
-- in the package database. We therefore explicity supply the path
-- to the @ghc-version@ file, to prevent GHC from trying to open the
-- RTS package in the package database and failing.
, package rts ? notStage0 ? arg ("-ghcversion-file=" ++ ghcVersion)
, map ("-optc" ++) <$> getStagedSettingList ConfCcArgs
, map ("-optP" ++) <$> getStagedSettingList ConfCppArgs
, map ("-optP" ++) <$> getContextData cppOpts
, arg "-odir" , arg path
, arg "-hidir" , arg path
, arg "-stubdir" , arg path ]
-- TODO: Do '-ticky' in all debug ways?
wayGhcArgs :: Args
wayGhcArgs = do
way <- getWay
mconcat [ if (Dynamic `wayUnit` way)
then pure ["-fPIC", "-dynamic"]
else arg "-static"
, (Threaded `wayUnit` way) ? arg "-optc-DTHREADED_RTS"
, (Debug `wayUnit` way) ? arg "-optc-DDEBUG"
, (Profiling `wayUnit` way) ? arg "-prof"
, (Logging `wayUnit` way) ? arg "-eventlog"
, (way == debug || way == debugDynamic) ?
pure ["-ticky", "-DTICKY_TICKY"] ]
packageGhcArgs :: Args
packageGhcArgs = do
package <- getPackage
pkgId <- expr $ pkgIdentifier package
mconcat [ arg "-hide-all-packages"
, arg "-no-user-package-db"
, packageDatabaseArgs
, libraryPackage ? arg ("-this-unit-id " ++ pkgId)
, map ("-package-id " ++) <$> getContextData depIds ]
includeGhcArgs :: Args
includeGhcArgs = do
pkg <- getPackage
path <- getBuildPath
root <- getBuildRoot
context <- getContext
srcDirs <- getContextData srcDirs
autogen <- expr $ autogenPath context
mconcat [ arg "-i"
, arg $ "-i" ++ path
, arg $ "-i" ++ autogen
, pure [ "-i" ++ pkgPath pkg -/- dir | dir <- srcDirs ]
, cIncludeArgs
, arg $ "-I" ++ root -/- generatedDir
, arg $ "-optc-I" ++ root -/- generatedDir
, pure ["-optP-include", "-optP" ++ autogen -/- "cabal_macros.h"] ]
| snowleopard/shaking-up-ghc | src/Settings/Builders/Ghc.hs | bsd-3-clause | 5,006 | 0 | 15 | 1,602 | 1,269 | 667 | 602 | 114 | 2 |
module Fun00013 where
data Manifest sh a = Syntax a => Manifest (Data [Internal a]) (Data [Length])
| charleso/intellij-haskforce | tests/gold/parser/Fun00013.hs | apache-2.0 | 101 | 0 | 10 | 18 | 45 | 25 | 20 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sr-CS">
<title>Advanced SQLInjection Scanner</title>
<maps>
<homeID>sqliplugin</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/sqliplugin/src/main/javahelp/help_sr_CS/helpset_sr_CS.hs | apache-2.0 | 981 | 77 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
{-# Language LambdaCase #-}
module Main where
import Common
import Control.Monad
import Text.Megaparsec
import Text.Megaparsec.Char
main :: IO ()
main =
do xs <- lines <$> readInputFile 9
print (sum (map decode1 xs))
print (sum (map decode2 xs))
decode1 :: String -> Int
decode1 = mkDecode (\n xs -> n * length xs)
decode2 :: String -> Int
decode2 = mkDecode (\n xs -> n * decode2 xs)
mkDecode ::
(Int -> String -> Int) {- ^ repeated segment logic -} ->
String {- ^ input string -} ->
Int {- ^ decoded length -}
mkDecode f = parseOrDie (sum <$> many (plain <|> repeated))
where
plain = length <$> some (satisfy (/='('))
repeated =
do len <- char '(' *> number <* char 'x'
f <$> number <* char ')' <*> replicateM len anySingle
| glguy/advent2016 | Day09.hs | isc | 829 | 0 | 12 | 238 | 289 | 149 | 140 | 24 | 1 |
module System.Posix.FileLock (lock,unlock,withLock,FileLock,LockType(..)) where
import Control.Exception (bracket)
import Control.Monad.IO.Class (MonadIO(..), liftIO)
import qualified System.Posix.Files as Posix
import qualified System.Posix.IO as Posix
import qualified System.Posix.Types as Posix
import System.IO
data FileLock = FileLock Posix.Fd Posix.FileLock
data LockType = ReadLock | WriteLock deriving (Eq, Show, Read)
-- | Gets the lock, executes the IO action, and then releases the lock.
-- Releases the lock even if an exception occurs.
withLock :: (MonadIO m) => FilePath -> LockType -> IO a -> m a
withLock pth t x = liftIO $ bracket (lock pth t) unlock (const x)
-- | Get a lock of the given type on the given path
lock :: (MonadIO m) => FilePath -> LockType -> m FileLock
lock pth t = liftIO $ do
fd <- Posix.openFd pth om mode Posix.defaultFileFlags
-- WARNING: I've been told the following line blocks the whole process?
Posix.waitToSetLock fd (req, AbsoluteSeek, 0, 0)
return $ FileLock fd (Posix.Unlock, AbsoluteSeek, 0, 0)
where
mode =
Just $ Posix.unionFileModes Posix.ownerReadMode Posix.ownerWriteMode
om = case t of
ReadLock -> Posix.ReadOnly
WriteLock -> Posix.WriteOnly
req = case t of
ReadLock -> Posix.ReadLock
WriteLock -> Posix.WriteLock
-- | Release a lock
unlock :: (MonadIO m) => FileLock -> m ()
unlock (FileLock fd lck) = liftIO $ do
Posix.setLock fd lck
Posix.closeFd fd
| singpolyma/posix-filelock-haskell | System/Posix/FileLock.hs | isc | 1,436 | 2 | 11 | 243 | 445 | 245 | 200 | 28 | 3 |
{
module Lexer (
Token(..),
scanTokens
) where
import Syntax
}
%wrapper "basic"
$digit = 0-9
$alpha = [a-zA-Z]
$eol = [\n]
$ordinal = first | second | third | fourth | fifth | sixth | seventh | eighth | ninth | tenth | eleventh | twelfth | thirteenth | fourteenth | fifteenth | sixteenth
tokens :-
'Let the record show' { \s -> TokenPrint }
'shall be' { \s -> TokenAssignment }
'and the portion' { \s -> TokenAddition }
'less the portion' { \s -> TokenSubtraction }
'distributed evenly among' { \s -> TokenDivision }
'apportioned evenly to each of' { \s -> TokenMultiplication }
'The party of the '$ordinal'part' { \s -> TokenDeclaration }
'hereafter known as' { \s -> TokenAlias }
with { \s -> TokenConcatenation }
'in the case of' { \s -> TokenIf }
being { \s -> TokenCheckEq }
surpassing { \s -> TokenCheckGt }
not { \s -> TokenNot }
'pursuant to' { \s -> TokenCall }
'This section grants the value' { \s -> TokenReturn }
'Given that' { \s -> TokenTry }
'Nonwithstanding the afformentioned' { \s -> TokenCatch }
$digit { \s -> TokenLiteralInt }
$digit+(\.$digit+)? { \s -> TokenLiteralFloat }
[\'][$alpha$white]*[\'] { \s -> TokenLiteralString }
[\.$eol] { \s -> TokenStatementEnd }
True { \s -> TokenTrue }
False { \s -> TokenFalse }
$alpha+ { \s -> TokenVariableName }
data Token
= TokenPrint
| TokenAssignment
| TokenAddition
| TokenSubtraction
| TokenDivision
| TokenMultiplication
| TokenConcatenation
| TokenIf
| TokenCheckEq
| TokenCheckGt
| TokenNot
| TokenCall
| TokenReturn
| TokenTry
| TokenCatch
| TokenLiteralInt
| TokenLiteralFloat
| TokenLiteralString
| TokenStatementEnd
| TokenTrue
| TokenFalse
| TokenVariableName
deriving (Eq, Show)
scanTokens :: String -> [Token]
| JohnKossa/Contractual-C | Lexer.hs | mit | 2,280 | 18 | 8 | 879 | 273 | 232 | 41 | -1 | -1 |
import Data.List
import Data.Char
import System.IO
import System.Environment
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Map.Strict ( Map )
import qualified Data.Text as Text
import Data.Text ( Text )
import Data.Either (partitionEithers)
import Data.Ord (comparing)
import IgrepCashbook2
-- general functions
useTextFunc :: (Text -> Text) -> String -> String
useTextFunc f s = Text.unpack $ f $ Text.pack s
justifyRight :: Int -> Char -> String -> String
justifyRight i c s = useTextFunc ( Text.justifyRight i c ) s
justifyLeft :: Int -> Char -> String -> String
justifyLeft i c s = useTextFunc ( Text.justifyLeft i c ) s
--
warnErrors :: String -> [String] -> IO ()
warnErrors path es = forM_ es $ (\e -> do
hPutStrLn stderr $ ( "[WARNING] " ++ e ++ " of " ++ path ++ ". OMMITED!" ))
incomesAndExpenditures :: [CashbookLine] -> ([CashbookLine], [CashbookLine])
incomesAndExpenditures = partition isIncome
type Summary = Map String Int
summarizeItems :: [CashbookLine] -> Summary
summarizeItems is =
Map.fromListWith (+) $ map (\i -> (getGroup i, getPrice i) ) is
digit :: Int -> Int
digit = length . show
formatSummary :: Int -> Int -> Summary -> String
formatSummary l d s = concatMap f $ sortBy ( comparing snd ) $ Map.toList s
where
f (g, i) = formatSumItem l d g i
formatSumItem :: Int -> Int -> String -> Int -> String
formatSumItem l d g i =
justifyLeft jl ' ' g ++ justifyRight d ' ' ( show i ) ++ "\n"
where
jl = l - ( length $ filter ( not . is8bitChar ) g )
is8bitChar :: Char -> Bool
is8bitChar = ( < 255 ) . ord
main :: IO ()
main = do
args <- getArgs
items <- forM args (\a -> do
contents <- readFile a
let items = parseWithoutDate contents
let ( errors, items' ) = partitionEithers items
warnErrors a errors
return items' )
let ( inItems, exItems ) = incomesAndExpenditures $ concat items
let exSummary = summarizeItems exItems
let inSummary = summarizeItems inItems
let exSum = sum $ Map.elems exSummary
let inSum = sum $ Map.elems inSummary
let wholeSum = inSum - exSum
let sumDigit = max (digit exSum) (digit inSum)
let groupLen = 8 -- fixed so far
putStrLn "## EXPENDITURES ##"
putStr $ formatSummary groupLen sumDigit exSummary
putStr $ formatSumItem groupLen sumDigit "小計" exSum
putStr "\n"
putStrLn "#### INCOMES ####"
putStr $ formatSummary groupLen sumDigit inSummary
putStr $ formatSumItem groupLen sumDigit "小計" inSum
putStr "\n"
putStr $ formatSumItem groupLen sumDigit "合計" wholeSum
| igrep/igrep-cashbook | hs/sum.hs | mit | 2,566 | 0 | 16 | 536 | 939 | 471 | 468 | 64 | 1 |
-- |
-- Module: Math.NumberTheory.Primes.FactorisationTests
-- Copyright: (c) 2017 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <[email protected]>
-- Stability: Provisional
--
-- Tests for Math.NumberTheory.Primes.Factorisation
--
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Math.NumberTheory.Primes.FactorisationTests
( testSuite
) where
import Test.Tasty
import Test.Tasty.HUnit
import Control.Monad (zipWithM_)
import Data.List (nub, sort)
import Math.NumberTheory.Primes.Factorisation
import Math.NumberTheory.Primes.Testing
import Math.NumberTheory.TestUtils
specialCases :: [(Integer, [(Integer, Int)])]
specialCases =
[ (4181339589500970917,[(15034813,1),(278110515209,1)])
, (4181339589500970918,[(2,1),(3,2),(7,1),(2595773,1),(12784336241,1)])
, (2227144715990344929,[(3,1),(317,1),(17381911,1),(134731889,1)])
, (10489674846272137811130167281,[(1312601,1),(9555017,1),(836368815445393,1)])
, (10489674846272137811130167282,[(2,1),(17,1),(577,1),(3863,1),(179347163,1),(771770327021,1)])
, (10489674846272137811130167283,[(3,1),(7,1),(4634410717,1),(107782489838601619,1)])
, (10489674846272137811130167287,[(4122913189601,1),(2544238591472087,1)])
, (6293073306208101456461600748,[(2,2),(3,1),(1613,1),(69973339,1),(4646378436563447,1)])
, (6293073306208101456461600749,[(7,1),(103,1),(4726591,1),(1846628365511484259,1)])
, (6293073306208101456461600750,[(2,1),(5,3),(239,1),(34422804769,1),(3059698456333,1)])
, (6293073306208101456461600751,[(3,1),(13523,1),(1032679,1),(150211485989006401,1)])
, (6293073306208101456461600753,[(19391,1),(372473053129,1),(871300023127,1)])
, (6293073306208101456461600754,[(2,1),(3,2),(11,1),(13,1),(71,1),(2311,1),(22859,1),(7798621,1),(83583569,1)])
, (11999991291828813663324577057,[(14381453,1),(10088205181,1),(82711187849,1)])
, (11999991291828813663324577062,[(2,1),(3,1),(7,1),(3769,1),(634819511,1),(119413997449529,1)])
, (16757651897802863152387219654541878160,[(2,4),(5,1),(12323,1),(1424513,1),(6205871923,1),(1922815011093901,1)])
, (16757651897802863152387219654541878162,[(2,1),(29,1),(78173,1),(401529283,1),(1995634649,1),(4612433663779,1)])
, (16757651897802863152387219654541878163,[(11,1),(31,1),(112160981904206269,1),(438144115295608147,1)])
, (16757651897802863152387219654541878166,[(2,1),(23,1),(277,1),(505353699591289,1),(2602436338718275457,1)])
]
lazyCases :: [(Integer, [(Integer, Int)])]
lazyCases =
[ ( 14145130711
* 10000000000000000000000000000000000000121
* 100000000000000000000000000000000000000000000000447
, [(14145130711, 1)]
)
]
factoriseProperty1 :: Assertion
factoriseProperty1 = assertEqual "0" [] (factorise 1)
factoriseProperty2 :: Positive Integer -> Bool
factoriseProperty2 (Positive n) = (-1, 1) : factorise n == factorise (negate n)
factoriseProperty3 :: Positive Integer -> Bool
factoriseProperty3 (Positive n) = all (isPrime . fst) (factorise n)
factoriseProperty4 :: Positive Integer -> Bool
factoriseProperty4 (Positive n) = bases == nub (sort bases)
where
bases = map fst $ factorise n
factoriseProperty5 :: Positive Integer -> Bool
factoriseProperty5 (Positive n) = product (map (uncurry (^)) (factorise n)) == n
factoriseProperty6 :: (Integer, [(Integer, Int)]) -> Assertion
factoriseProperty6 (n, fs) = assertEqual (show n) (sort fs) (sort (factorise n))
factoriseProperty7 :: (Integer, [(Integer, Int)]) -> Assertion
factoriseProperty7 (n, fs) = zipWithM_ (assertEqual (show n)) fs (factorise n)
testSuite :: TestTree
testSuite = testGroup "Factorisation"
[ testGroup "factorise" $
[ testCase "0" factoriseProperty1
, testSmallAndQuick "negate" factoriseProperty2
, testSmallAndQuick "bases are prime" factoriseProperty3
, testSmallAndQuick "bases are ordered and distinct" factoriseProperty4
, testSmallAndQuick "factorback" factoriseProperty5
] ++
map (\x -> testCase ("special case " ++ show (fst x)) (factoriseProperty6 x)) specialCases
++
map (\x -> testCase ("laziness " ++ show (fst x)) (factoriseProperty7 x)) lazyCases
]
| cfredric/arithmoi | test-suite/Math/NumberTheory/Primes/FactorisationTests.hs | mit | 4,213 | 0 | 17 | 547 | 1,623 | 1,003 | 620 | 64 | 1 |
-- | procedural level generation (from https://jeremykun.com/2012/07/29/the-cellular-automaton-method-for-cave-generation/)
module Cave where
import CellularAutomata2D
import GUI
main :: IO ()
main = randomSpace (100, 100) [True, False] >>= runCellularAutomata2D caveRule >> return ()
caveRule :: Rule Bool
caveRule = makeTotalMoorRule [6..8] [3..8]
smoothingRule :: Rule Bool
smoothingRule = makeTotalMoorRule [5..8] [5..8]
| orion-42/cellular-automata-2d | Cave.hs | mit | 429 | 0 | 8 | 53 | 115 | 63 | 52 | 9 | 1 |
import Data.List (findIndex)
-- combination nCr
comb :: Integral a=>a->a->a
comb n r | d>0 = (s n (r-d))`div`(s (r-d) (r-d-1))
| otherwise= (s n r) `div`(s r (r-1)) where
s = subpower
d = 2*r-n
-- i * i-1 * ... * i-j+i
subpower :: Integral a=>a->a->a
subpower i j = product [i,i-1..i-j+1]
-- max: comb n (n+1)`div`2
-- Data.List.findIndex (>1000000) [comb i ((i+1)`div`2)|i<-[1..]]
-- Just 22
answer n = (length. filter (>1000000)) [comb i j|i<-[23..n],j<-[1..i]]
main = print $ answer 100
-- 4075
| yuto-matsum/contest-util-hs | src/Euler/053.hs | mit | 525 | 0 | 11 | 112 | 286 | 152 | 134 | 10 | 1 |
{-# LANGUAGE StandaloneDeriving, FlexibleInstances #-}
module Derivation where
import qualified Prelude as P
import Lib
import qualified Data.List as L
c2hl :: List a -> [a]
c2hl Nil = []
c2hl (Cons x xs) = x : (c2hl xs)
deriving instance (P.Eq Cand)
deriving instance (P.Ord Cand)
deriving instance (P.Show Cand)
deriving instance (P.Show Bool)
deriving instance (P.Eq Bool)
deriving instance (P.Show Nat)
deriving instance (P.Eq Nat)
deriving instance (P.Ord Nat)
deriving instance (P.Show a, P.Show b) => P.Show (Sum a b)
deriving instance (P.Show a, P.Show b) => P.Show (Prod a b)
deriving instance (P.Read Cand)
deriving instance (P.Show a) => P.Show (List a)
deriving instance (P.Show Comparison)
deriving instance (P.Show Sumbool)
-- deriving instance (P.Show a) => P.Show (Sumor a)
deriving instance (P.Show Positive)
deriving instance (P.Show Z)
haskInt :: Nat -> P.Int
haskInt O = 0
haskInt (S p) = 1 P.+ haskInt p
haskPos :: Positive -> P.Int
haskPos XH = 1
haskPos p = haskHelp p 1 where
haskHelp XH p2 = p2
haskHelp (XO r) p2 = haskHelp r (2 P.* p2)
haskHelp (XI r) p2 = p2 P.+ haskHelp r (2 P.* p2)
haskZ :: Z -> P.Int
haskZ Z0 = 0
haskZ (Zpos p) = haskPos p
haskZ (Zneg p) = -1 P.* haskPos p
instance P.Show (PathT Cand) where
show (UnitT x y) = P.show x P.++ " --> " P.++ P.show y
show (ConsT x _ _ p) = P.show x P.++ " --> " P.++ P.show p
-- deriving instance (P.Show PathT)
instance P.Show (SigT (Cand -> Bool) (SigT (Count Cand) ())) where
show (ExistT f (ExistT v _)) = P.show v
show_winner :: (Wins_type Cand)-> Cand -> [Cand] -> P.String
show_winner g x [] = ""
show_winner g x (y : ys) =
case (g y) of
(ExistT u (Pair v (ExistT f _))) ->
" for " P.++ P.show y P.++ ": " P.++ "path " P.++ P.show v P.++ " of strenght " P.++ P.show (haskZ u) P.++ ", " P.++
P.show (1 P.+ haskZ u) P.++ "-" P.++ "coclosed set: " P.++ P.show (P.filter (\(xx, yy) -> f (Pair xx yy) P.== True) [(a, b) | a <- (c2hl cand_all), b <- (c2hl cand_all)])
P.++ (if ys P.== [] then "" else "\n") P.++ show_winner g x ys
show_loser :: (Loses_type Cand)-> Cand -> P.String
show_loser g x =
case g of
(ExistT u (ExistT c (Pair p (ExistT f _)))) ->
" exists " P.++ P.show c P.++ ": " P.++ "path " P.++ P.show p P.++ " of strength " P.++ P.show (haskZ u) P.++ ", " P.++
P.show (haskZ u) P.++ "-" P.++ "coclosed set: " P.++ P.show (P.filter (\(xx, yy) -> f (Pair xx yy) P.== True) [(a, b) | a <- (c2hl cand_all), b <- (c2hl cand_all)])
show_cand :: (Cand -> Sum (Wins_type Cand) (Loses_type Cand)) -> Cand -> P.String
show_cand f x =
case (f x) of
Inl g -> "winning: " P.++ P.show x P.++ "\n" P.++ show_winner g x (P.filter (\y -> y P./= x) (c2hl cand_all))
Inr h -> "losing: " P.++ P.show x P.++ "\n" P.++ show_loser h x
show_ballot :: (Ballot Cand)-> P.String
show_ballot f = P.unwords (P.map (\x -> P.show x P.++ P.show (haskInt (f x))) (c2hl cand_all))
show_marg :: (Cand -> Cand -> Z) -> P.String
show_marg m = "[" P.++ P.unwords (P.map (\(x, y) -> P.show x P.++ P.show y P.++ ":" P.++ P.show (haskZ (m x y))) [(a, b) | a <- (c2hl cand_all), b <- (c2hl cand_all), b P.> a]) P.++ "]"
bool_b :: List (Ballot Cand)-> P.Bool
bool_b Nil = P.True
bool_b _ = P.False
line :: P.String
line = '-' : line
show_list_inv_ballot Nil = "[]"
show_list_inv_ballot (Cons b Nil) = "[" P.++ show_ballot b P.++ "]"
show_list_inv_ballot (Cons b (Cons _ _)) = "[" P.++ show_ballot b P.++ ",..]"
instance P.Show (Count Cand) where
show (Ax ls m) = ""
show (Cvalid u us m nm inbs c) = P.show c P.++ underline (show_cv (Cvalid u us m nm inbs c)) P.++ "\n"
where
show_cv (Cvalid u us m nm inbs c) = "V: [" P.++ show_ballot u P.++
(if bool_b us P.== P.True then "]" else ",..]") P.++ ", I: " P.++
show_list_inv_ballot inbs P.++ ", M: " P.++ show_marg m
underline s = s P.++ "\n" P.++ (P.take (P.length s) line)
show (Cinvalid u us m inbs c) = P.show c P.++ underline (show_ci (Cinvalid u us m inbs c)) P.++ "\n"
where
show_ci (Cinvalid u us m inbs c) = "V: [" P.++ show_ballot u P.++
(if bool_b us P.== P.True then "]" else ",..]") P.++ ", I: " P.++ show_list_inv_ballot inbs P.++
", M: " P.++ show_marg m
underline s = s P.++ "\n" P.++ (P.take (P.length s) line)
show (Fin m ls p f c) = P.show c P.++ (underline (show_fin (Fin m ls p f c))) P.++ "\n" P.++
(P.unlines P.$ P.map (show_cand f) (c2hl cand_all))
where
show_fin (Fin m ls p f c) = "V: [], I: " P.++ show_list_inv_ballot ls P.++ ", M: " P.++ show_marg m
underline s = s P.++ "\n" P.++ (P.take (P.length s) line)
| mukeshtiwari/formalized-voting | SchulzeCounting/Derivation.hs | mit | 4,639 | 1 | 22 | 1,062 | 2,479 | 1,247 | 1,232 | 89 | 3 |
{-# htermination (last :: (List a) -> a) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
last :: (List a) -> a;
last (Cons x Nil) = x;
last (Cons vv xs) = last xs;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/last_1.hs | mit | 221 | 0 | 8 | 56 | 90 | 50 | 40 | 6 | 1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.PluginArray
(item, item_, itemUnsafe, itemUnchecked, namedItem, namedItem_,
namedItemUnsafe, namedItemUnchecked, refresh, getLength,
PluginArray(..), gTypePluginArray)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.item Mozilla PluginArray.item documentation>
item :: (MonadDOM m) => PluginArray -> Word -> m (Maybe Plugin)
item self index
= liftDOM ((self ^. jsf "item" [toJSVal index]) >>= fromJSVal)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.item Mozilla PluginArray.item documentation>
item_ :: (MonadDOM m) => PluginArray -> Word -> m ()
item_ self index
= liftDOM (void (self ^. jsf "item" [toJSVal index]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.item Mozilla PluginArray.item documentation>
itemUnsafe ::
(MonadDOM m, HasCallStack) => PluginArray -> Word -> m Plugin
itemUnsafe self index
= liftDOM
(((self ^. jsf "item" [toJSVal index]) >>= fromJSVal) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.item Mozilla PluginArray.item documentation>
itemUnchecked :: (MonadDOM m) => PluginArray -> Word -> m Plugin
itemUnchecked self index
= liftDOM
((self ^. jsf "item" [toJSVal index]) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.namedItem Mozilla PluginArray.namedItem documentation>
namedItem ::
(MonadDOM m, ToJSString name) =>
PluginArray -> name -> m (Maybe Plugin)
namedItem self name = liftDOM ((self ! name) >>= fromJSVal)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.namedItem Mozilla PluginArray.namedItem documentation>
namedItem_ ::
(MonadDOM m, ToJSString name) => PluginArray -> name -> m ()
namedItem_ self name = liftDOM (void (self ! name))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.namedItem Mozilla PluginArray.namedItem documentation>
namedItemUnsafe ::
(MonadDOM m, ToJSString name, HasCallStack) =>
PluginArray -> name -> m Plugin
namedItemUnsafe self name
= liftDOM
(((self ! name) >>= fromJSVal) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.namedItem Mozilla PluginArray.namedItem documentation>
namedItemUnchecked ::
(MonadDOM m, ToJSString name) => PluginArray -> name -> m Plugin
namedItemUnchecked self name
= liftDOM ((self ! name) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.refresh Mozilla PluginArray.refresh documentation>
refresh :: (MonadDOM m) => PluginArray -> Bool -> m ()
refresh self reload
= liftDOM (void (self ^. jsf "refresh" [toJSVal reload]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PluginArray.length Mozilla PluginArray.length documentation>
getLength :: (MonadDOM m) => PluginArray -> m Word
getLength self
= liftDOM (round <$> ((self ^. js "length") >>= valToNumber))
| ghcjs/jsaddle-dom | src/JSDOM/Generated/PluginArray.hs | mit | 4,043 | 0 | 14 | 618 | 998 | 565 | 433 | -1 | -1 |
-----------------------------------------------------------------------------
-- Copyright : (c) Hanzhong Xu, Meng Meng 2016,
-- License : MIT License
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
-- {-# LANGUAGE Arrows #-}
module Main where
import Control.Arrow
import Control.Monad
import Data.SF
import Data.SF.IOSF
import Data.Maybe
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.STM.TChan
import Data.IORef
{-
psMV = newMVar ()
safePutStrLn :: String -> IO()
safePutStrLn s = do
m <- psMV
takeMVar m
putStrLn s
putMVar m ()
-}
delayTChan :: Int -> TChan Int -> IO ()
delayTChan x ch = do
threadDelay 1000000
atomically $ writeTChan ch x
delayTChan x ch
in2ret :: SF Int (Maybe Int)
in2ret = simpleSF (\s x -> (s + x, Just (s + x))) 0
main = do
tc <- newBroadcastTChanIO
tf <- newThreadSF in2ret
ret <- tf tc
tc1 <- newBroadcastTChanIO
tf1 <- newThreadSF in2ret
ret1 <- tf1 tc1
forkIO $ outputTChan ret (putStrLn.show)
forkIO $ outputTChan ret1 (putStrLn.show)
forkIO $ delayTChan 1 tc
forkIO $ delayTChan 10000 tc1
getContents >>= putStrLn
| PseudoPower/AFSM | draft/testIOSF.hs | mit | 1,274 | 0 | 11 | 242 | 300 | 153 | 147 | 29 | 1 |
module SolutionsTo50
( solutionsTo50
) where
import System.IO
import Data.List
import Control.Applicative
import MyMath.Fibonacci
import Util.Misc (isPalindromic)
import Data.Char
solutionsTo50 :: Int -> IO ()
solutionsTo50 n = do
putStr $ "The solution to problem " ++ show n ++ " is "
solutionsTo50_ n
solutionsTo50_ :: Int -> IO ()
solutionsTo50_ n
| n == 1 = solution1
| n == 2 = solution2
| n == 3 = solution3
| n == 4 = solution4
| n == 5 = solution5
| n == 6 = solution6
| n == 8 = solution8
| n == 13 = solution13
| n == 18 = solution18
| otherwise = print "solution not present in program"
solution1 = putStrLn $ show answer
where answer = sum $ union [3,6..999] [5,10..999]
solution2 = putStrLn $ show answer
where answer = sum . filter even $ takeWhile (<= 4000000) fibs
solution3 = putStrLn $ show answer
where answer = let primes = 2 : filter (null . tail . primeFactors) [3,5..]
primeFactors n = factor n primes
where factor n (p:ps)
| p*p > n = [n]
| n `mod` p == 0 = p : factor (n `div` p) (p:ps)
| otherwise = factor n ps
in maximum $ primeFactors 600851475143
solution4 = putStrLn $ show answer
where answer = maximum [x | y<-[999,998..100], z<-[999,998..y], let x = y*z, isPalindromic x]
solution5 = putStrLn $ show answer
where answer = foldr1 lcm [1..20]
solution6 = putStrLn $ show answer
where answer = sumSquare - squareSums
where squareSums = foldl (\s i-> s + i^2) 0 [1..100]
sumSquare = (^2) $ sum [1..100]
solution8 = putStrLn $ show answer
where answer = getAdjacentSums digitArr 13
where getAdjacentSums [] _ = 0
getAdjacentSums xss@(x:xs) y
| len < y = 0
| len == y = product xss
| otherwise = max adjSum $ getAdjacentSums xs y
where len = length xss
adjSum = product $ take y xss
digitArr = map digitToInt digitString
solution13 = do
numbers <- fmap ( map read . lines ) (readFile "p13numbers.txt")
putStrLn . take 10 . show . sum $ numbers
solution18 = do
a <- answer
putStrLn $ show a
where answer = head . foldr1 solve' . parse <$> readFile "triangle.txt"
where parse t = map (map read . words) $ lines t
solve' [] [z] = [z]
solve' (x:xs) (y:ys:yss) = x + max y ys : solve' xs (ys:yss)
digitString = "73167176531330624919225119674426574742355349194934"
++ "96983520312774506326239578318016984801869478851843"
++ "85861560789112949495459501737958331952853208805511"
++ "12540698747158523863050715693290963295227443043557"
++ "66896648950445244523161731856403098711121722383113"
++ "62229893423380308135336276614282806444486645238749"
++ "30358907296290491560440772390713810515859307960866"
++ "70172427121883998797908792274921901699720888093776"
++ "65727333001053367881220235421809751254540594752243"
++ "52584907711670556013604839586446706324415722155397"
++ "53697817977846174064955149290862569321978468622482"
++ "83972241375657056057490261407972968652414535100474"
++ "82166370484403199890008895243450658541227588666881"
++ "16427171479924442928230863465674813919123162824586"
++ "17866458359124566529476545682848912883142607690042"
++ "24219022671055626321111109370544217506941658960408"
++ "07198403850962455444362981230987879927244284909188"
++ "84580156166097919133875499200524063689912560717606"
++ "05886116467109405077541002256983155200055935729725"
++ "71636269561882670428252483600823257530420752963450"
| james-ralston/project-euler | src/SolutionsTo50.hs | mit | 4,094 | 0 | 23 | 1,290 | 1,102 | 553 | 549 | 84 | 2 |
module SudokuSorted where
import Data.List
numlist = [1..9]
allp (i,j) = concat [block,line,col]
where block = [(i + dx - mod i 3,j + dy - mod j 3) |dx<-[0..2],dy<-[0..2]]
line = [(i,dy)| dy <- [0..9]]
col = [(dx,j)| dx<-[0..9]]
get pos all = (map head).group.sort $ [ k | (xy,k)<- all, elem xy $ allp pos ]
refresh pos k all = [ if (not $ elem xy $ allp pos) || elem k ks then (xy,ks) else (xy,k:ks) | (xy,ks) <- all]
solve ([],taken) = [taken]
solve (empty,taken) = concatMap solve [ (refresh pos i rst,(pos,i):taken) | i<-avail]
where (pos,used):rst = sortBy (\a b -> compare (length.snd $ b) (length.snd $ a)) empty
avail = [ i |i<-numlist, not $ elem i used]
solveStr :: [Int] -> [Int]
solveStr = (getout 0). head . solve . fill . (getin 0)
fill (empty,taken) = ([(pos,get pos taken) | pos <- empty],taken)
getin i [] = ([],[])
getin i (x:xs) = if x/=0 then (empty,(pos,x):taken)
else (pos:empty,taken)
where (empty,taken) = getin (i+1) xs
pos = (div i 9, mod i 9)
getout 81 taken = []
getout i taken = k:(getout (i+1) taken)
where pos = (div i 9, mod i 9)
k = head [ k|(xy,k)<-taken,xy==pos]
| ztuowen/sudoku | SudokuSorted.hs | mit | 1,193 | 0 | 13 | 302 | 769 | 421 | 348 | 25 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Unison.Symbol where
import Data.Text (Text)
import GHC.Generics
import Unison.Var (Var(..))
import qualified Data.Set as Set
import qualified Data.Text as Text
data Symbol = Symbol !Word Text deriving (Generic)
freshId :: Symbol -> Word
freshId (Symbol id _) = id
instance Var Symbol where
rename n (Symbol id _) = Symbol id n
name (Symbol _ n) = n
named n = Symbol 0 n
clear (Symbol id n) = Symbol id n
qualifiedName s =
if freshId s /= 0 then name s `Text.append` "" `Text.append` (Text.pack (show (freshId s)))
else name s
freshIn vs s | Set.null vs || Set.notMember s vs = s -- already fresh!
freshIn vs s@(Symbol i n) = case Set.elemAt (Set.size vs - 1) vs of
Symbol i2 _ -> if i > i2 then s else Symbol (i2+1) n
freshenId id (Symbol _ n) = Symbol id n
instance Eq Symbol where
Symbol id1 name1 == Symbol id2 name2 = id1 == id2 && name1 == name2
instance Ord Symbol where
Symbol id1 name1 `compare` Symbol id2 name2 = (id1,name1) `compare` (id2,name2)
instance Show Symbol where
show (Symbol 0 n) = Text.unpack n
show (Symbol id n) = Text.unpack n ++ show id
symbol :: Text -> Symbol
symbol n = Symbol 0 n
| paulp/unison | parser-typechecker/src/Unison/Symbol.hs | mit | 1,261 | 0 | 13 | 266 | 548 | 283 | 265 | 35 | 1 |
{-# LANGUAGE CPP #-}
module Main where
import Prelude hiding (div,id,span)
import Transient.Base
#ifdef ghcjs_HOST_OS
hiding ( option)
#endif
import GHCJS.HPlay.View
#ifdef ghcjs_HOST_OS
hiding (map)
#else
hiding (map, option)
#endif
import Transient.Move
import Transient.Indeterminism
import Control.Applicative
import Control.Monad
import Data.Typeable
import Data.IORef
import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class
-- Show the composability of transient web aplications
-- with three examples composed together, each one is a widget that execute
-- code in the browser AND the server.
main = simpleWebApp 8080 $ demo <|> demo2 <|> counters
demo= do
name <- local . render $ do
rawHtml $ do
hr
p "this snippet captures the essence of this demonstration"
p $ do
span "it's a blend of server and browser code in a "
span $ b "composable"
span " piece"
div ! id (fs "fibs") $ i "Fibonacci numbers should appear here"
local . render $ wlink () (p " stream fibonacci numbers")
-- stream fibonacci
r <- atRemote $ do
let fibs= 0 : 1 : zipWith (+) fibs (tail fibs) :: [Int] -- fibonacci numb. definition
r <- local . threads 1 . choose $ take 10 fibs
lliftIO $ print r
lliftIO $ threadDelay 1000000
return r
local . render . at (fs "#fibs") Append $ rawHtml $ (h2 r)
demo2= do
name <- local . render $ do
rawHtml $ do
hr
br;br
p "In this example you enter your name and the server will salute you"
br
-- inputString (Just "Your name") `fire` OnKeyUp -- send once a char is entered
inputString Nothing ! atr "placeholder" (fs "enter your name") `fire` OnKeyUp
<++ br -- new line
r <- atRemote $ lliftIO $ print (name ++ " calling") >> return ("Hi " ++ name)
local . render . rawHtml $ do
p " returned"
h2 r
fs= toJSString
counters= do
local . render . rawHtml $ do
hr
p "To demonstrate the use of teleport, widgets, interactive streaming"
p "and composability in a web application."
br
p "This is one of the most complicated interactions: how to control a stream in the server"
p "by means of a web interface without loosing composability."
br
p "in this example, events flow from the server to the browser (a counter) and back from"
p "the browser to the server (initiating and cancelling the counters)"
-- server <- local $ getSData <|> error "no server???"
counter <|> counter
where
counter = do
op <- startOrCancel
teleport -- translates the computation to the server
r <- local $ case op of
"start" -> killChilds >> stream
"cancel" -> killChilds >> stop
teleport -- back to the browser again
local $ render $ rawHtml $ h1 r
-- generates a sequence of numbers
stream= do
counter <- liftIO $ newIORef (0 :: Int)
waitEvents $ do
n <- atomicModifyIORef counter $ \r -> (r +1,r)
threadDelay 1000000
putStr "generating: " >> print n
return n
startOrCancel :: Cloud String
startOrCancel= local $ render $ (inputSubmit "start" `fire` OnClick)
<|> (inputSubmit "cancel" `fire` OnClick)
<++ br
| geraldus/transient-universe | examples/webapp.hs | mit | 3,749 | 0 | 18 | 1,345 | 808 | 395 | 413 | 78 | 2 |
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module Math.Symbolic.Expression where
import Data.Word
import Data.Maybe
import Data.List
import Data.Ratio
import Data.String
import Data.Monoid
import Data.Generics (Typeable, Data)
import Control.Arrow
import qualified Data.Text as T
import Data.Text (Text)
data Math a = Numeric a
| Sym Text
| Op Text [Math a]
deriving (Eq, Typeable, Data)
percedende :: Text -> Int
percedende "+" = 1
percedende "-" = 1
percedende "*" = 2
percedende "/" = 2
percedende "^" = 3
percedende _ = 3
instance (Show a, Fractional a, Real a, Ord a) => Show (Math a) where
show = showMath . toTree
toTree :: (Show a, Real a, Fractional a, Ord a) => Math a -> Math a
toTree (Op "*" xs) = foldr1 (*) $ toTree <$> xs
toTree (Op "+" xs) = foldl1 sumTree $ toTree <$> xs
where
sumTree y (Op "*" [Numeric (-1), x]) = Op "-" [y, x]
sumTree y (Op "*" (Numeric x:xs)) | x < 0 = Op "-" [y, Op "*" $ (Numeric $ abs x):xs]
sumTree y (Numeric x) | x < 0 = Op "-" [y, Numeric $ abs x]
sumTree x y = x + y
toTree (Op op x) = Op op $ toTree <$> x
toTree x = x
parens :: (Show a, Fractional a, Ord a) => Int -> Math a -> String
parens p (Op "*" [Numeric (-1), x]) | 1 > p = "-(" <> showMath x <> ")"
-- | otherwise = "(" <> showMath x <> ")"
parens p x@(Op op _) | percedende op < p = "(" <> showMath x <> ")"
parens _ (Numeric x) | x < 0 = "-" <> show (abs x)
parens _ x = showMath x
isNeg :: (Show a, Fractional a, Ord a) => Math a -> Bool
isNeg (Op "*" (Numeric (-1):_)) = True
isNeg (Numeric x) = x < 0
isNeg _ = False
getNeg :: (Show a, Fractional a, Ord a) => Math a -> Math a
getNeg (Op "*" [_, x]) = x
getNeg x = x
sig :: (Show a, Fractional a, Ord a) => Math a -> String
sig (Op "*" (Numeric (-1):_)) = "-"
sig (Numeric x) | x < 0 = "-"
sig _ = ""
showMath :: (Show a, Fractional a, Ord a) => Math a -> String
showMath (Op op [x]) = T.unpack op <> "(" <> showMath x <> ")"
showMath (Op op xs) = intercalate (T.unpack op) $ parens (percedende op) <$> xs
showMath (Sym x) = T.unpack x
showMath (Numeric x) = show $ abs x
ifEq :: Ordering -> Ordering -> Ordering
ifEq EQ a = a
ifEq a _ = a
instance (Ord a) => Ord (Math a) where
compare (Numeric x) (Numeric y) = compare x y
compare (Numeric _) _ = LT
compare _ (Numeric _) = GT
compare (Op x [x']) (Op y [y']) = compare y x `ifEq` compare x' y'
compare (Op x xs) (Op y ys) = compare y x `ifEq` compare (sort ys) (sort xs)
compare Op{} _ = LT
compare _ Op{} = GT
compare (Sym x) (Sym y) = compare x y
instance (Ord a, Real a, Fractional a) => Num (Math a) where
x + y = Op "+" [x, y]
x - y = Op "+" [x, Numeric (-1) * y]
x * y = Op "*" [x, y]
abs x = Op "abs" [x]
negate x = Numeric (-1) * x
signum x = Op "signum" [x]
fromInteger x = Numeric (fromInteger x)
instance (Ord a, Real a, Fractional a) => Fractional (Math a) where
x / y = Op "/" [x, y]
fromRational x = Numeric (fromRational x)
instance (Ord a, Real a, Fractional a) => Floating (Math a) where
x ** y = Op "^" [x, y]
pi = Sym "pi"
exp x = Sym "e" ** x
sqrt x = Op "sqrt" [x]
log x = Op "log" [x]
logBase x y = Op "logBase" [x, y]
sin x = Op "sin" [x]
cos x = Op "cos" [x]
tan x = Op "tan" [x]
asin x = Op "asin" [x]
acos x = Op "acos" [x]
atan x = Op "atan" [x]
sinh x = Op "sinh" [x]
cosh x = Op "cosh" [x]
tanh x = Op "tanh" [x]
asinh x = Op "asinh" [x]
acosh x = Op "acosh" [x]
atanh x = Op "atanh" [x]
| NatureShade/SymbolicHaskell | src/Math/Symbolic/Expression.hs | mit | 3,616 | 0 | 14 | 1,017 | 1,979 | 1,001 | 978 | 97 | 4 |
module Main where
import Data.List
newline str = str ++ "\n"
main =
interact (newline . show . length . words)
| dicander/progp_haskell | word_count_simple.hs | mit | 117 | 0 | 9 | 27 | 44 | 24 | 20 | 5 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
import qualified Bonlang as B
import Bonlang.Lang
import Bonlang.Lexer
import Control.Monad.Except
import Data.Aeson
import Data.Functor.Identity
import Data.Maybe (fromJust)
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import qualified Data.Yaml as Y
import GHC.Generics
import System.Directory
import System.FilePath
import System.IO
import Test.Tasty
import Test.Tasty.HUnit
import Text.Parsec
import Text.ParserCombinators.Parsec
data TestFile = TestFile { meta :: T.Text
, code :: T.Text
, name :: String
}
deriving (Show)
data TestOuput = TestOuput { output :: String
}
deriving (Generic, Show)
instance FromJSON TestOuput
instance ToJSON TestOuput
main :: IO ()
main = tests >>= defaultMain
tests :: IO TestTree
tests = testGroup "Bonlang" <$> sequence [parsing, testExpectations]
--------------------------------------------------------------------------------
-- | Match running each example with the expected output
testExpectations :: IO TestTree
testExpectations = getFiles "test/examples/" >>=
\files -> return $ testGroup "Example tests" $ map exampleFiles files
--------------------------------------------------------------------------------
-- | Parsing test tree
parsing :: IO TestTree
parsing = getFiles "test/parser_tests/" >>=
\files -> return $ testGroup "Parsing tests" $ map testParseFiles files
--------------------------------------------------------------------------------
-- | For an example file, get a test tree
exampleFiles :: FilePath -> TestTree
exampleFiles f = localOption (mkTimeout 1000000) $
testCase ("Example file: " `mappend` f) exampleAssertion
where
exampleAssertion :: Assertion
exampleAssertion = do testFile <- makeTestFile f
case testFile of
Right testF -> runTestFile testF
Left x -> error x
--------------------------------------------------------------------------------
-- | Read an expression
readExpr :: String -> B.ThrowsError B.BonlangValue
readExpr = readOrThrow B.bonlangParser
--------------------------------------------------------------------------------
-- | Read an expression or throw an error
readOrThrow :: (MonadError B.BonlangError m, Stream s Identity t)
=> Parsec s () a -> s -> m a
readOrThrow parser input = case parse parser "bonlang" input of
Left e -> throwError $ B.Parser e
Right x -> return x
--------------------------------------------------------------------------------
-- | Eval a string
evalString :: B.Scope -> String -> IO (Either B.BonlangError B.BonlangValue)
evalString scope expr = runExceptT $ B.liftThrows (readExpr expr)
>>= B.startEval scope
--------------------------------------------------------------------------------
-- | For a TestFile, assert that running it returns the expected output
runTestFile :: TestFile -> Assertion
runTestFile testFile
= do output' <- programOutput
expectedOutput' <- expectedOutput
output' @?= output (fromJust expectedOutput')
where
programOutput
= do (tempFile, tempH) <- createTmpFile
let testInput = B.BonHandle stdin
let testOutput = B.BonHandle tempH
s <- B.primitiveBindings testInput testOutput
d <- evalString s $ (T.unpack . code) testFile
hClose tempH
case d of
Right _ -> readFile tempFile
Left _ -> return $ show d
expectedOutput
= let tioSource = E.encodeUtf8 $ meta testFile in
return $ Y.decode tioSource :: IO (Maybe TestOuput)
--------------------------------------------------------------------------------
-- | For a file path, get a TestFile value
makeTestFile :: FilePath -> IO (Either String TestFile)
makeTestFile f = do fileContents <- T.pack <$> readFile f
case T.splitOn "---" fileContents of
[_, meta', code']
-> return $ Right TestFile { meta = meta'
, code = code'
, name = f
}
_ -> return $ Left "Invalid syntax for example file"
--------------------------------------------------------------------------------
-- | Create a temporary file
createTmpFile :: IO (FilePath, Handle)
createTmpFile = do tmpdir <- getTemporaryDirectory
openTempFile tmpdir ""
--------------------------------------------------------------------------------
-- | For a file name, parse it and assert that it was parsed correctly
testParseFiles :: String -> TestTree
testParseFiles f = localOption (mkTimeout 50000) $
testCase ("Parsing file: " `mappend` f) fileAssertion
where
fileAssertion :: Assertion
fileAssertion = do (_, b) <- parse' f
b @?= True
--------------------------------------------------------------------------------
-- | Parse a file and return a pair of file name and Either
parse' :: String -> IO (String, Bool)
parse' f = parseFromFile bonlangParser f >>= \r -> return (f, parsedCorr r)
where
parsedCorr :: Either ParseError BonlangValue -> Bool
parsedCorr (Left _) = False
parsedCorr (Right _) = True
--------------------------------------------------------------------------------
-- | Get files from a directory
getFiles :: FilePath -> IO [String]
getFiles dir = do files <- getDirectoryContents dir
let filtered = filter (\f -> takeExtension f == ".bl") files
return $ map (dir ++) filtered
| charlydagos/bonlang | test/Spec.hs | mit | 6,488 | 2 | 14 | 2,026 | 1,260 | 653 | 607 | 102 | 2 |
module HasseTree where
import Data.List
type ItemSet = [String] -- an item set is a collection of items, which are identified with strings
type Item = String
-- a node in the Hasse diagram search tree contains an item, a counter for the support of the item set that is
-- constructed by traversing the tree to this item and a pointer to the list of child nodes
data HasseNode = HasseTreeNode Item Int HasseTree | HasseLeafNode Item Int deriving Show
type HasseTree = [HasseNode]
item :: HasseNode -> Item
item (HasseTreeNode itm _ _) = itm
item (HasseLeafNode itm _) = itm
count :: HasseNode -> Int
count (HasseTreeNode _ n _) = n
count (HasseLeafNode _ n) = n
child :: HasseNode -> HasseTree
child (HasseTreeNode _ _ c) = c
addCount :: Int -> HasseNode -> HasseNode
addCount a (HasseTreeNode itm n c)= HasseTreeNode itm (n + a) c
addCount a (HasseLeafNode itm n) = HasseLeafNode itm (n + a)
incCount = addCount 1
maxDepth :: HasseTree -> Int
maxDepth [] = 1
maxDepth ((HasseLeafNode _ _):htT) = maxDepth htT
maxDepth ((HasseTreeNode _ _ c):htT) = max (1 + maxDepth c) (maxDepth htT)
toString :: HasseTree -> String
toString ht = toString' ht ""
toString' :: HasseTree -> String -> String
toString' [] _ = ""
toString' ((HasseTreeNode itm n []):htT) prefix = toString' ((HasseLeafNode itm n):htT) prefix
toString' ((HasseLeafNode itm n):htT) prefix = prefix ++ itm ++ " " ++ (show n) ++ "\n"++ (toString' htT prefix)
toString' ((HasseTreeNode itm n child):htT) prefix = (toString' child (prefix ++ " " ++ itm ++ " ")) ++ (toString' htT prefix)
-- removes the infrequent item sets from the Hasse Tree
removeInfrequent :: Int -> HasseTree -> Int -> HasseTree
removeInfrequent _ [] _ = []
removeInfrequent minSupport ht 1 = filter (\x -> (count x) >= minSupport) ht
removeInfrequent minSupport (htH@(HasseLeafNode _ _):htT) k = htH:(removeInfrequent minSupport htT k)
removeInfrequent minSupport ((HasseTreeNode itm n child):htT) k = [HasseTreeNode itm n (removeInfrequent minSupport child (k - 1))] ++ (removeInfrequent minSupport htT k)
-- generates the top level of the hasse tree with all the singletons, filtered for minimum support and sorted lexicographically
singletons :: [ItemSet] -> Int -> HasseTree
singletons dataSet minSupport = sortOn item $ removeInfrequent minSupport (getSingletons dataSet) 1
-- count support for all singletons in the database
getSingletons :: [ItemSet] -> HasseTree
getSingletons is = getSingletons' is []
getSingletons' :: [ItemSet] -> HasseTree -> HasseTree
getSingletons' [] acc = acc
getSingletons' (isH:isT) acc = getSingletons' isT (addSetToSingletons isH acc)
-- adds/counts all the singletons in one transaction, adds them to a Hasse Tree
addSetToSingletons :: ItemSet -> HasseTree -> HasseTree
addSetToSingletons [] ht = ht -- stop condition
addSetToSingletons (isH:isT) ht = addSetToSingletons isT (addItemToSingletons isH ht)
addItemToSingletons :: Item -> HasseTree -> HasseTree
addItemToSingletons itm [] = [HasseLeafNode itm 1] -- itm is the first occurence in the database, we append it with support 1 to the HasseTree
addItemToSingletons itm (htH@(HasseLeafNode singleton n):htT)
| itm == singleton = (HasseLeafNode itm (n+1)):htT-- the item matches the element in the node, so increase counter
| itm /= singleton = htH:(addItemToSingletons itm htT) -- otherwise go through rest of list
resetLeafCounts :: HasseTree -> HasseTree
resetLeafCounts [] = []
resetLeafCounts ((HasseLeafNode itm n):tail) = (HasseLeafNode itm 0):(resetLeafCounts tail)
| gaetjen/FunFreakyPatMan | src/HasseTree.hs | mit | 3,525 | 0 | 11 | 581 | 1,118 | 583 | 535 | 52 | 1 |
{-# LANGUAGE NullaryTypeClasses #-}
module Algorithms.Data
where
import Geometry
class Algorithm d where
algorithmVisualize :: d -> IO [Point2D]
algorithmWindowTitle :: d -> String
| CGenie/haskell-algorithms | src/Algorithms/Data.hs | gpl-2.0 | 195 | 0 | 9 | 38 | 43 | 24 | 19 | 6 | 0 |
{-
Given: Two positive integers a and b (a<b<10000).
Return: The sum of all odd integers from a through b, inclusively.
-}
a = 100
b = 200
sumOdd a b = sum $ filter odd [a..b]
main = do
print $ sumOdd a b
| forgit/Rosalind | ini4.hs | gpl-2.0 | 209 | 2 | 8 | 49 | 59 | 27 | 32 | 5 | 1 |
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses #-}
module Baum.RedBlack
( make_quiz )
where
-- $Id$
import Baum.RedBlack.Type
import Baum.RedBlack.Ops
import Baum.RedBlack.Show
import qualified Baum.Such.Class as C
import qualified Baum.Such.Central
import qualified Tree as T
import Autolib.ToDoc
import Inter.Types
import Data.Typeable
instance C.Such RedBlackTree where
empty = Empty
isEmpty = isLeaf
contains = contains
insert = rbInsert
delete = error "Delete für RedBlackTree nicht implementiert"
equal = (==)
contents = contents
instance Show a => T.ToTree ( RedBlackTree a ) where
toTree = toTree . fmap show
toTreeNode = toTreeNode . fmap show
data SuchbaumRedBlack = SuchbaumRedBlack
deriving ( Eq, Ord, Show, Read, Typeable )
instance C.Tag SuchbaumRedBlack RedBlackTree Int where
tag = SuchbaumRedBlack
make_quiz :: Make
make_quiz = Baum.Such.Central.make_quiz SuchbaumRedBlack
| Erdwolf/autotool-bonn | src/Baum/RedBlack.hs | gpl-2.0 | 943 | 0 | 7 | 162 | 231 | 135 | 96 | 29 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module DB where
import Data.Int
import Data.Maybe
import Control.Applicative
import qualified Data.Text.Lazy as T
import qualified Data.Text as TT (concat)
import Database.SQLite.Simple
import Database.SQLite.Simple.FromField
import Database.SQLite.Simple.ToField
import Database.SQLite.Simple.FromRow
import Database.SQLite.Simple.Internal
import Type
instance FromField CellStatus where
fromField (Field (SQLInteger i) _) =
case i of
0 -> pure E
1 -> pure X
2 -> pure O
_ -> error "Int must be between 0 and 2"
instance FromRow Int where
fromRow = field
instance FromRow User where
fromRow = User <$> field <*> field
instance FromRow Game where
fromRow = Game
<$> field
<*> field
<*> field
<*> field
<*> (Board
<$> field
<*> field
<*> field
<*> field
<*> field
<*> field
<*> field
<*> field
<*> field)
instance ToField CellStatus where
toField E = toField (0 :: Int)
toField X = toField (1 :: Int)
toField O = toField (2 :: Int)
instance ToRow User where
toRow (User i u) = toRow (i, u)
simpleGame :: Game -> IO Game
simpleGame (Game i p1 0 _ _) = do
u1 <- getUser p1
return (SimpleGame i (fromJust u1) Nothing)
simpleGame (Game i p1 p2 _ _) = do
u1 <- getUser p1
u2 <- getUser p2
return (SimpleGame i (fromJust u1) u2)
tictactoeDB :: String
tictactoeDB = "tictactoe.db"
setupDB :: IO ()
setupDB = withConnection tictactoeDB $
\conn -> do
execute_ conn "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY NOT NULL, username TEXT NOT NULL)"
execute_ conn "CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY NOT NULL, player1 INTEGER NOT NULL, player2 INTEGER NOT NULL DEFAULT 0, turn INTEGER NOT NULL DEFAULT 0, c0 INTEGER NOT NULL DEFAULT 0, c1 INTEGER NOT NULL DEFAULT 0, c2 INTEGER NOT NULL DEFAULT 0, c3 INTEGER NOT NULL DEFAULT 0, c4 INTEGER NOT NULL DEFAULT 0, c5 INTEGER NOT NULL DEFAULT 0, c6 INTEGER NOT NULL DEFAULT 0, c7 INTEGER NOT NULL DEFAULT 0, c8 INTEGER NOT NULL DEFAULT 0)"
createNewUser :: T.Text -> IO User
createNewUser u = withConnection tictactoeDB $
\conn -> do
execute conn "INSERT INTO users (username) VALUES (?)" (Only u)
i <- lastInsertRowId conn
return (User (fromIntegral i) u)
checkUser :: Connection -> User -> IO Bool
checkUser conn u = do
let i = user_id u
r0 <- query conn "SELECT id FROM users where id = ?" (Only i) :: IO [Id]
return (not (null r0))
getPlayerCS :: Game -> User -> CellStatus
getPlayerCS (Game _ p1 p2 _ _) (User i _)
| p1 == i = X
| p2 == i = O
checkPlayerTurn :: Game -> User -> Bool
checkPlayerTurn (Game _ p1 p2 t _) (User i _) = (p1 == i || p2 == i) && (t == i)
createNewGame :: User -> IO (Maybe Game)
createNewGame u = withConnection tictactoeDB $
\conn -> do
b <- checkUser conn u
if b
then do
execute conn "INSERT INTO games (player1) VALUES (?)" (Only (user_id u))
gameId <- lastInsertRowId conn
return (Just (SimpleGame (fromIntegral gameId) u Nothing))
else return Nothing
joinGame :: Id -> User -> IO (Maybe Game)
joinGame gi u = withConnection tictactoeDB $
\conn -> do
cu <- checkUser conn u
game <- getGame' conn gi
maybe (return Nothing)
(\(Game gi p1 p2 t b) ->
let i = user_id u
in
if cu && p2 == 0 && p1 /= i
then do
execute conn "UPDATE games SET player2 = ?, turn = ? WHERE id = ?" [i, p1, gi]
u1 <- getUser p1
return (Just (SimpleGame gi (fromJust u1) (Just u)))
else return Nothing) game
playQuery :: T.Text -> Query
playQuery cell = let c = T.toStrict cell
in Query $ TT.concat [ "UPDATE games SET "
, c
, " = ?, turn = ? WHERE id = ?"
]
boardCell :: T.Text -> Board -> CellStatus
boardCell "c0" = c0
boardCell "c1" = c1
boardCell "c2" = c2
boardCell "c3" = c3
boardCell "c4" = c4
boardCell "c5" = c5
boardCell "c6" = c6
boardCell "c7" = c7
boardCell "c8" = c8
boardCell _ = \ _ -> X
playGame :: Id -> Play -> IO Bool
playGame gi p = withConnection tictactoeDB $
\conn -> do
game <- getGame' conn gi
maybe (return False)
(\game@(Game _ p1 p2 _ brd) ->
let plyr = player p
cell = play p
b = checkPlayerTurn game plyr
in
if not (b && boardCell cell brd == E)
then return False
else
let cs = getPlayerCS game plyr
nt = if user_id plyr == p1 then p2 else p1
in do
execute conn (playQuery cell) (cs, nt, gi)
return True) game
getUser :: Id -> IO (Maybe User)
getUser i = withConnection tictactoeDB $
\conn -> do
result <- query conn "SELECT * FROM users WHERE id = ?" (Only i)
case result of
[user] -> return (Just user)
_ -> return Nothing
getUser' :: T.Text -> IO (Maybe User)
getUser' username = withConnection tictactoeDB $
\conn -> do
result <- query conn "SELECT * FROM users where username = ?" (Only username)
case result of
[user] -> return (Just user)
_ -> return Nothing
getGame :: Id -> IO (Maybe Game)
getGame i = withConnection tictactoeDB $
\conn -> getGame' conn i
getGame' :: Connection -> Id -> IO (Maybe Game)
getGame' conn i = do
result <- query conn "SELECT * FROM games where id = ?" (Only i)
case result of
[game] -> return (Just game)
_ -> return Nothing
getGames :: IO [Game]
getGames = withConnection tictactoeDB $
\conn -> query_ conn "SELECT * FROM games" >>= mapM simpleGame
| jgalat0/tictactoe | src/DB.hs | gpl-3.0 | 6,075 | 0 | 23 | 1,988 | 1,896 | 940 | 956 | 160 | 3 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module Lamdu.GUI.ExpressionEdit.CaseEdit
( make
) where
import Prelude.Compat
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.MonadA (MonadA)
import qualified Data.List as List
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Store.Transaction (Transaction)
import Data.Vector.Vector2 (Vector2(..))
import Graphics.UI.Bottle.Animation (AnimId)
import qualified Graphics.UI.Bottle.Animation as Anim
import qualified Graphics.UI.Bottle.EventMap as E
import Graphics.UI.Bottle.View (View(..))
import qualified Graphics.UI.Bottle.Widget as Widget
import Lamdu.Config (Config)
import qualified Lamdu.Config as Config
import qualified Lamdu.Eval.Val as EV
import Lamdu.Expr.Type (Tag)
import qualified Lamdu.Expr.Val as V
import qualified Lamdu.GUI.ExpressionEdit.EventMap as ExprEventMap
import qualified Lamdu.GUI.ExpressionEdit.TagEdit as TagEdit
import Lamdu.GUI.ExpressionGui (ExpressionGui)
import qualified Lamdu.GUI.ExpressionGui as ExpressionGui
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import Lamdu.Sugar.Names.Types (Name(..))
import qualified Lamdu.Sugar.Types as Sugar
type T = Transaction
assignCursor ::
MonadA m =>
Widget.Id ->
[Sugar.CaseAlt name n (Sugar.Expression name n p)] ->
ExprGuiM m a -> ExprGuiM m a
assignCursor _ [] = id
assignCursor myId (alt : _) =
ExprGuiM.assignCursor myId
( alt ^. Sugar.caHandler . Sugar.rPayload
& WidgetIds.fromExprPayload )
make ::
MonadA m =>
Sugar.Case (Name m) m (ExprGuiT.SugarExpr m) ->
Sugar.Payload m ExprGuiT.Payload ->
ExprGuiM m (ExpressionGui m)
make (Sugar.Case mArg alts caseTail mAddAlt cEntityId) pl =
ExpressionGui.stdWrapParentExpr pl $ \myId ->
assignCursor myId alts $
do
config <- ExprGuiM.readConfig
let mExprAfterHeader =
( (alts ^.. Lens.traversed . Lens.traversed)
++ (caseTail ^.. Lens.traversed)
) ^? Lens.traversed
labelJumpHoleEventMap <-
mExprAfterHeader <&> ExprGuiT.nextHolesBefore
& Lens._Just ExprEventMap.jumpHolesEventMap
<&> fromMaybe mempty
let label text =
WidgetIds.fromEntityId cEntityId & Widget.toAnimId
& ExpressionGui.grammarLabel text
let headerLabel text =
label text
>>= ExpressionGui.makeFocusableView
(Widget.joinId myId ["header"])
<&> ExpressionGui.egWidget
%~ Widget.weakerEvents labelJumpHoleEventMap
(mActiveTag, header) <-
case mArg of
Sugar.LambdaCase -> headerLabel "λ:" <&> (,) Nothing
Sugar.CaseWithArg (Sugar.CaseArg arg mToLambdaCase) ->
do
argEdit <-
ExprGuiM.makeSubexpression 0 arg
<&> ExpressionGui.egWidget %~ Widget.weakerEvents
(maybe mempty (toLambdaCaseEventMap config)
mToLambdaCase)
caseLabel <- headerLabel ":"
mTag <-
ExpressionGui.evaluationResult (arg ^. Sugar.rPayload)
<&> (>>= (^? Lens._Right . EV._HInject . V.injectTag))
return (mTag, ExpressionGui.hbox [argEdit, caseLabel])
(altsGui, resultPickers) <-
ExprGuiM.listenResultPickers $
do
altsGui <- makeAltsWidget mActiveTag alts myId
case caseTail of
Sugar.ClosedCase mDeleteTail ->
altsGui
& ExpressionGui.egWidget %~
Widget.weakerEvents
(maybe mempty (caseOpenEventMap config) mDeleteTail)
& return
Sugar.CaseExtending rest ->
altsGui
& makeOpenCase rest (Widget.toAnimId myId)
let addAltEventMap Nothing = mempty
addAltEventMap (Just addAlt) =
ExprGuiM.holePickersAction resultPickers >> addAlt
<&> (^. Sugar.caarNewTag . Sugar.tagInstance)
<&> WidgetIds.fromEntityId
<&> TagEdit.diveToCaseTag
& Widget.keysEventMapMovesCursor (Config.caseAddAltKeys config)
(E.Doc ["Edit", "Case", "Add Alt"])
vspace <- ExpressionGui.verticalSpace
[header, vspace, altsGui]
& ExpressionGui.vboxTopFocalAlignedTo 0
& ExpressionGui.addValPadding
<&> ExpressionGui.egWidget %~
Widget.weakerEvents (addAltEventMap mAddAlt)
>>= ExpressionGui.egWidget %%~ ExpressionGui.addValBG myId
makeAltRow ::
MonadA m =>
Maybe Tag ->
Sugar.CaseAlt (Name m) m (Sugar.Expression (Name m) m ExprGuiT.Payload) ->
ExprGuiM m [ExpressionGui m]
makeAltRow mActiveTag (Sugar.CaseAlt mDelete tag altExpr) =
do
config <- ExprGuiM.readConfig
altRefGui <-
TagEdit.makeCaseTag (ExprGuiT.nextHolesBefore altExpr) tag
>>= if mActiveTag == Just (tag ^. Sugar.tagVal)
then ExpressionGui.addValFrame
(WidgetIds.fromEntityId (tag ^. Sugar.tagInstance))
else return
altExprGui <- ExprGuiM.makeSubexpression 0 altExpr
let itemEventMap = maybe mempty (caseDelEventMap config) mDelete
space <- ExpressionGui.stdSpace
[ altRefGui & ExpressionGui.egAlignment . _1 .~ 1
, space
, altExprGui & ExpressionGui.egAlignment . _1 .~ 0
]
<&> ExpressionGui.egWidget %~ Widget.weakerEvents itemEventMap
& return
makeAltsWidget ::
MonadA m =>
Maybe Tag ->
[Sugar.CaseAlt (Name m) m (Sugar.Expression (Name m) m ExprGuiT.Payload)] ->
Widget.Id -> ExprGuiM m (ExpressionGui m)
makeAltsWidget _ [] myId =
ExpressionGui.grammarLabel "Ø" (Widget.toAnimId myId)
>>= ExpressionGui.makeFocusableView (Widget.joinId myId ["Ø"])
makeAltsWidget mActiveTag alts _ =
do
vspace <- ExpressionGui.verticalSpace
mapM (makeAltRow mActiveTag) alts
<&> List.intersperse (replicate 3 vspace)
<&> ExpressionGui.gridTopLeftFocal
separationBar :: Config -> Widget.R -> Anim.AnimId -> ExpressionGui m
separationBar config width animId =
Anim.unitSquare (animId <> ["tailsep"])
& View 1
& Widget.fromView
& Widget.tint (Config.caseTailColor config)
& Widget.scale (Vector2 width 10)
& ExpressionGui.fromValueWidget
makeOpenCase ::
MonadA m =>
ExprGuiT.SugarExpr m -> AnimId -> ExpressionGui m ->
ExprGuiM m (ExpressionGui m)
makeOpenCase rest animId altsGui =
do
config <- ExprGuiM.readConfig
vspace <- ExpressionGui.verticalSpace
restExpr <-
ExprGuiM.makeSubexpression 0 rest >>= ExpressionGui.addValPadding
let minWidth = restExpr ^. ExpressionGui.egWidget . Widget.width
[ altsGui
, separationBar config (max minWidth targetWidth) animId
, vspace
, restExpr
] & ExpressionGui.vboxTopFocalAlignedTo 0 & return
where
targetWidth = altsGui ^. ExpressionGui.egWidget . Widget.width
caseOpenEventMap ::
MonadA m =>
Config -> T m Sugar.EntityId -> Widget.EventHandlers (T m)
caseOpenEventMap config open =
Widget.keysEventMapMovesCursor (Config.caseOpenKeys config)
(E.Doc ["Edit", "Case", "Open"]) $ WidgetIds.fromEntityId <$> open
caseDelEventMap ::
MonadA m =>
Config -> T m Sugar.EntityId -> Widget.EventHandlers (T m)
caseDelEventMap config delete =
Widget.keysEventMapMovesCursor (Config.delKeys config)
(E.Doc ["Edit", "Case", "Delete Alt"]) $ WidgetIds.fromEntityId <$> delete
toLambdaCaseEventMap ::
MonadA m =>
Config -> T m Sugar.EntityId -> Widget.EventHandlers (T m)
toLambdaCaseEventMap config toLamCase =
Widget.keysEventMapMovesCursor (Config.delKeys config)
(E.Doc ["Edit", "Case", "Turn to Lambda-Case"]) $
WidgetIds.fromEntityId <$> toLamCase
| rvion/lamdu | Lamdu/GUI/ExpressionEdit/CaseEdit.hs | gpl-3.0 | 8,582 | 0 | 23 | 2,493 | 2,203 | 1,146 | 1,057 | -1 | -1 |
module Hazel.CoreSpec (spec)
where
import Test.Hspec
import Hazel.Core ()
import Hazel.TestCases
spec :: Spec
spec = describe "Show instances" $ do
it "shows plain role names" $
show role `shouldBe` "hasChild"
it "shows plain concept names" $
show top `shouldBe` "Thing"
it "shows conjuctions" $
show conjunction `shouldBe` "(Thing and Person)"
it "shows existentials" $
show existential `shouldBe` "(hasChild some Person)"
it "shows GCIs" $
show gci `shouldBe` "(hasChild some Person) SubClassOf Person"
it "shows TBoxes" $
show tbox `shouldBe` "[(hasChild some Person) SubClassOf Person,Thing SubClassOf (Thing and Person)]"
| hazel-el/hazel | test/Hazel/CoreSpec.hs | gpl-3.0 | 673 | 0 | 10 | 135 | 160 | 81 | 79 | 18 | 1 |
{-# LANGUAGE CPP #-}
module Data.AtFieldTH (make) where
import qualified Data.Char as Char
import qualified Data.List as List
import Language.Haskell.TH.Syntax
make :: Name -> Q [Dec]
make typeName = do
TyConI typeCons <- reify typeName
(makeAtName, typeVars, ctor) <-
case typeCons of
DataD _ _ typeVars constructors _ ->
case constructors of
[ctor] -> return (makeAtNameForDataField, typeVars, ctor)
_ -> fail "one constructor expected for Data.AtFieldTH.make"
NewtypeD _ _ typeVars ctor _ -> return (makeAtNameForNewtype typeName, typeVars, ctor)
_ -> error $ show typeCons ++ " is not supported!"
return $ constructorAtFuncs makeAtName typeName typeVars ctor
constructorAtFuncs :: (Name -> Name) -> Name -> [TyVarBndr] -> Con -> [Dec]
constructorAtFuncs makeAtName typeName typeVars constructor =
concatMap (uncurry (fieldAtFunc makeAtName typeName typeVars isFreeVar)) fields
where
fields = constructorFields constructor
constructorVars = concatMap (List.nub . varsOfType . snd) fields
isFreeVar v = 1 == countElemRepetitions v constructorVars
constructorFields :: Con -> [(Name, Type)]
constructorFields (NormalC name [(_, t)]) = [(name, t)]
constructorFields (RecC _ fields) =
map f fields
where
f (name, _, t) = (name, t)
constructorFields _ = error "unsupported constructor for type supplied to Data.AtFieldTH.make"
countElemRepetitions :: Eq a => a -> [a] -> Int
countElemRepetitions x = length . filter (== x)
-- When field name is *Typename, such as unTypename, or getTypename,
-- As is common convention for 'conceptual' newtype wrappers, we name the accessor atTypename.
-- Otherwise we name it as we do normally with Data constructors.
makeAtNameForNewtype :: Name -> Name -> Name
makeAtNameForNewtype newTypeName fieldName
| typeNameStr `List.isSuffixOf` nameBase fieldName = mkName $ "at" ++ typeNameStr
| otherwise = makeAtNameForDataField fieldName
where
typeNameStr = nameBase newTypeName
makeAtNameForDataField :: Name -> Name
makeAtNameForDataField fieldName =
mkName $ "at" ++ (Char.toUpper fieldNameHead : fieldNameTail)
where
fieldNameHead : fieldNameTail = nameBase fieldName
fieldAtFunc :: (Name -> Name) -> Name -> [TyVarBndr] -> (Name -> Bool) -> Name -> Type -> [Dec]
fieldAtFunc makeAtName typeName typeVars isFreeVar fieldName fieldType =
[ SigD resName . ForallT resultTypeVars [] $ foldr1 arrow
[ arrow (sideType fieldType "Src") (sideType fieldType "Dst")
, input
, output
]
, FunD resName [ Clause [VarP funcName, VarP valName] clause [] ]
]
where
arrow = AppT . AppT ArrowT
funcName = mkName "func"
valName = mkName "val"
resName = makeAtName fieldName
clause = NormalB $ RecUpdE (VarE valName) [(fieldName, applyExp)]
applyExp = AppE (VarE funcName) . AppE (VarE fieldName) $ VarE valName
valType = foldl AppT (ConT typeName) $ map (VarT . tyVarBndrName) typeVars
sideType t suffix = mapTypeVarNames (sideTypeVar suffix) t
fieldVars = List.nub (varsOfType fieldType)
sideTypeVar suffix name =
if isFreeVar name && elem name fieldVars
then mkName (nameBase name ++ suffix) else name
input = sideType valType "Src"
output = sideType valType "Dst"
resultTypeVars = map PlainTV . List.nub $ concatMap varsOfType [input, output]
tyVarBndrName :: TyVarBndr -> Name
tyVarBndrName (PlainTV name) = name
tyVarBndrName (KindedTV name _) = name
-- TODO [BP]: can boilerplate be reduced with SYB/uniplate ?
varsOfType :: Type -> [Name]
varsOfType (ForallT _ _ t) = varsOfType t -- TODO: dwa need todo something wrt the predicates?
varsOfType (VarT x) = [x]
varsOfType (ConT _) = []
varsOfType (TupleT _) = []
#if __GLASGOW_HASKELL__ >= 704
varsOfType (UnboxedTupleT _) = []
#endif
varsOfType ArrowT = []
varsOfType ListT = []
varsOfType (AppT x y) = varsOfType x ++ varsOfType y
varsOfType (SigT x _) = varsOfType x
-- TODO BP
mapTypeVarNames :: (Name -> Name) -> Type -> Type
mapTypeVarNames func (ForallT vars cxt t) =
ForallT vars (map (mapPredVarNames func) cxt) (mapTypeVarNames func t)
mapTypeVarNames func (VarT x) = VarT (func x)
mapTypeVarNames _ (ConT x) = ConT x
mapTypeVarNames _ (TupleT x) = TupleT x
#if __GLASGOW_HASKELL__ >= 704
mapTypeVarNames _ (UnboxedTupleT x) = UnboxedTupleT x
#endif
mapTypeVarNames _ ArrowT = ArrowT
mapTypeVarNames _ ListT = ListT
mapTypeVarNames func (AppT x y) = AppT (mapTypeVarNames func x) (mapTypeVarNames func y)
mapTypeVarNames func (SigT t kind) = SigT (mapTypeVarNames func t) kind
-- TODO BP
mapPredVarNames :: (Name -> Name) -> Pred -> Pred
mapPredVarNames func (ClassP name types) = ClassP name $ map (mapTypeVarNames func) types
mapPredVarNames func (EqualP x y) = EqualP (mapTypeVarNames func x) (mapTypeVarNames func y)
| nimia/bottle | bottlelib/Data/AtFieldTH.hs | gpl-3.0 | 4,991 | 0 | 15 | 1,083 | 1,567 | 803 | 764 | 87 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
module Command where
import System.Console.CmdArgs
data HPythia8Generate = Generate { config :: FilePath }
deriving (Show,Data,Typeable)
generate :: HPythia8Generate
generate = Generate { config = "HPythia8.conf" }
mode :: HPythia8Generate
mode = modes [generate]
| wavewave/HPythia8-generate | exe/Command.hs | gpl-3.0 | 321 | 0 | 8 | 59 | 75 | 45 | 30 | 9 | 1 |
-- searchable spaces, based on code by Martin Escardo
module Searchable where
data Searchable a = Finder ((a -> Bool) -> a)
find :: Searchable a -> (a -> Bool) -> a
find (Finder epsilon) p = epsilon p
-- auxiliary function search
search :: Searchable a -> (a -> Bool) -> Maybe a
search s p =
let x = find s p
in if p x then Just x else Nothing
-- quantifiers
exists' s p = p (find s p)
forall' s p = not (exists' s (not . p))
-- some searchable spaces
-- singleton
singleton x = Finder (\p -> x)
-- doubleton
doubleton x y = Finder (\p -> if p x then x else y)
-- non-empty sets
set :: [a] -> Searchable a
set lst = Finder (\p ->
let loop [] = undefined
loop [x] = x
loop (x:xs) = if p x then x else loop xs
in loop lst)
-- the sum of two searchable sets a and b is searchable
sum s t = Finder (\p -> let x = Left (find s (p . Left))
y = Right (find t (p . Right))
in if p x then x else y)
-- a union of a searchable family of searchable spaces ss
bigUnion :: Searchable (Searchable a) -> Searchable a
bigUnion ss = Finder (\p -> find (find ss (\s -> exists' s p)) p)
-- a union of two sets is a special case
union s t = bigUnion (doubleton s t)
-- the image of a searchable set s under a map f
image f s = Finder (\p -> f (find s (p . f)))
-- monad structure for searchable spaces
instance Monad Searchable where
return = singleton
s >>= f = bigUnion (image f s)
-- product of a and b
a `times` b = do x <- a
y <- b
return (x, y)
-- a product of a list of spaces, where the list may be infinite
prod [] = return []
prod (a:as) = do x <- a
xs <- prod as
return (x:xs)
-- the Cantor space
two = doubleton False True
cantor = prod (repeat two)
-- we may test equality of functions
equal' a f g = forall' a (\x -> f x == g x)
| aljosaVodopija/eksaktnaRealna | Searchable.hs | gpl-3.0 | 1,942 | 0 | 16 | 608 | 748 | 383 | 365 | 38 | 4 |
module Herguis.Setup(buildInterface) where
import Control.Monad
import Control.Monad.Trans(liftIO)
import Data.IORef
import Data.List
import Data.Tree
import Data.Time.Clock
import Graphics.UI.Gtk
import Graphics.UI.Gtk.SourceView
import Text.Printf
import qualified Herguis.Action as Action
import Herguis.Entities
setupMenuItemFile editorStatusRef assemblerStatusRef config window = do
file <- menuItemNewWithMnemonic "_File"
menu <- menuNew
s0 <- separatorMenuItemNew
s1 <- separatorMenuItemNew
new <- menuItemNewWithMnemonic "_New"
new `on` menuItemActivate $ Action.new editorStatusRef assemblerStatusRef window
open <- menuItemNewWithMnemonic "_Open"
open `on` menuItemActivate $ Action.open editorStatusRef assemblerStatusRef window
save <- menuItemNewWithMnemonic "_Save"
save `on` menuItemActivate $ Action.save editorStatusRef assemblerStatusRef window >> return ()
saveas <- menuItemNewWithMnemonic "Save _as"
saveas `on` menuItemActivate $ Action.saveAs editorStatusRef assemblerStatusRef window >> return ()
exit <- menuItemNewWithMnemonic "_Exit"
exit `on` menuItemActivate $ Action.quit editorStatusRef assemblerStatusRef (lastStatusFile config) window >>= \x -> return ()
containerAdd menu new
containerAdd menu s0
containerAdd menu open
containerAdd menu save
containerAdd menu saveas
containerAdd menu s1
containerAdd menu exit
set file [menuItemSubmenu := menu]
return file
setupMenuItemPreferences = menuItemNewWithMnemonic "_Preferences"
setupMenuItemHelp = menuItemNewWithMnemonic "_Help"
setupMenuBar editorStatusRef assemblerStatusRef config window = do
bar <- menuBarNew
miFile <- setupMenuItemFile editorStatusRef assemblerStatusRef config window
miPref <- setupMenuItemPreferences
miHelp <- setupMenuItemHelp
containerAdd bar miFile
containerAdd bar miPref
containerAdd bar miHelp
return bar
setupTextView config = do
tTextView <- sourceViewNew
set tTextView [textViewWrapMode := wrapMode config, sourceViewShowLineNumbers := lineNumbering config]
tTextBuffer <- get tTextView textViewBuffer
return (tTextView,tTextBuffer)
setupActionBar machines editorStatusRef assemblerStatusRef assemblerName msgFile outputList window = do
bar <- hBoxNew False 0
machineBox <- comboBoxNewText
set machineBox [comboBoxWrapWidth := 1]
mapM_ (\(x,y) -> comboBoxAppendText machineBox x) machines
assemblerStatus <- readIORef assemblerStatusRef
when (machineFile assemblerStatus /= "") $
let index = find (\((_,y),_) -> y == (machineFile assemblerStatus)) $ zip machines [0,1..] in
case index of
Just (_,index) -> set machineBox [comboBoxActive := index]
Nothing -> return ()
sep <- vSeparatorNew
refreshImg <- imageNewFromStock stockRefresh IconSizeButton
assembleImg <- imageNewFromStock stockExecute IconSizeButton
refreshBtn <- buttonNew
assembleBtn <- buttonNew
set refreshBtn [buttonImage := refreshImg, widgetTooltipText := Just "Refresh"]
set assembleBtn [buttonImage := assembleImg, widgetTooltipText := Just "Assemble"]
boxPackStart bar machineBox PackNatural 0
boxPackStart bar sep PackNatural 10
boxPackStart bar refreshBtn PackNatural 0
boxPackStart bar assembleBtn PackNatural 0
machineBox `on` changed $ do
active <- get machineBox comboBoxActive
let (name,location) = machines !! active
assemblerStatus <- readIORef assemblerStatusRef
writeIORef assemblerStatusRef assemblerStatus{machineFile = location}
refreshBtn `on` buttonActivated $ do
editorStatus <- readIORef editorStatusRef
Action.load (filename editorStatus) editorStatusRef
assembleBtn `on` buttonActivated $ Action.assemble editorStatusRef assemblerStatusRef assemblerName msgFile outputList window
return bar
setupOutputBar = do
treeModel <- listStoreNew []
treeView <- treeViewNewWithModel treeModel
vAdjust <- get treeView treeViewVAdjustment
case vAdjust of
Just ad -> set ad [adjustmentUpper := 0.3, adjustmentValue := 0.1]
Nothing -> return ()
typeCol <- treeViewColumnNew
lineCol <- treeViewColumnNew
msgCol <- treeViewColumnNew
treeViewColumnSetTitle typeCol "Type"
treeViewColumnSetTitle lineCol "Line"
treeViewColumnSetTitle msgCol "Message"
typeRenderer <- cellRendererTextNew
lineRenderer <- cellRendererTextNew
msgRenderer <- cellRendererTextNew
cellLayoutPackStart typeCol typeRenderer False
cellLayoutPackStart lineCol lineRenderer False
cellLayoutPackStart msgCol msgRenderer False
cellLayoutSetAttributes typeCol typeRenderer treeModel
$ \(a,b,c) -> [cellText := a]
cellLayoutSetAttributes typeCol lineRenderer treeModel
$ \(a,b,c) -> [cellText := b]
cellLayoutSetAttributes msgCol msgRenderer treeModel
$ \(a,b,c) -> [cellText := c]
treeViewAppendColumn treeView typeCol
treeViewAppendColumn treeView lineCol
treeViewAppendColumn treeView msgCol
treeViewSetHeadersVisible treeView True
vadj <- get treeView treeViewVAdjustment
hadj <- get treeView treeViewHAdjustment
swin <- scrolledWindowNew hadj vadj
containerAdd swin treeView
return (treeModel,swin)
buildInterface config editorStatus assemblerStatus = do
window <- windowNew
mainBox <- vBoxNew False 0
textWindow <- scrolledWindowNew Nothing Nothing
set textWindow [scrolledWindowHscrollbarPolicy := PolicyAutomatic, scrolledWindowVscrollbarPolicy := PolicyAutomatic]
-- sets up editor's text
(tTextView,tTextBuffer) <- setupTextView config
editorStatusRef <- newIORef editorStatus{buffer = tTextBuffer}
Action.load (filename editorStatus) editorStatusRef
tTextBuffer `on` bufferChanged $ liftIO $ do
eStatus <- readIORef editorStatusRef
writeIORef editorStatusRef eStatus{modified = True}
assemblerStatusRef <- newIORef assemblerStatus
(outputList, outputView) <- setupOutputBar
mMenuBar <- setupMenuBar editorStatusRef assemblerStatusRef config window
actionBar <- setupActionBar (machines config) editorStatusRef assemblerStatusRef (assembler config) (messageFile config) outputList window
set window [windowDefaultWidth := 640, windowDefaultHeight := 480, containerChild := mainBox, containerBorderWidth := 1]
let cols = 4
sourceBox <- tableNew cols 1 True
boxPackStart mainBox mMenuBar PackNatural 0
boxPackStart mainBox actionBar PackNatural 0
boxPackStart mainBox sourceBox PackGrow 0
tableAttachDefaults sourceBox textWindow 0 1 0 (cols -1)
tableAttachDefaults sourceBox outputView 0 1 (cols -1) cols
containerAdd textWindow tTextView
window `on` deleteEvent $ liftIO $ Action.quit editorStatusRef assemblerStatusRef (lastStatusFile config) window
window `on` focusInEvent $ liftIO $ Action.reloadFile editorStatusRef
widgetShowAll window
when (hasError config) $ Action.popupError (errorMsg config) window
| mgmillani/herguis | Herguis/Setup.hs | gpl-3.0 | 6,669 | 4 | 18 | 899 | 1,920 | 902 | 1,018 | 146 | 2 |
{-# LANGUAGE ForeignFunctionInterface
, EmptyDataDecls
#-}
module Rollsum where
import Data.Word
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.ByteString.Internal as BI
import Foreign
import Foreign.C
blobModulo = 16383
foreign import ccall unsafe "rollsum.h"
c_make :: IO (Ptr CSum)
foreign import ccall unsafe "rollsum.h"
c_init :: Ptr CSum -> IO ()
foreign import ccall unsafe "rollsum.h"
c_next :: Ptr CSum -> Ptr Word8 -> CInt -> CUInt -> IO CInt
foreign import ccall unsafe "rollsum.h"
c_feed :: Ptr CSum -> Ptr Word8 -> CInt -> CUInt -> IO ()
data CSum
newtype Sum = Sum { getSum :: ForeignPtr CSum }
deriving Show
makeSum :: IO Sum
makeSum = do
cs <- c_make
fptr <- newForeignPtr finalizerFree cs
return $! Sum $! fptr
{-# INLINE makeSum #-}
resetSum :: Sum -> IO ()
resetSum (Sum fptr) = withForeignPtr fptr c_init
{-# INLINE resetSum #-}
nextPos :: Sum -> B.ByteString -> IO (Maybe Int)
nextPos (Sum fptrS) bs = do
withForeignPtr fptrB $ \ptrB -> do
withForeignPtr fptrS $ \ptrS -> do
pos <- c_next ptrS (ptrB `plusPtr` offset) (fromIntegral len) blobModulo
return $ if pos == -1
then Nothing
else Just $! fromIntegral pos
where
(fptrB, offset, len) = toForeignPtr bs
{-# INLINE nextPos #-}
splitBlock :: Sum -> B.ByteString -> IO (Maybe (B.ByteString, B.ByteString))
splitBlock sum bs = do
mpos <- nextPos sum bs
return $ do pos <- mpos
return $ B.splitAt pos bs
{-# INLINE splitBlock #-}
splitBlockLazy :: Sum -> BL.ByteString -> IO (Maybe (BL.ByteString, BL.ByteString))
splitBlockLazy sum bs = go BL.empty $ BL.toChunks bs
where
go s [] = return Nothing
go s (x:xs) = do
mpos <- nextPos sum x
case mpos of
Just i -> let len = BL.length s + fromIntegral i
in return $ Just $! BL.splitAt len bs
Nothing -> go (BL.append s $ BL.fromChunks [x]) xs
{-# INLINE splitBlockLazy #-}
feedSum :: Sum -> B.ByteString -> IO ()
feedSum sum = go
where
go bs = do
msplit <- splitBlock sum bs
case msplit of
Nothing -> return ()
Just (hd, tl) -> go tl
{-# INLINE feedSum #-}
feedSumLazy :: Sum -> BL.ByteString -> IO ()
feedSumLazy sum = mapM_ (feedSum sum) . BL.toChunks
| br0ns/hindsight | src/Rollsum.hs | gpl-3.0 | 2,355 | 0 | 18 | 607 | 832 | 421 | 411 | -1 | -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.GamesManagement.Quests.ResetForAllPlayers
-- 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)
--
-- Resets all player progress on the quest with the given ID for all
-- players. This method is only available to user accounts for your
-- developer console. Only draft quests can be reset.
--
-- /See:/ <https://developers.google.com/games/services Google Play Game Services Management API Reference> for @gamesManagement.quests.resetForAllPlayers@.
module Network.Google.Resource.GamesManagement.Quests.ResetForAllPlayers
(
-- * REST Resource
QuestsResetForAllPlayersResource
-- * Creating a Request
, questsResetForAllPlayers
, QuestsResetForAllPlayers
-- * Request Lenses
, qrfapQuestId
) where
import Network.Google.GamesManagement.Types
import Network.Google.Prelude
-- | A resource alias for @gamesManagement.quests.resetForAllPlayers@ method which the
-- 'QuestsResetForAllPlayers' request conforms to.
type QuestsResetForAllPlayersResource =
"games" :>
"v1management" :>
"quests" :>
Capture "questId" Text :>
"resetForAllPlayers" :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Resets all player progress on the quest with the given ID for all
-- players. This method is only available to user accounts for your
-- developer console. Only draft quests can be reset.
--
-- /See:/ 'questsResetForAllPlayers' smart constructor.
newtype QuestsResetForAllPlayers = QuestsResetForAllPlayers'
{ _qrfapQuestId :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'QuestsResetForAllPlayers' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'qrfapQuestId'
questsResetForAllPlayers
:: Text -- ^ 'qrfapQuestId'
-> QuestsResetForAllPlayers
questsResetForAllPlayers pQrfapQuestId_ =
QuestsResetForAllPlayers'
{ _qrfapQuestId = pQrfapQuestId_
}
-- | The ID of the quest.
qrfapQuestId :: Lens' QuestsResetForAllPlayers Text
qrfapQuestId
= lens _qrfapQuestId (\ s a -> s{_qrfapQuestId = a})
instance GoogleRequest QuestsResetForAllPlayers where
type Rs QuestsResetForAllPlayers = ()
type Scopes QuestsResetForAllPlayers =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.login"]
requestClient QuestsResetForAllPlayers'{..}
= go _qrfapQuestId (Just AltJSON)
gamesManagementService
where go
= buildClient
(Proxy :: Proxy QuestsResetForAllPlayersResource)
mempty
| rueshyna/gogol | gogol-games-management/gen/Network/Google/Resource/GamesManagement/Quests/ResetForAllPlayers.hs | mpl-2.0 | 3,385 | 0 | 13 | 718 | 314 | 194 | 120 | 51 | 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.ProximityBeacon.Beacons.Deactivate
-- 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)
--
-- Deactivates a beacon. Once deactivated, the API will not return
-- information nor attachment data for the beacon when queried via
-- \`beaconinfo.getforobserved\`. Calling this method on an already
-- inactive beacon will do nothing (but will return a successful response
-- code). Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **Is owner** or **Can edit** permissions in
-- the Google Developers Console project.
--
-- /See:/ <https://developers.google.com/beacons/proximity/ Google Proximity Beacon API Reference> for @proximitybeacon.beacons.deactivate@.
module Network.Google.Resource.ProximityBeacon.Beacons.Deactivate
(
-- * REST Resource
BeaconsDeactivateResource
-- * Creating a Request
, beaconsDeactivate
, BeaconsDeactivate
-- * Request Lenses
, bdXgafv
, bdUploadProtocol
, bdPp
, bdAccessToken
, bdBeaconName
, bdUploadType
, bdBearerToken
, bdProjectId
, bdCallback
) where
import Network.Google.Prelude
import Network.Google.ProximityBeacon.Types
-- | A resource alias for @proximitybeacon.beacons.deactivate@ method which the
-- 'BeaconsDeactivate' request conforms to.
type BeaconsDeactivateResource =
"v1beta1" :>
CaptureMode "beaconName" "deactivate" Text :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "projectId" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] Empty
-- | Deactivates a beacon. Once deactivated, the API will not return
-- information nor attachment data for the beacon when queried via
-- \`beaconinfo.getforobserved\`. Calling this method on an already
-- inactive beacon will do nothing (but will return a successful response
-- code). Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **Is owner** or **Can edit** permissions in
-- the Google Developers Console project.
--
-- /See:/ 'beaconsDeactivate' smart constructor.
data BeaconsDeactivate = BeaconsDeactivate'
{ _bdXgafv :: !(Maybe Text)
, _bdUploadProtocol :: !(Maybe Text)
, _bdPp :: !Bool
, _bdAccessToken :: !(Maybe Text)
, _bdBeaconName :: !Text
, _bdUploadType :: !(Maybe Text)
, _bdBearerToken :: !(Maybe Text)
, _bdProjectId :: !(Maybe Text)
, _bdCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'BeaconsDeactivate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bdXgafv'
--
-- * 'bdUploadProtocol'
--
-- * 'bdPp'
--
-- * 'bdAccessToken'
--
-- * 'bdBeaconName'
--
-- * 'bdUploadType'
--
-- * 'bdBearerToken'
--
-- * 'bdProjectId'
--
-- * 'bdCallback'
beaconsDeactivate
:: Text -- ^ 'bdBeaconName'
-> BeaconsDeactivate
beaconsDeactivate pBdBeaconName_ =
BeaconsDeactivate'
{ _bdXgafv = Nothing
, _bdUploadProtocol = Nothing
, _bdPp = True
, _bdAccessToken = Nothing
, _bdBeaconName = pBdBeaconName_
, _bdUploadType = Nothing
, _bdBearerToken = Nothing
, _bdProjectId = Nothing
, _bdCallback = Nothing
}
-- | V1 error format.
bdXgafv :: Lens' BeaconsDeactivate (Maybe Text)
bdXgafv = lens _bdXgafv (\ s a -> s{_bdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bdUploadProtocol :: Lens' BeaconsDeactivate (Maybe Text)
bdUploadProtocol
= lens _bdUploadProtocol
(\ s a -> s{_bdUploadProtocol = a})
-- | Pretty-print response.
bdPp :: Lens' BeaconsDeactivate Bool
bdPp = lens _bdPp (\ s a -> s{_bdPp = a})
-- | OAuth access token.
bdAccessToken :: Lens' BeaconsDeactivate (Maybe Text)
bdAccessToken
= lens _bdAccessToken
(\ s a -> s{_bdAccessToken = a})
-- | Beacon that should be deactivated. A beacon name has the format
-- \"beacons\/N!beaconId\" where the beaconId is the base16 ID broadcast by
-- the beacon and N is a code for the beacon\'s type. Possible values are
-- \`3\` for Eddystone-UID, \`4\` for Eddystone-EID, \`1\` for iBeacon, or
-- \`5\` for AltBeacon. For Eddystone-EID beacons, you may use either the
-- current EID or the beacon\'s \"stable\" UID. Required.
bdBeaconName :: Lens' BeaconsDeactivate Text
bdBeaconName
= lens _bdBeaconName (\ s a -> s{_bdBeaconName = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bdUploadType :: Lens' BeaconsDeactivate (Maybe Text)
bdUploadType
= lens _bdUploadType (\ s a -> s{_bdUploadType = a})
-- | OAuth bearer token.
bdBearerToken :: Lens' BeaconsDeactivate (Maybe Text)
bdBearerToken
= lens _bdBearerToken
(\ s a -> s{_bdBearerToken = a})
-- | The project id of the beacon to deactivate. If the project id is not
-- specified then the project making the request is used. The project id
-- must match the project that owns the beacon. Optional.
bdProjectId :: Lens' BeaconsDeactivate (Maybe Text)
bdProjectId
= lens _bdProjectId (\ s a -> s{_bdProjectId = a})
-- | JSONP
bdCallback :: Lens' BeaconsDeactivate (Maybe Text)
bdCallback
= lens _bdCallback (\ s a -> s{_bdCallback = a})
instance GoogleRequest BeaconsDeactivate where
type Rs BeaconsDeactivate = Empty
type Scopes BeaconsDeactivate =
'["https://www.googleapis.com/auth/userlocation.beacon.registry"]
requestClient BeaconsDeactivate'{..}
= go _bdBeaconName _bdXgafv _bdUploadProtocol
(Just _bdPp)
_bdAccessToken
_bdUploadType
_bdBearerToken
_bdProjectId
_bdCallback
(Just AltJSON)
proximityBeaconService
where go
= buildClient
(Proxy :: Proxy BeaconsDeactivateResource)
mempty
| rueshyna/gogol | gogol-proximitybeacon/gen/Network/Google/Resource/ProximityBeacon/Beacons/Deactivate.hs | mpl-2.0 | 7,008 | 0 | 18 | 1,587 | 951 | 559 | 392 | 129 | 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.Instances.TestIAMPermissions
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns permissions that a caller has on the specified resource.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.testIamPermissions@.
module Network.Google.Resource.Compute.Instances.TestIAMPermissions
(
-- * REST Resource
InstancesTestIAMPermissionsResource
-- * Creating a Request
, instancesTestIAMPermissions
, InstancesTestIAMPermissions
-- * Request Lenses
, itipProject
, itipZone
, itipPayload
, itipResource
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instances.testIamPermissions@ method which the
-- 'InstancesTestIAMPermissions' request conforms to.
type InstancesTestIAMPermissionsResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instances" :>
Capture "resource" Text :>
"testIamPermissions" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TestPermissionsRequest :>
Post '[JSON] TestPermissionsResponse
-- | Returns permissions that a caller has on the specified resource.
--
-- /See:/ 'instancesTestIAMPermissions' smart constructor.
data InstancesTestIAMPermissions =
InstancesTestIAMPermissions'
{ _itipProject :: !Text
, _itipZone :: !Text
, _itipPayload :: !TestPermissionsRequest
, _itipResource :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstancesTestIAMPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'itipProject'
--
-- * 'itipZone'
--
-- * 'itipPayload'
--
-- * 'itipResource'
instancesTestIAMPermissions
:: Text -- ^ 'itipProject'
-> Text -- ^ 'itipZone'
-> TestPermissionsRequest -- ^ 'itipPayload'
-> Text -- ^ 'itipResource'
-> InstancesTestIAMPermissions
instancesTestIAMPermissions pItipProject_ pItipZone_ pItipPayload_ pItipResource_ =
InstancesTestIAMPermissions'
{ _itipProject = pItipProject_
, _itipZone = pItipZone_
, _itipPayload = pItipPayload_
, _itipResource = pItipResource_
}
-- | Project ID for this request.
itipProject :: Lens' InstancesTestIAMPermissions Text
itipProject
= lens _itipProject (\ s a -> s{_itipProject = a})
-- | The name of the zone for this request.
itipZone :: Lens' InstancesTestIAMPermissions Text
itipZone = lens _itipZone (\ s a -> s{_itipZone = a})
-- | Multipart request metadata.
itipPayload :: Lens' InstancesTestIAMPermissions TestPermissionsRequest
itipPayload
= lens _itipPayload (\ s a -> s{_itipPayload = a})
-- | Name or id of the resource for this request.
itipResource :: Lens' InstancesTestIAMPermissions Text
itipResource
= lens _itipResource (\ s a -> s{_itipResource = a})
instance GoogleRequest InstancesTestIAMPermissions
where
type Rs InstancesTestIAMPermissions =
TestPermissionsResponse
type Scopes InstancesTestIAMPermissions =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient InstancesTestIAMPermissions'{..}
= go _itipProject _itipZone _itipResource
(Just AltJSON)
_itipPayload
computeService
where go
= buildClient
(Proxy :: Proxy InstancesTestIAMPermissionsResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Instances/TestIAMPermissions.hs | mpl-2.0 | 4,543 | 0 | 18 | 1,061 | 550 | 326 | 224 | 90 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.CreateUser
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new user for your AWS account.
--
-- For information about limitations on the number of users you can create,
-- see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities>
-- in the /Using IAM/ guide.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html AWS API Reference> for CreateUser.
module Network.AWS.IAM.CreateUser
(
-- * Creating a Request
createUser
, CreateUser
-- * Request Lenses
, cuPath
, cuUserName
-- * Destructuring the Response
, createUserResponse
, CreateUserResponse
-- * Response Lenses
, cursUser
, cursResponseStatus
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createUser' smart constructor.
data CreateUser = CreateUser'
{ _cuPath :: !(Maybe Text)
, _cuUserName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateUser' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cuPath'
--
-- * 'cuUserName'
createUser
:: Text -- ^ 'cuUserName'
-> CreateUser
createUser pUserName_ =
CreateUser'
{ _cuPath = Nothing
, _cuUserName = pUserName_
}
-- | The path for the user name. For more information about paths, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers>
-- in the /Using IAM/ guide.
--
-- This parameter is optional. If it is not included, it defaults to a
-- slash (\/).
cuPath :: Lens' CreateUser (Maybe Text)
cuPath = lens _cuPath (\ s a -> s{_cuPath = a});
-- | The name of the user to create.
cuUserName :: Lens' CreateUser Text
cuUserName = lens _cuUserName (\ s a -> s{_cuUserName = a});
instance AWSRequest CreateUser where
type Rs CreateUser = CreateUserResponse
request = postQuery iAM
response
= receiveXMLWrapper "CreateUserResult"
(\ s h x ->
CreateUserResponse' <$>
(x .@? "User") <*> (pure (fromEnum s)))
instance ToHeaders CreateUser where
toHeaders = const mempty
instance ToPath CreateUser where
toPath = const "/"
instance ToQuery CreateUser where
toQuery CreateUser'{..}
= mconcat
["Action" =: ("CreateUser" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"Path" =: _cuPath, "UserName" =: _cuUserName]
-- | Contains the response to a successful CreateUser request.
--
-- /See:/ 'createUserResponse' smart constructor.
data CreateUserResponse = CreateUserResponse'
{ _cursUser :: !(Maybe User)
, _cursResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateUserResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cursUser'
--
-- * 'cursResponseStatus'
createUserResponse
:: Int -- ^ 'cursResponseStatus'
-> CreateUserResponse
createUserResponse pResponseStatus_ =
CreateUserResponse'
{ _cursUser = Nothing
, _cursResponseStatus = pResponseStatus_
}
-- | Information about the user.
cursUser :: Lens' CreateUserResponse (Maybe User)
cursUser = lens _cursUser (\ s a -> s{_cursUser = a});
-- | The response status code.
cursResponseStatus :: Lens' CreateUserResponse Int
cursResponseStatus = lens _cursResponseStatus (\ s a -> s{_cursResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/CreateUser.hs | mpl-2.0 | 4,370 | 0 | 13 | 950 | 638 | 385 | 253 | 79 | 1 |
-- Copyright (C) 2017 Red Hat, Inc.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, see <http://www.gnu.org/licenses/>.
module Import.URI(appendURI,
baseURI,
isCompsFile,
isPrimaryXMLFile,
showURI,
uriToPath)
where
import Data.List(isInfixOf, isSuffixOf)
import Data.Maybe(fromJust)
import Network.URI(URI(..), escapeURIString, isUnescapedInURI,
parseURIReference, pathSegments, relativeTo, unEscapeString, uriToString)
-- convert a file:// URI to a FilePath
-- This does not check that the URI is a file:// URI, assumes posix-style paths
uriToPath :: URI -> FilePath
uriToPath uri = unEscapeString $ uriPath uri
-- the path is, e.g., /path/to/repo/repodata/primary.xml. Go up one directory.
baseURI :: URI -> URI
baseURI uri = let upOne = fromJust $ parseURIReference ".." in
relativeTo upOne uri
-- append a path to a URI
appendURI :: URI -> String -> Maybe URI
appendURI base path = let
-- Escape the path characters and create a URI reference
relativeURI = parseURIReference $ escapeURIString isUnescapedInURI path
appendToBase = (`relativeTo` base)
in
fmap appendToBase relativeURI
-- Convert a URI to string with no obfuscation
showURI :: URI -> String
showURI uri = uriToString id uri ""
isCompsFile :: URI -> Bool
isCompsFile uri = let path = last (pathSegments uri) in
"-comps" `isInfixOf` path && (".xml" `isSuffixOf` path || ".xml.gz" `isSuffixOf` path)
isPrimaryXMLFile :: URI -> Bool
isPrimaryXMLFile uri = "primary.xml" `isInfixOf` last (pathSegments uri)
| dashea/bdcs | importer/Import/URI.hs | lgpl-2.1 | 2,200 | 0 | 11 | 457 | 352 | 202 | 150 | 27 | 1 |
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
import Control.Monad
import Data.Map as Map hiding (map)
import Numeric
import Data.Char
main = getArgs >>= putStrLn . show . eval . readExpr . (!!0)
readExpr :: String -> LispVal
readExpr input = case parse parseExpr "lisp" input of
Left err -> String $ "No match: " ++ show err
Right val -> val
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
| Character Char
| Array [LispVal]
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> parseString -- begin with "
<|> do char '#'
parseBool <|> parseNumber <|> parseCharacter <|> parseArray
<|> parseDecNumber -- begin with a digit
<|> parseQuoted -- begin with '
<|> parseBackquoted -- begin with `
<|> do char '('
x <- (try parseList) <|> parseDottedList
char ')'
return x
parseString :: Parser LispVal
parseString = do char '"'
x <- many parseChar
char '"'
return $ String x
parseChar :: Parser Char
parseChar = do c <- noneOf "\""
if c == '\\'
then parseEscapedChar -- escaped char
else return c -- other chars
escapedChars :: Map.Map Char Char
escapedChars = Map.fromList [
('\"', '\"'),
('n', '\n'),
('r', '\r'),
('t', '\t'),
('\\', '\\')
]
parseEscapedChar :: Parser Char
parseEscapedChar = do c <- satisfy (`Map.member` escapedChars);
case Map.lookup c escapedChars of
Just x -> return x -- always match
parseAtom :: Parser LispVal
parseAtom = do first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = [first] ++ rest
return $ Atom atom
parseBool :: Parser LispVal
parseBool = do c <- choice $ map char "tf"
return $ case c of
't' -> Bool True
'f' -> Bool False
parseNumber :: Parser LispVal
parseNumber = do base <- choice $ map char "bodx"
liftM (Number . fst . head) $
case base of
'b' -> many1 binDigit >>= return . readBin
'o' -> many1 octDigit >>= return . readOct
'd' -> many1 digit >>= return . readDec
'x' -> many1 hexDigit >>= return . readHex
parseDecNumber :: Parser LispVal
parseDecNumber = liftM (Number . read) $ many1 digit
parseCharacter :: Parser LispVal
parseCharacter = do char '\\'
c <- anyChar
s <- many letter
case map toLower (c:s) of
[a] -> return $ Character a
"space" -> return $ Character ' '
"newline" -> return $ Character '\n'
x -> (unexpected $ "Invalid character name: " ++ x) <?> "\"newline\" or \"space\""
parseArray :: Parser LispVal
parseArray = do char '('
x <- sepBy parseExpr spaces
char ')'
return $ Array x
binDigit :: Parser Char
binDigit = satisfy (`elem` "01")
readBin :: ReadS Integer
readBin = readInt 2 (`elem` "01") digitToInt
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
parseList :: Parser LispVal
parseList = liftM List $ sepBy parseExpr spaces
parseDottedList :: Parser LispVal
parseDottedList = do head <- endBy parseExpr spaces
tail <- char '.' >> spaces >> parseExpr
return $ DottedList head tail
parseQuoted :: Parser LispVal
parseQuoted = do char '\''
x <- parseExpr
return $ List [Atom "quote", x]
parseBackquoted :: Parser LispVal
parseBackquoted = do char '`'
x <- parseExpr
return $ List [Atom "quasiquote", x]
instance Show LispVal where
show (String contents) = "\"" ++ contents ++ "\""
show (Atom name) = name
show (Number contents) = show contents
show (Bool True) = "#t"
show (Bool False) = "#f"
show (List contents) = "(" ++ unwordsList contents ++ ")"
show (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ show tail ++ ")"
unwordsList :: [LispVal] -> String
unwordsList = unwords . map show
eval :: LispVal -> LispVal
eval val@(String _) = val
eval val@(Number _) = val
eval val@(Bool _) = val
eval (List [Atom "quote", val]) = val
| spockwangs/scheme.in.haskell | list4.2.hs | unlicense | 4,857 | 0 | 14 | 1,797 | 1,453 | 727 | 726 | 123 | 4 |
{-# LANGUAGE NoImplicitPrelude #-}
module X02 where
import Protolude
-- http://dev.stephendiehl.com/hask/#phantom-types
-- newtypes to distinguish between plaintext and cryptotext
newtype PlaintextNT = PlaintextNT Text
newtype CryptotextNT = CryptotextNT Text
data Key = Key
encryptNT :: Key -> PlaintextNT -> CryptotextNT
decryptNT :: Key -> CryptotextNT -> PlaintextNT
encryptNT _k (PlaintextNT t) = CryptotextNT t
decryptNT _k (CryptotextNT t) = PlaintextNT t
-- via phantom types
data Cryptotext
data Plaintext
newtype Msg a = Msg Text
encrypt :: Key -> Msg Plaintext -> Msg Cryptotext
decrypt :: Key -> Msg Cryptotext -> Msg Plaintext
encrypt _k (Msg t) = Msg t
decrypt _k (Msg t) = Msg t
-- -XEmptyDataDecls with phantom types that contain no value inhabitants : "anonymous types"
-- {-# LANGUAGE EmptyDataDecls #-}
data Token a
-- The tagged library defines a similar Tagged newtype wrapper.
| haroldcarr/learn-haskell-coq-ml-etc | haskell/topic/phantoms/hc-phantom/src/X02.hs | unlicense | 930 | 0 | 7 | 169 | 196 | 107 | 89 | -1 | -1 |
import Control.Monad
import Data.Bits
import Data.List (foldl')
makeSlice l r =
let blockN n = div n 4
makeBlock n = [n * 4, 1, (n * 4) + 3, 0]
lBlock = drop (mod l 4) $ makeBlock $ blockN l
rBlock = take (1 + (mod r 4)) $ makeBlock $ blockN r
blockDiff = (blockN r) - (blockN l)
twos = replicate (1 + (mod blockDiff 2)) 2
slice x y
| blockN x == blockN y = take (1 + y - x) lBlock
| blockN x == (blockN y) - 1 = lBlock ++ rBlock
| otherwise = lBlock ++ twos ++ rBlock
in slice l r
question :: Int -> Int -> Int
question l r = foldl' xor 0 $ makeSlice l r
readQs :: IO (Int, Int)
readQs = do
[x, y] <- fmap ((take 2) . (map read) . words) getLine
return (x, y)
main = do
q <- readLn
qs <- replicateM q readQs
mapM_ print $ map (uncurry question) qs
| itsbruce/hackerrank | alg/bits/xorSequence.hs | unlicense | 879 | 0 | 15 | 301 | 440 | 218 | 222 | 25 | 1 |
module TypesClasses where
addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z
factorial :: Integer -> Integer
factorial n = product [1..n]
circumference :: Float -> Float
circumference r = 2 * pi * r
circumference' :: Double -> Double
circumference' r = 2 * pi * r
-- :t read
-- read :: Read a => String -> a
-- [function] :: [class constraint 1], ..., [class constraint m] => [ parameter 1 ] -> ... -> [ parameter n] -> [ result ]
-- :: can be used as a means of type coercion, in case the compiler cannot resolve ambiguity
-- read "5" :: Int
-- Helpful typeclasses: Show, Read; Enum, Bounded; Num, Integral, Floating | mboogerd/hello-haskell | src/lyah/TypesClasses.hs | apache-2.0 | 640 | 0 | 7 | 137 | 122 | 67 | 55 | 9 | 1 |
{-
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Main where
import Control.Exception.Base
import Control.Monad
import Data.Array.IO
import qualified Data.Char as Char
import qualified Data.Logic.Propositional as Prop
import qualified Data.Logic.Propositional.NormalForms as NormalForms
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import qualified Data.Tuple as Tuple
import MiniSat
import System.Environment
import System.IO
import System.Process
import System.Random
import Text.ParserCombinators.Parsec
import Text.Parsec.Combinator
------------------------------------ Types ------------------------------------
{-
An Entailment is a struct containing:
two propositions A and B
whether A entails B (written A ⊧ B)
three statistics (used as simple heuristic estimates):
whether length(A) >= length(B)
whether vars(B) ⊆ vars(A)
whether literals(B*) ⊆ literals(A*)
where A* is negation-normal-form version of A
-}
type Entailment = (Prop.Expr, Prop.Expr, Int, Int, Int, Int)
{-
A FourTuple is four propositions (A, B, A*, B*) such that:
A ⊧ B
A* ⊧ B*
A ⊭ B*
A* ⊭ B
-}
type FourTuple = (Prop.Expr, Prop.Expr, Prop.Expr, Prop.Expr)
------------------------------------ main -----------------------------------
{-
Usage:
first argument: number of pairs to generate
second argument: max number of variables in a formula
third argument: max complexity of a formula
NB four-tuples are extracted from generated pairs.
But many pairs are unsuitable for four-tuples.
So if you want 100 entailment lines, you need 100/4 = 25 four-tuples,
and you might need 200 pairs to produce 25 four-tuples.
(The ratio of pairs-to-four-tuples depends on the complexity of the formulas)
-}
main :: IO ()
main = do
args <- getArgs
case args of
[] -> make_four_tuples 100 20 30
[ns] -> do
let n = read ns :: Int
make_four_tuples n 20 30
[ns, vs] -> do
let n = read ns :: Int
let v = read vs :: Int
make_four_tuples n v 30
[ns, vs, ks] -> do
let n = read ns :: Int
let v = read vs :: Int
let k = read ks :: Int
make_four_tuples n v k
------------------------------------ Generation -------------------------------
gen_formula :: RandomGen r => r -> Int -> [Char] -> (Prop.Expr, r)
gen_formula r complexity vs = gen_f r complexity vs
gen_f :: RandomGen r => r -> Int -> [Char] -> (Prop.Expr, r)
gen_f r 0 vs = gen_atom r vs
gen_f r n vs = f r3 where
n1 = n - 1
(na, r2) = pick [0 .. n1] r
nb = n1 - na
(f, r3) = pick [gen_unary Prop.Negation n1 vs,
gen_binary Prop.Conjunction na nb vs,
gen_binary Prop.Disjunction na nb vs,
gen_binary Prop.Conditional na nb vs] r2
gen_atom :: RandomGen r => r -> [Char] -> (Prop.Expr, r)
gen_atom r vs = (Prop.Variable (Prop.Var v), r2) where
(v, r2) = pick vs r
gen_unary :: RandomGen r => (Prop.Expr -> Prop.Expr) -> Int -> [Char] -> r -> (Prop.Expr, r)
gen_unary f n vs r = (f p, r') where
(p, r') = gen_f r n vs
gen_binary :: RandomGen r => (Prop.Expr -> Prop.Expr -> Prop.Expr) -> Int -> Int -> [Char] -> r -> (Prop.Expr, r)
gen_binary f na nb vs r = (f p q, r3) where
(p, r2) = gen_f r na vs
(q, r3) = gen_f r2 nb vs
alphabet :: [Char]
alphabet = ['a'..'z']
make_exprs :: Int -> Int -> Int -> Int -> IO (Prop.Expr, Prop.Expr)
make_exprs c1 c2 num_vars n = do
r <- newStdGen
let (vs, _, r2) = take_n alphabet num_vars r
let (p1, r3) = gen_formula r2 c1 vs
let (p2, _) = gen_formula r3 c2 vs
return (p1, p2)
pick :: RandomGen r => [a] -> r -> (a, r)
pick [] _ = error "pick wrongly given empty list"
pick as r =
let indices = (0, length as-1)
(i, r') = randomR indices r
in (as !! i, r')
pick_freq :: RandomGen r => [(Int, a)] -> r -> (a, r)
pick_freq [] _ = error "pick_freq wrongly given empty list"
pick_freq as r = (pick_n n as, r') where
(n, r') = randomR (0, tot-1) r
tot = List.foldl' (\b -> (\(a,_) -> a + b)) 0 as
pick_n :: Int -> [(Int, a)] -> a
pick_n _ [] = error "Empty list"
pick_n x ((y,a):_) | x < y = a
pick_n x ((y,_):ps) | otherwise = pick_n (x-y) ps
pick_take :: RandomGen r => [a] -> r -> (a, [a], r)
pick_take [] _ = error "pick_take wrongly given empty list"
pick_take as r =
let indices = (0, length as-1)
(i, r') = randomR indices r
in (as !! i, take i as ++ drop (i+1) as, r')
take_n :: RandomGen r => [a] -> Int -> r -> ([a], [a], r)
take_n as n r = take_n2 as n r []
take_n2 :: RandomGen r => [a] -> Int -> r -> [a] -> ([a], [a], r)
take_n2 as n r acc | length acc == n = (acc, as, r)
take_n2 as n r acc | otherwise = take_n2 as' n r' (a:acc) where
(a, as', r') = pick_take as r
------------------------------------ Entails ----------------------------------
entails :: Prop.Expr -> Prop.Expr -> IO Bool
entails a b = do
let p = Prop.Conjunction a (Prop.Negation b)
b <- sat p
return (not b)
equiv :: Prop.Expr -> Prop.Expr -> IO Bool
equiv a b = do
let p = Prop.Conjunction a (Prop.Negation b)
let q = Prop.Conjunction b (Prop.Negation a)
b <- sat (Prop.Disjunction p q)
return (not b)
sat :: Prop.Expr -> IO Bool
sat p = do
let (n, cs) = convert_to_dimacs p
s <- make_solver cs n
b <- solve s []
deleteSolver s
return b
convert_to_dimacs :: Prop.Expr -> (Int, [[Int]])
convert_to_dimacs = expr_to_dimacs . toCNF
toCNF :: Prop.Expr -> Prop.Expr
toCNF = fixed_point NormalForms.toCNF
fixed_point :: Eq a => (a->a) -> a -> a
fixed_point f a =
if f a == a then a
else fixed_point f (f a)
expr_to_dimacs :: Prop.Expr -> (Int, [[Int]])
expr_to_dimacs e = to_dimacs e (zip (extract_vars e) [1..])
to_dimacs :: Prop.Expr -> [(Char, Int)] -> (Int, [[Int]])
to_dimacs e m = (length m, to_dimacs_c e m)
to_dimacs_c :: Prop.Expr -> [(Char, Int)] -> [[Int]]
to_dimacs_c (Prop.Variable (Prop.Var c)) m = case lookup c m of
Just i -> [[i]]
to_dimacs_c (Prop.Negation (Prop.Variable (Prop.Var c))) m = case lookup c m of
Just i -> [[-i]]
to_dimacs_c (Prop.Conjunction p q) m = to_dimacs_c p m ++ to_dimacs_c q m
to_dimacs_c (Prop.Disjunction p q) m = [to_dimacs_d p m ++ to_dimacs_d q m]
to_dimacs_d :: Prop.Expr -> [(Char, Int)] -> [Int]
to_dimacs_d (Prop.Variable (Prop.Var c)) m = case lookup c m of
Just i -> [i]
to_dimacs_d (Prop.Negation (Prop.Variable (Prop.Var c))) m = case lookup c m of
Just i -> [-i]
to_dimacs_d (Prop.Disjunction p q) m = to_dimacs_d p m ++ to_dimacs_d q m
extract_vars :: Prop.Expr -> [Char]
extract_vars e = List.sort (List.nub (f e)) where
f (Prop.Variable (Prop.Var c)) = [c]
f (Prop.Negation p) = f p
f (Prop.Conjunction p q ) = f p ++ f q
f (Prop.Disjunction p q ) = f p ++ f q
f (Prop.Conditional p q ) = f p ++ f q
make_solver:: [[Int]] -> Int -> (IO Solver)
make_solver baseClauses vars = do
s <- newSolver
literals <- sequence [newLit s | i <- [1..vars]]
sequence_ $ map ( (addClause s).(toLits)) baseClauses
return s
toLits :: [Int] -> [Lit]
toLits xs = map lit' xs where
lit' x | x > 0 = minisat_mkLit $ MkVar (fromIntegral (x-1))
lit' x | x < 0 = neg $ minisat_mkLit $ MkVar (fromIntegral (abs x - 1))
------------------------------------ show -------------------------------------
showF :: Prop.Expr -> String
showF (Prop.Variable (Prop.Var c)) = [c]
showF (Prop.Negation p) = "~(" ++ showF p ++ ")"
showF (Prop.Conjunction p q) = "(" ++ showF p ++ "&" ++ showF q ++ ")"
showF (Prop.Disjunction p q) = "(" ++ showF p ++ "|" ++ showF q ++ ")"
showF (Prop.Conditional p q) = "(" ++ showF p ++ ">" ++ showF q ++ ")"
------------------------------------ check ------------------------------------
verify_dataset :: String -> IO ()
verify_dataset f = do
ts <- parse_file f
forM_ ts $ \(a, b, e, _, _, _) -> do
let not_e = e == 0
not_entails <- sat (Prop.Conjunction a (Prop.Negation b))
putStrLn $ "Verifying " ++ show a ++ ", " ++ show b ++ ", " ++ show e
case not_entails == not_e of
True -> return ()
False -> do
putStrLn $ "Problem with " ++ show a ++ ", " ++ show b ++ ", " ++ show e
error "Error"
putStrLn "Ok"
------------------------------------ Parsing ----------------------------------
parse_file :: String -> IO [Entailment]
parse_file f = do
x <- readFile f
case (parse file f x) of
Left e -> do
putStrLn $ "Parse error: " ++ show e
return []
Right rs -> do
return rs
file :: Parser [Entailment]
file = spaces >> parse_triples
parse_triples :: Parser [Entailment]
parse_triples = many1 parse_triple
parse_triple :: Parser Entailment
parse_triple = do
p <- parse_formula
lexeme ","
q <- parse_formula
lexeme ","
n <- parse_int
lexeme ","
h1 <- parse_int
lexeme ","
h2 <- parse_int
lexeme ","
h3 <- parse_int
return (p, q, n, h1, h2, h3)
parse_formula :: Parser Prop.Expr
parse_formula = do
e <- Text.ParserCombinators.Parsec.try parse_negation <|>
Text.ParserCombinators.Parsec.try parse_conjunction <|>
Text.ParserCombinators.Parsec.try parse_disjunction <|>
Text.ParserCombinators.Parsec.try parse_implication <|>
parse_atom
return e
comma = lexeme ","
parse_atom :: Parser Prop.Expr
parse_atom = do
a <- identifierSymbol
return $ Prop.Variable (Prop.Var a)
identifierSymbol :: Parser Char
identifierSymbol = alphaNum <|> (char '_')
parse_negation :: Parser Prop.Expr
parse_negation = do
lexeme "~"
lexeme "("
p <- parse_formula
lexeme ")"
return $ Prop.Negation p
parse_conjunction :: Parser Prop.Expr
parse_conjunction = do
lexeme "("
p <- parse_formula
lexeme "&"
q <- parse_formula
lexeme ")"
return $ Prop.Conjunction p q
parse_disjunction :: Parser Prop.Expr
parse_disjunction = do
lexeme "("
p <- parse_formula
lexeme "|"
q <- parse_formula
lexeme ")"
return $ Prop.Disjunction p q
parse_implication :: Parser Prop.Expr
parse_implication = do
lexeme "("
p <- parse_formula
lexeme ">"
q <- parse_formula
lexeme ")"
return $ Prop.Conditional p q
parse_int :: Parser Int
parse_int = do
e <- Text.ParserCombinators.Parsec.try parse_1 <|> parse_0
return e
parse_1 :: Parser Int
parse_1 = do
lexeme "1"
return 1
parse_0 :: Parser Int
parse_0 = do
lexeme "0"
return 0
lexeme :: String -> Parser String
lexeme s = do
string s
spaces
return s
------------------------------------ de Bruijn --------------------------------
type SymbolMap = [(Prop.Var, Int)]
deBruijn :: (Prop.Expr, SymbolMap) -> (Prop.Expr, SymbolMap)
deBruijn (Prop.Negation p, m) = (Prop.Negation p', m') where (p', m') = deBruijn (p, m)
deBruijn (Prop.Conjunction p q, m) = (Prop.Conjunction p' q', m'') where
(p', m') = deBruijn (p, m)
(q', m'') = deBruijn (q, m')
deBruijn (Prop.Disjunction p q, m) = (Prop.Disjunction p' q', m'') where
(p', m') = deBruijn (p, m)
(q', m'') = deBruijn (q, m')
deBruijn (Prop.Conditional p q, m) = (Prop.Conditional p' q', m'') where
(p', m') = deBruijn (p, m)
(q', m'') = deBruijn (q, m')
deBruijn (Prop.Variable p, m) = case lookup p m of
Nothing -> (Prop.Variable p', m') where
n = length m + 1
p' = Prop.Var (Char.chr n)
m' = (p, n) : m
Just n -> (Prop.Variable p', m) where
p' = Prop.Var (Char.chr n)
------------------------------------ Alpha-Equivalence ------------------------
build_set :: String -> IO (Set.Set (Prop.Expr, Prop.Expr))
build_set f = do
ts <- parse_file f
let fs = List.foldl' add_triple Set.empty ts
return fs
add_triple :: Set.Set (Prop.Expr, Prop.Expr) -> Entailment -> Set.Set (Prop.Expr, Prop.Expr)
add_triple s (p,q,_,_,_,_) = Set.insert (p',q') s where
(p', m) = deBruijn (p, [])
(q', _) = deBruijn (q, m)
check_triple :: Set.Set (Prop.Expr, Prop.Expr) -> String -> Entailment -> IO ()
check_triple s f (a,b,n,h1,h2,h3) = do
let (a', m) = deBruijn (a, [])
let (b', _) = deBruijn (b, m)
case Set.member (a',b') s of
True -> putStrLn $ "Redundant: " ++ showF a ++ "," ++ showF b
False -> appendFile f $ showF a ++ "," ++ showF b ++ "," ++ show n ++ "," ++ show h1 ++ "," ++ show h2 ++ "," ++ show h3 ++ "\n"
filter_alpha_equivalences :: String -> String -> String -> IO ()
filter_alpha_equivalences training test results = do
s <- build_set training
ts <- parse_file test
forM_ ts (check_triple s results)
instance Ord Prop.Expr where
compare (Prop.Variable p) (Prop.Variable q) = compare p q
compare (Prop.Variable _) (Prop.Negation _) = LT
compare (Prop.Variable _) (Prop.Conjunction _ _) = LT
compare (Prop.Variable _) (Prop.Disjunction _ _) = LT
compare (Prop.Variable _) (Prop.Conditional _ _) = LT
compare (Prop.Negation _) (Prop.Variable _) = GT
compare (Prop.Negation p) (Prop.Negation q) = compare p q
compare (Prop.Negation _) (Prop.Conjunction _ _) = LT
compare (Prop.Negation _) (Prop.Disjunction _ _) = LT
compare (Prop.Negation _) (Prop.Conditional _ _) = LT
compare (Prop.Conjunction _ _) (Prop.Variable _) = GT
compare (Prop.Conjunction _ _) (Prop.Negation _) = GT
compare (Prop.Conjunction p q) (Prop.Conjunction p' q') = compare (p,q) (p',q')
compare (Prop.Conjunction _ _) (Prop.Disjunction _ _) = LT
compare (Prop.Conjunction _ _) (Prop.Conditional _ _) = LT
compare (Prop.Disjunction _ _) (Prop.Variable _) = GT
compare (Prop.Disjunction _ _) (Prop.Negation _) = GT
compare (Prop.Disjunction _ _) (Prop.Conjunction _ _) = GT
compare (Prop.Disjunction p q) (Prop.Disjunction p' q') = compare (p,q) (p',q')
compare (Prop.Disjunction _ _) (Prop.Conditional _ _) = LT
compare (Prop.Conditional _ _) (Prop.Variable _) = GT
compare (Prop.Conditional _ _) (Prop.Negation _) = GT
compare (Prop.Conditional _ _) (Prop.Conjunction _ _) = GT
compare (Prop.Conditional _ _) (Prop.Disjunction _ _) = GT
compare (Prop.Conditional p q) (Prop.Conditional p' q') = compare (p,q) (p',q')
------------------------------------ Simple Baselines -------------------------
subset :: (Eq a) => [a] -> [a] -> Bool
subset a b = all (`elem` b) a
prop_length :: Prop.Expr -> Int
prop_length (Prop.Variable _) = 1
prop_length (Prop.Negation p) = prop_length p + 1
prop_length (Prop.Conjunction p q) = prop_length p + prop_length q + 1
prop_length (Prop.Disjunction p q) = prop_length p + prop_length q + 1
prop_length (Prop.Conditional p q) = prop_length p + prop_length q + 1
prop_length (Prop.Biconditional p q) = prop_length p + prop_length q + 1
heuristic_1 :: Prop.Expr -> Prop.Expr -> Int
heuristic_1 a b = case prop_length a >= prop_length b of
True -> 1
False -> 0
heuristic_2 :: Prop.Expr -> Prop.Expr -> Int
heuristic_2 a b = case Prop.variables b `subset` Prop.variables a of
True -> 1
False -> 0
heuristic_3 :: Prop.Expr -> Prop.Expr -> Int
heuristic_3 a b = case ls_b `subset` ls_a of
True -> 1
False -> 0
where
ls_a = literals (fixed_point NormalForms.toNNF a)
ls_b = literals (fixed_point NormalForms.toNNF b)
literals :: Prop.Expr -> [(Prop.Var, Bool)]
literals (Prop.Variable p) = [(p, True)]
literals (Prop.Negation (Prop.Variable p)) = [(p, False)]
literals (Prop.Conjunction p q) = List.nub $ literals p ++ literals q
literals (Prop.Disjunction p q) = List.nub $ literals p ++ literals q
literals (Prop.Conditional p q) = List.nub $ literals p ++ literals q
literals (Prop.Biconditional p q) = List.nub $ literals p ++ literals q
------------------------------------ Baselines Stats -------------------------
get_stats :: String -> IO ()
get_stats f = do
ts <- parse_file f
(stat1, stat2, stat3, stat4, stat5) <- foldM accumulate_stat (0, 0, 0, 0, 0) ts
putStrLn $ "Heuristic 1: " ++ show stat1 ++ " / " ++ show (length ts)
putStrLn $ "Heuristic 2: " ++ show stat2 ++ " / " ++ show (length ts)
putStrLn $ "Heuristic 3: " ++ show stat3 ++ " / " ++ show (length ts)
putStrLn $ "Proportion of tautologies: " ++ show stat4 ++ " / " ++ show (length ts)
putStrLn $ "Proportion of satisfiable Bs: " ++ show stat5 ++ " / " ++ show (length ts)
accumulate_stat :: (Int, Int, Int, Int, Int) -> Entailment -> IO (Int, Int, Int, Int, Int)
accumulate_stat (s1, s2, s3, s4, s5) (_, b, entails, h1, h2, h3) = do
let s1' = if h1 == entails then s1 + 1 else s1
let s2' = if h2 == entails then s2 + 1 else s2
let s3' = if h3 == entails then s3 + 1 else s3
not_is_tautology_b <- sat (Prop.Negation b)
let s4' = if not_is_tautology_b then s4 else s4 + 1
satisfiable_b <- sat b
let s5' = if satisfiable_b then s5 + 1 else s5
return (s1', s2', s3', s4', s5')
------------------------------------ Bias Stats -------------------------------
bias_stats :: String -> IO ()
bias_stats f = do
ts <- parse_file f
print_stats ts prop_length "length"
print_stats ts num_vars "num vars"
print_stats2 ts num_new_vars "new vars"
print_stats ts num_negs "num negs"
print_stats ts num_conjs "num conjs"
print_stats ts num_disjs "num disjs"
print_stats ts num_imps "num imps"
print_stats ts count_sats "num satisfying TVAs"
print_stats ts (num_negs_at_level 0) "negs at level 0"
print_stats ts (num_negs_at_level 1) "negs at level 1"
print_stats ts (num_negs_at_level 2) "negs at level 2"
print_stats ts (num_conjs_at_level 0) "conjs at level 0"
print_stats ts (num_conjs_at_level 1) "conjs at level 1"
print_stats ts (num_conjs_at_level 2) "conjs at level 2"
print_stats ts (num_disjs_at_level 0) "disjs at level 0"
print_stats ts (num_disjs_at_level 1) "disjs at level 1"
print_stats ts (num_disjs_at_level 2) "disjs at level 2"
print_stats :: [Entailment] -> (Prop.Expr -> Int) -> String -> IO ()
print_stats ts f s = do
let (dist1, dist0) = List.foldl' (accumulate_bias_a f) (Map.empty, Map.empty) ts
let (m1, m2) = (mean dist1, mean dist0)
putStrLn $ "Mean " ++ s ++ " for A: " ++ show m1
putStrLn $ "Mean " ++ s ++ " for A*: " ++ show m2
putStrLn $ "Chi-squared for " ++ s ++ " is: " ++ show (chi_squared dist1 dist0)
let (dist1, dist0) = List.foldl' (accumulate_bias_b f) (Map.empty, Map.empty) ts
let (m1, m2) = (mean dist1, mean dist0)
putStrLn $ "Mean " ++ s ++ " for B: " ++ show m1
putStrLn $ "Mean " ++ s ++ " for B*: " ++ show m2
putStrLn $ "Chi-squared for " ++ s ++ " is: " ++ show (chi_squared dist1 dist0)
print_stats2 :: [Entailment] -> (Prop.Expr -> Prop.Expr -> Int) -> String -> IO ()
print_stats2 ts f s = do
let (dist1, dist0) = List.foldl' (accumulate_bias2 f) (Map.empty, Map.empty) ts
let (m1, m2) = (mean dist1, mean dist0)
putStrLn $ "Mean " ++ s ++ " for B: " ++ show m1
putStrLn $ "Mean " ++ s ++ " for B*: " ++ show m2
putStrLn $ "Chi-squared for " ++ s ++ " is: " ++ show (chi_squared dist1 dist0)
chi_squared :: Map.Map Int Int -> Map.Map Int Int -> (Float, Int)
chi_squared m1 m2 = (sum (map f all_keys), length all_keys) where
all_keys = List.sort (List.nub (Map.keys m1 ++ Map.keys m2))
f i = case (Map.lookup i m1, Map.lookup i m2) of
(Nothing, Nothing) -> 0.0
(Nothing, Just s_i) -> fromIntegral s_i
(Just r_i, Nothing) -> fromIntegral r_i
(Just r_i, Just s_i) -> g (fromIntegral r_i) (fromIntegral s_i)
g x y = (x - y)**2 / (x+y)
mean :: Map.Map Int Int -> Float
mean m = total / count where
m_l = Map.toList m
count = sum (map (fromIntegral . snd) m_l) :: Float
total = sum (map (\(a,b) -> (fromIntegral (a * b))) m_l) :: Float
accumulate_bias_a :: (Prop.Expr -> Int) -> (Map.Map Int Int, Map.Map Int Int) -> Entailment -> (Map.Map Int Int, Map.Map Int Int)
accumulate_bias_a f (pos_dist, neg_dist) (a, _, 1, _, _, _) = (update_count f pos_dist a, neg_dist)
accumulate_bias_a f (pos_dist, neg_dist) (a, _, 0, _, _, _) = (pos_dist, update_count f neg_dist a)
accumulate_bias_b :: (Prop.Expr -> Int) -> (Map.Map Int Int, Map.Map Int Int) -> Entailment -> (Map.Map Int Int, Map.Map Int Int)
accumulate_bias_b f (pos_dist, neg_dist) (_, b, 1, _, _, _) = (update_count f pos_dist b, neg_dist)
accumulate_bias_b f (pos_dist, neg_dist) (_, b, 0, _, _, _) = (pos_dist, update_count f neg_dist b)
accumulate_bias2 :: (Prop.Expr -> Prop.Expr -> Int) -> (Map.Map Int Int, Map.Map Int Int) -> Entailment -> (Map.Map Int Int, Map.Map Int Int)
accumulate_bias2 f (pos_dist, neg_dist) (a, b, 1, _, _, _) = (update_count2 f pos_dist a b, neg_dist)
accumulate_bias2 f (pos_dist, neg_dist) (a, b, 0, _, _, _) = (pos_dist, update_count2 f neg_dist a b)
update_count :: (Prop.Expr -> Int) -> Map.Map Int Int -> Prop.Expr -> Map.Map Int Int
update_count f m b = case Map.lookup l m of
Nothing -> Map.insert l 1 m
Just n -> Map.insert l (n+1) m
where l = f b
update_count2 :: (Prop.Expr -> Prop.Expr -> Int) -> Map.Map Int Int -> Prop.Expr -> Prop.Expr -> Map.Map Int Int
update_count2 f m a b = case Map.lookup l m of
Nothing -> Map.insert l 1 m
Just n -> Map.insert l (n+1) m
where l = f a b
num_vars :: Prop.Expr -> Int
num_vars = length . extract_vars
num_new_vars :: Prop.Expr -> Prop.Expr -> Int
num_new_vars a b = length (extract_vars b List.\\ extract_vars a)
num_negs :: Prop.Expr -> Int
num_negs (Prop.Variable _) = 0
num_negs (Prop.Negation p) = num_negs p + 1
num_negs (Prop.Conjunction p q) = num_negs p + num_negs q
num_negs (Prop.Disjunction p q) = num_negs p + num_negs q
num_negs (Prop.Conditional p q) = num_negs p + num_negs q
num_negs (Prop.Biconditional p q) = num_negs p + num_negs q
num_conjs :: Prop.Expr -> Int
num_conjs (Prop.Variable _) = 0
num_conjs (Prop.Negation p) = num_conjs p
num_conjs (Prop.Conjunction p q) = num_conjs p + num_conjs q + 1
num_conjs (Prop.Disjunction p q) = num_conjs p + num_conjs q
num_conjs (Prop.Conditional p q) = num_conjs p + num_conjs q
num_conjs (Prop.Biconditional p q) = num_conjs p + num_conjs q
num_disjs :: Prop.Expr -> Int
num_disjs (Prop.Variable _) = 0
num_disjs (Prop.Negation p) = num_disjs p
num_disjs (Prop.Conjunction p q) = num_disjs p + num_disjs q
num_disjs (Prop.Disjunction p q) = num_disjs p + num_disjs q + 1
num_disjs (Prop.Conditional p q) = num_disjs p + num_disjs q
num_disjs (Prop.Biconditional p q) = num_disjs p + num_disjs q
num_imps :: Prop.Expr -> Int
num_imps (Prop.Variable _) = 0
num_imps (Prop.Negation p) = num_imps p
num_imps (Prop.Conjunction p q) = num_imps p + num_imps q
num_imps (Prop.Disjunction p q) = num_imps p + num_imps q
num_imps (Prop.Conditional p q) = num_imps p + num_imps q + 1
num_imps (Prop.Biconditional p q) = num_imps p + num_imps q
num_negs_at_level :: Int -> Prop.Expr -> Int
num_negs_at_level level p = num_negs_at_level2 p level 0
num_negs_at_level2 :: Prop.Expr -> Int -> Int -> Int
num_negs_at_level2 (Prop.Variable _) _ _ = 0
num_negs_at_level2 (Prop.Negation _) level current | level == current = 1
num_negs_at_level2 (Prop.Negation _) level current | level < current = 0
num_negs_at_level2 (Prop.Negation p) level current | level > current = num_negs_at_level2 p level (current+1)
num_negs_at_level2 (Prop.Conjunction _ _) level current | level <= current = 0
num_negs_at_level2 (Prop.Conjunction p q) level current | level > current =
num_negs_at_level2 p level (current+1) + num_negs_at_level2 q level (current+1)
num_negs_at_level2 (Prop.Disjunction _ _) level current | level <= current = 0
num_negs_at_level2 (Prop.Disjunction p q) level current | level > current =
num_negs_at_level2 p level (current+1) + num_negs_at_level2 q level (current+1)
num_negs_at_level2 (Prop.Conditional _ _) level current | level <= current = 0
num_negs_at_level2 (Prop.Conditional p q) level current | level > current =
num_negs_at_level2 p level (current+1) + num_negs_at_level2 q level (current+1)
num_conjs_at_level :: Int -> Prop.Expr -> Int
num_conjs_at_level level p = num_conjs_at_level2 p level 0
num_conjs_at_level2 :: Prop.Expr -> Int -> Int -> Int
num_conjs_at_level2 (Prop.Variable _) _ _ = 0
num_conjs_at_level2 (Prop.Negation _) level current | level <= current = 0
num_conjs_at_level2 (Prop.Negation p) level current | level > current = num_conjs_at_level2 p level (current+1)
num_conjs_at_level2 (Prop.Conjunction _ _) level current | level == current = 1
num_conjs_at_level2 (Prop.Conjunction _ _) level current | level < current = 0
num_conjs_at_level2 (Prop.Conjunction p q) level current | level > current =
num_conjs_at_level2 p level (current+1) + num_conjs_at_level2 q level (current+1)
num_conjs_at_level2 (Prop.Disjunction _ _) level current | level <= current = 0
num_conjs_at_level2 (Prop.Disjunction p q) level current | level > current =
num_conjs_at_level2 p level (current+1) + num_conjs_at_level2 q level (current+1)
num_conjs_at_level2 (Prop.Conditional _ _) level current | level <= current = 0
num_conjs_at_level2 (Prop.Conditional p q) level current | level > current =
num_conjs_at_level2 p level (current+1) + num_conjs_at_level2 q level (current+1)
num_disjs_at_level :: Int -> Prop.Expr -> Int
num_disjs_at_level level p = num_disjs_at_level2 p level 0
num_disjs_at_level2 :: Prop.Expr -> Int -> Int -> Int
num_disjs_at_level2 (Prop.Variable _) _ _ = 0
num_disjs_at_level2 (Prop.Negation _) level current | level <= current = 0
num_disjs_at_level2 (Prop.Negation p) level current | level > current = num_disjs_at_level2 p level (current+1)
num_disjs_at_level2 (Prop.Disjunction _ _) level current | level == current = 1
num_disjs_at_level2 (Prop.Disjunction _ _) level current | level < current = 0
num_disjs_at_level2 (Prop.Disjunction p q) level current | level > current =
num_disjs_at_level2 p level (current+1) + num_disjs_at_level2 q level (current+1)
num_disjs_at_level2 (Prop.Conjunction _ _) level current | level <= current = 0
num_disjs_at_level2 (Prop.Conjunction p q) level current | level > current =
num_disjs_at_level2 p level (current+1) + num_disjs_at_level2 q level (current+1)
num_disjs_at_level2 (Prop.Conditional _ _) level current | level <= current = 0
num_disjs_at_level2 (Prop.Conditional p q) level current | level > current =
num_disjs_at_level2 p level (current+1) + num_disjs_at_level2 q level (current+1)
------------------------------------ Counting Sats ----------------------------
type TVA = [(Char, Bool)]
getTVAs :: [Char] -> [TVA]
getTVAs vars =
let bs = getBools (length vars)
f b = zip vars b
in map f bs
getBools :: Int -> [[Bool]]
getBools 0 = [[]]
getBools n =
let p = getBools (n-1)
lhs = map (False :) p
rhs = map (True :) p
in lhs ++ rhs
getTable :: Prop.Expr -> [TVA]
getTable p =
let vs = extract_vars p
in getTVAs vs
satProp :: TVA -> Prop.Expr -> Bool
satProp tva (Prop.Variable (Prop.Var p)) = case lookup p tva of
Nothing -> error "Unexpected"
Just b -> b
satProp tva (Prop.Negation p) = not (satProp tva p)
satProp tva (Prop.Conjunction p q) = (satProp tva p) && (satProp tva q)
satProp tva (Prop.Disjunction p q) = (satProp tva p) || (satProp tva q)
satProp tva (Prop.Conditional p q) = (not $ satProp tva p) || (satProp tva q)
count_sats :: Prop.Expr -> Int
count_sats p = length (filter (\tva -> satProp tva p) (getTable p))
------------------------------------ four-tuples ------------------------------
create_four_tuples :: Int -> Int -> Int -> IO [FourTuple]
create_four_tuples n v k = do
pairs <- make_pairs n v k
extract_four_tuples pairs []
make_pairs :: Int -> Int -> Int -> IO [(Prop.Expr, Prop.Expr)]
make_pairs n v k = do
putStrLn $ "Creating " ++ show n ++ " pairs..."
r <- newStdGen
let (num_vars, r2) = randomR (1,v) r
let (vs, _, r2) = take_n alphabet num_vars r
make_pairs2 n k vs []
make_pairs2 :: Int -> Int -> [Char] -> [(Prop.Expr, Prop.Expr)] -> IO [(Prop.Expr, Prop.Expr)]
make_pairs2 n _ _ xs | length xs >= n = return xs
make_pairs2 n k vs acc = do
r <- newStdGen
let (c1, r2) = randomR (k `div` 3, k) r
let (c2, r3) = randomR (k `div` 3, k) r2
(e1, e2) <- make_pair c1 c2 vs
is_entails <- e1 `entails` e2
case is_entails of
True -> make_pairs2 n k vs ((e1, e2) : acc)
False -> make_pairs2 n k vs acc
extract_four_tuples :: [(Prop.Expr, Prop.Expr)] -> [FourTuple] -> IO [FourTuple]
extract_four_tuples [] acc = return acc
extract_four_tuples ((a,b) : ps) acc = do
x <- find_other_pair (a,b) ps []
case x of
Just ((a',b'), ps') -> extract_four_tuples ps' ((a, b, a', b'):acc)
Nothing -> extract_four_tuples ps acc
find_other_pair :: (Prop.Expr, Prop.Expr) -> [(Prop.Expr, Prop.Expr)] -> [(Prop.Expr, Prop.Expr)] -> IO (Maybe ((Prop.Expr, Prop.Expr), [(Prop.Expr, Prop.Expr)]))
find_other_pair _ [] acc = return Nothing
find_other_pair (a,b) ((a', b') : ps) acc = do
x <- valid_four_tuple (a,b) (a', b')
case x of
True -> return $ Just ((a', b'), acc ++ ps)
False -> find_other_pair (a, b) ps ((a', b') : acc)
valid_four_tuple :: (Prop.Expr, Prop.Expr) -> (Prop.Expr, Prop.Expr) -> IO Bool
valid_four_tuple (a, b) (a', b') = do
let p1 = Prop.Conjunction a (Prop.Negation b')
let p2 = Prop.Conjunction a' (Prop.Negation b)
s1 <- sat p1
s2 <- sat p2
return (s1 && s2)
output_file :: String
output_file = "four_tuples.txt"
write_four_tuples :: [FourTuple] -> IO ()
write_four_tuples fts = forM_ fts $ \(a, b, a2, b2) -> do
let a' = showF a
let b' = showF b
let a2' = showF a2
let b2' = showF b2
--putStrLn "Four-tuple found"
--putStrLn a'
--putStrLn b'
--putStrLn a2'
--putStrLn b2'
--putStrLn "---"
let file = output_file
let baselines_ab = show (heuristic_1 a b) ++ "," ++ show (heuristic_2 a b) ++ "," ++ show (heuristic_3 a b)
appendFile file $ a' ++ "," ++ b' ++ ",1," ++ baselines_ab ++ "\n"
let baselines_a2b2 = show (heuristic_1 a2 b2) ++ "," ++ show (heuristic_2 a2 b2) ++ "," ++ show (heuristic_3 a2 b2)
appendFile file $ a2' ++ "," ++ b2' ++ ",1," ++ baselines_a2b2 ++ "\n"
let baselines_ab2 = show (heuristic_1 a b2) ++ "," ++ show (heuristic_2 a b2) ++ "," ++ show (heuristic_3 a b2)
appendFile file $ a' ++ "," ++ b2' ++ ",0," ++ baselines_ab2 ++ "\n"
let baselines_a2b = show (heuristic_1 a2 b) ++ "," ++ show (heuristic_2 a2 b) ++ "," ++ show (heuristic_3 a2 b)
appendFile file $ a2' ++ "," ++ b' ++ ",0," ++ baselines_a2b ++ "\n"
make_four_tuples :: Int -> Int -> Int -> IO ()
make_four_tuples n v k = do
fts <- create_four_tuples n v k
putStrLn $ "There were " ++ show (length fts) ++ " four-tuples found."
putStrLn $ "They produce " ++ show (4 * length fts) ++ " lines."
write_four_tuples fts
putStrLn $ "Output written (appended) to " ++ output_file
make_pair :: Int -> Int -> [Char] -> IO (Prop.Expr, Prop.Expr)
make_pair c1 c2 vs = do
r2 <- newStdGen
let (p1, r3) = gen_formula r2 c1 vs
let (p2, _) = gen_formula r3 c2 vs
return (p1, p2)
average_length = average_stats length_triple
average_num_vars = average_stats num_vars_triple
average_num_ops = average_stats num_ops_triple
average_power_two_num_vars = average_stats power_two_num_vars_triple
average_stats :: (Int -> Entailment -> Int) -> String -> IO Float
average_stats g f = do
ts <- parse_file f
let x = List.foldl' g 0 ts
let x' = fromIntegral x :: Float
let l = fromIntegral (length ts) :: Float
let y = x' / l :: Float
return y
length_triple :: Int -> Entailment -> Int
length_triple n (a, b, _, _, _, _) = n + prop_length a + prop_length b
num_vars_triple :: Int -> Entailment -> Int
num_vars_triple n (a, b, _, _, _, _) = n + num_vars (Prop.Conditional a b)
power_two_num_vars_triple :: Int -> Entailment -> Int
power_two_num_vars_triple n (a, b, _, _, _, _) = n + 2 ^ (num_vars (Prop.Conditional a b))
num_ops_triple :: Int -> Entailment -> Int
num_ops_triple n (a, b, _, _, _, _) = n + num_ops a + num_ops b
num_ops :: Prop.Expr -> Int
num_ops (Prop.Variable _) = 0
num_ops (Prop.Negation p) = num_ops p + 1
num_ops (Prop.Conjunction p q) = num_ops p + num_ops q + 1
num_ops (Prop.Disjunction p q) = num_ops p + num_ops q + 1
num_ops (Prop.Conditional p q) = num_ops p + num_ops q + 1
num_ops (Prop.Biconditional p q) = num_ops p + num_ops q + 1
| deepmind/logical-entailment-dataset | Main.hs | apache-2.0 | 32,522 | 1 | 22 | 6,636 | 13,798 | 6,949 | 6,849 | 659 | 6 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module AndroidLintSummary.CLI where
import BasicPrelude hiding (fromString)
import AndroidLintSummary
import Control.Lens ((^.))
import Options.Applicative
import Rainbow
import Control.Monad.Reader (runReader)
import Data.Default (def)
import Data.Stringable (Stringable (fromString, toString))
import Data.Version (Version (), showVersion)
import System.Directory (getCurrentDirectory)
import qualified System.Console.Terminal.Size as Terminal
import qualified System.FilePath.Find as Find
findFilesFromArgs :: AppOpts -> IO [FilePath]
findFilesFromArgs args' = go $ args' ^. targets
where
go (Just names) = return names
go Nothing = do
dir <- getCurrentDirectory
Find.find Find.always (Find.filePath Find.~~? (args' ^. pattern)) dir
lintSummaryParser :: Version -> ParserInfo AppOpts
lintSummaryParser version =
info (helper <*> appOpts <**> versionInfo)
( fullDesc
<> progDesc "Format Android Lint XML output nicely"
<> header "android-lint-summary - a lint-results.xml pretty printer" )
where
appOpts = AppOpts
<$> optional ( some $ argument str (metavar "FILES") )
<*> strOption ( long "glob"
<> short 'g'
<> help "Glob pattern to select result files"
<> value (def ^. pattern)
<> showDefault )
<*> ( fromString <$>
strOption ( long "formatter"
<> short 'f'
<> help "Specify a formatter to use [simple|null]"
<> value (toString $ def ^. formatter)
<> showDefault ) )
<*> flag Normal Verbose ( long "verbose"
<> short 'v'
<> help "Enable verbose mode" )
versionInfo = infoOption ("android-lint-summary " ++ showVersion version)
( short 'V'
<> long "version"
<> hidden
<> help "Show version information" )
runCLI :: Version -> IO ()
runCLI version = execParser (lintSummaryParser version) >>= run
where
run :: AppOpts -> IO ()
run args' = do
size <- Terminal.size
let env = AppEnv args' size
files <- findFilesFromArgs args'
lintIssues <- concat <$> forM files (openXMLFile >=> readLintIssues)
mapM_ putChunk $ runReader (formatLintIssues (args' ^. formatter) lintIssues) env
| VikingDen/android-lint-summary | src/AndroidLintSummary/CLI.hs | apache-2.0 | 2,685 | 0 | 18 | 921 | 625 | 323 | 302 | 57 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Base.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:34
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Classes.Base (
module Qtc.Classes.Types
, getProgName, getArgs
, unsafePerformIO
, module Foreign.StablePtr
, module Foreign.Marshal.Alloc
, Wrap(..), when
)
where
import Foreign.C.Types
import Qtc.Classes.Types
import System.Environment( getProgName, getArgs )
import System.IO.Unsafe( unsafePerformIO )
import Foreign.StablePtr
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import qualified Control.Monad as M
data Wrap a = Wrap a
when :: Bool -> IO () -> IO ()
when = M.when
| keera-studios/hsQt | Qtc/Classes/Base.hs | bsd-2-clause | 928 | 0 | 8 | 157 | 153 | 98 | 55 | 19 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Data.Array.Nikola.Backend.CUDA.Haskell.Compile
-- Copyright : (c) Geoffrey Mainland 2012
-- License : BSD-style
--
-- Maintainer : Geoffrey Mainland <[email protected]>
-- Stability : experimental
-- Portability : non-portable
module Data.Array.Nikola.Backend.CUDA.Haskell.Compile
( CEx
, runCEx
, evalCEx
, compileToEx
) where
import Control.Applicative (Applicative, (<$>), (<*>), pure)
import Control.Monad.State
import Data.Bits
import Data.Int
import Data.List (foldl')
import qualified Data.Map as Map
import Data.Word
import qualified Foreign.CUDA.Driver as CU
import qualified Foreign.CUDA.ForeignPtr as CU
import qualified Language.C.Syntax as C
import Text.PrettyPrint.Mainland
import Data.Array.Nikola.Backend.C.Codegen
import Data.Array.Nikola.Backend.C.Monad hiding (gensym)
import Data.Array.Nikola.Backend.CUDA (sizeOfT)
import Data.Array.Nikola.Backend.CUDA.Haskell.Ex
import Data.Array.Nikola.Backend.Flags
import Data.Array.Nikola.Language.Check
import Data.Array.Nikola.Language.Syntax
newtype CEx a = CEx { runCEx :: CExEnv -> IO (CExEnv, a) }
evalCEx :: CEx a -> IO ([C.Definition], a)
evalCEx m = do
(env, a) <- runCEx m defaultCExEnv
return (cenvToCUnit (cexCEnv env), a)
data CExEnv = CExEnv
{ cexUniq :: !Int
, cexCEnv :: CEnv
, cexContext :: Context
, cexVarTypes :: Map.Map Var Type
, cexVarIdxs :: Map.Map Var Int
}
defaultCExEnv :: CExEnv
defaultCExEnv = CExEnv
{ cexUniq = 0
, cexCEnv = defaultCEnv flags
, cexContext = Host
, cexVarTypes = Map.empty
, cexVarIdxs = Map.empty
}
where
flags :: Flags
flags = defaultFlags { fOptimize = ljust 1 }
instance Monad CEx where
return a = CEx $ \s -> return (s, a)
m >>= f = CEx $ \s -> do (s', x) <- runCEx m s
runCEx (f x) s'
m1 >> m2 = CEx $ \s -> do (s', _) <- runCEx m1 s
runCEx m2 s'
fail err = CEx $ \_ -> fail err
instance Functor CEx where
fmap f x = x >>= return . f
instance Applicative CEx where
pure = return
(<*>) = ap
instance MonadState CExEnv CEx where
get = CEx $ \s -> return (s, s)
put s = CEx $ \_ -> return (s, ())
instance MonadIO CEx where
liftIO m = CEx $ \s -> do x <- m
return (s, x)
instance MonadCheck CEx where
getContext = gets cexContext
setContext ctx = modify $ \s -> s { cexContext = ctx }
lookupVarType v = do
maybe_tau <- gets $ \s -> Map.lookup v (cexVarTypes s)
case maybe_tau of
Just tau -> return tau
Nothing -> faildoc $ text "Variable" <+> ppr v <+>
text "not in scope."
extendVarTypes vtaus act = do
old_vars <- gets cexVarTypes
modify $ \s -> s { cexVarTypes = foldl' insert (cexVarTypes s) vtaus }
x <- act
modify $ \s -> s { cexVarTypes = old_vars }
return x
where
insert m (k, v) = Map.insert k v m
extendVars :: [(Var, Type)] -> CEx a -> CEx a
extendVars vtaus act = do
old_vars <- gets cexVarTypes
old_idxs <- gets cexVarIdxs
let n = length vtaus
modify $ \s -> s { cexVarTypes = foldl' insert (cexVarTypes s) vtaus
, cexVarIdxs = foldl' insert
(Map.map (+n) (cexVarIdxs s))
(map fst vtaus `zip` [0..n-1])
}
x <- act
modify $ \s -> s { cexVarTypes = old_vars
, cexVarIdxs = old_idxs
}
return x
where
insert m (k, v) = Map.insert k v m
lookupVar :: Var -> CEx Int
lookupVar v = do
maybe_i <- gets $ Map.lookup v . cexVarIdxs
case maybe_i of
Nothing -> faildoc $ text "Cannot find argument index for" <+> ppr v
Just i -> i `seq` return i
gensym :: String -> CEx String
gensym s = do
u <- gets cexUniq
modify $ \s -> s { cexUniq = u + 1 }
return $ s ++ show u
addKernel :: Exp -> CEx CudaKernel
addKernel f = do
kname <- gensym "kernel"
cenv <- gets cexCEnv
(kern, cenv') <- liftIO $ runC (compileKernelFun CUDA kname f) cenv
modify $ \s -> s { cexCEnv = cenv' }
return kern
fromIx :: Val -> Ex Int
fromIx (Int32V n) = return (fromIntegral n)
fromIx _ = faildoc $ text "internal error: fromIx"
toIx :: Int -> Ex Val
toIx n = return $ Int32V (fromIntegral n)
-- 'compileToEx' takes a host procedure and compiles it to a monadic action of
-- type 'Ex Val' in the 'Ex' monad'. This monadic action coordinates execution
-- the GPU kernels. It isn't particularly efficient---if you want efficiency,
-- use the Template Haskell back-end in
-- "Data.Array.Nikola.Backend.CUDA.TH.Compile".
compileToEx :: Exp -> CEx (Ex Val)
compileToEx e = do
let (vtaus, body) = splitLamE e
extendVars vtaus $ do
compileExp body
compileConst :: Const -> CEx (Ex Val)
compileConst (BoolC b) = return $ return $ BoolV b
compileConst (Int8C n) = return $ return $ Int8V n
compileConst (Int16C n) = return $ return $ Int16V n
compileConst (Int32C n) = return $ return $ Int32V n
compileConst (Int64C n) = return $ return $ Int64V n
compileConst (Word8C n) = return $ return $ Word8V n
compileConst (Word16C n) = return $ return $ Word16V n
compileConst (Word32C n) = return $ return $ Word32V n
compileConst (Word64C n) = return $ return $ Word64V n
compileConst (FloatC f) = return $ return $ FloatV f
compileConst (DoubleC f) = return $ return $ DoubleV f
compileExp :: Exp -> CEx (Ex Val)
compileExp (VarE v) = do
i <- lookupVar v
return $ gets (\s -> exVals s !! i)
compileExp (ConstE c) =
compileConst c
compileExp UnitE =
return $ return UnitV
compileExp (LetE v tau _ e1 e2) = do
f <- compileExp e1
g <- extendVars [(v,tau)] $
compileExp e2
return $ do f >>= pushVal
x <- g
popVal
return x
compileExp (LamE vtaus e) = do
f <- extendVars vtaus $ compileExp e
return $ return (FunV f)
compileExp (AppE f es) = do
mf <- compileExp f
mes <- mapM compileExp es
return $ do FunV f <- mf
vals <- sequence mes
mapM_ pushVal (reverse vals)
x <- f
popVals (length vals)
return x
compileExp (CallE f es) = do
kern <- addKernel f
(gdims, tdims) <- liftIO $ calcKernelDims kern es
margs <- mapM compileExp es
return $ do mod <- getCUDAModule
f <- liftIO $ CU.getFun mod (cukernName kern)
args <- sequence margs
liftIO $ toFunParams args $ \fparams ->
CU.launchKernel f gdims tdims 0 Nothing fparams
return UnitV
compileExp (BinopE op e1 e2) = do
m1 <- compileExp e1
m2 <- compileExp e2
return $ go op m1 m2
where
go :: Binop -> Ex Val -> Ex Val -> Ex Val
go EqO m1 m2 = liftOrd (==) m1 m2
go NeO m1 m2 = liftOrd (/=) m1 m2
go GtO m1 m2 = liftOrd (>) m1 m2
go GeO m1 m2 = liftOrd (>=) m1 m2
go LtO m1 m2 = liftOrd (<) m1 m2
go LeO m1 m2 = liftOrd (<=) m1 m2
go MaxO m1 m2 = liftMaxMin max m1 m2
go MinO m1 m2 = liftMaxMin min m1 m2
go AndL m1 m2 = liftBool (&&) m1 m2
go OrL m1 m2 = liftBool (||) m1 m2
go AddN m1 m2 = liftNum (+) m1 m2
go SubN m1 m2 = liftNum (-) m1 m2
go MulN m1 m2 = liftNum (*) m1 m2
go AndB m1 m2 = liftBits (.&.) m1 m2
go OrB m1 m2 = liftBits (.|.) m1 m2
go QuotI m1 m2 = liftIntegral quot m1 m2
go RemI m1 m2 = liftIntegral rem m1 m2
go DivF m1 m2 = liftFloating (/) m1 m2
go ModF m1 m2 = liftFloating fmod m1 m2
go PowF m1 m2 = liftFloating (**) m1 m2
go LogBaseF m1 m2 = liftFloating logBase m1 m2
fmod :: RealFrac a => a -> a -> a
x `fmod` y = x - (fromIntegral (floor (x/y)))*y
compileExp (IfThenElseE e_test e_then e_else) = do
m_test <- compileExp e_test
m_then <- compileExp e_then
m_else <- compileExp e_else
return $ do BoolV v_test <- m_test
if v_test then m_then else m_else
compileExp (ReturnE e) =
compileExp e
compileExp (SeqE m1 m2) = do
f <- compileExp m1
g <- compileExp m2
return $ f >> g
compileExp (BindE v tau m1 m2) = do
f <- compileExp m1
g <- extendVars [(v,tau)] $
compileExp m2
return $ do f >>= pushVal
g
compileExp (AllocE atau e_sh) = do
(tau, _) <- checkArrayT atau
m_sh <- mapM compileExp e_sh
return $ do sh <- sequence m_sh >>= mapM fromIx
ptrs <- go (product sh) tau
return $ ArrayV ptrs sh
where
go :: Int -> ScalarType -> Ex PtrVal
go sz (TupleT taus) =
TupPtrV <$> mapM (go sz) taus
go sz tau = do
ptr :: CU.ForeignDevicePtr Word8 <-
liftIO $ CU.mallocForeignDevPtrArray (sz*sizeOfT tau)
return $ PtrV (CU.castForeignDevPtr ptr)
compileExp (DimE i _ e) = do
me <- compileExp e
return $ do ArrayV _ sh <- me
toIx (sh !! i)
compileExp e =
faildoc $ nest 4 $
text "Cannot compile the following Nikola term to an interpreted term:" </> ppr e
class ToFunParams a where
toFunParams :: a -> ([CU.FunParam] -> IO b) -> IO b
instance ToFunParams a => ToFunParams [a] where
toFunParams [] kont =
kont []
toFunParams (x:xs) kont =
toFunParams x $ \fparams_x ->
toFunParams xs $ \fparams_xs ->
kont $ fparams_x ++ fparams_xs
instance ToFunParams PtrVal where
toFunParams (PtrV fdptr) kont =
CU.withForeignDevPtr fdptr $ \dptr ->
kont [CU.VArg dptr]
toFunParams (TupPtrV ptrs) kont =
toFunParams ptrs kont
instance ToFunParams Val where
toFunParams UnitV _ = error "Cannot pass unit type to CUDA function"
toFunParams (BoolV False) kont = kont [CU.VArg (0 :: Word8)]
toFunParams (BoolV True) kont = kont [CU.VArg (1 :: Word8)]
toFunParams (Int8V n) kont = kont [CU.VArg n]
toFunParams (Int16V n) kont = kont [CU.VArg n]
toFunParams (Int32V n) kont = kont [CU.VArg n]
toFunParams (Int64V n) kont = kont [CU.VArg n]
toFunParams (Word8V n) kont = kont [CU.VArg n]
toFunParams (Word16V n) kont = kont [CU.VArg n]
toFunParams (Word32V n) kont = kont [CU.VArg n]
toFunParams (Word64V n) kont = kont [CU.VArg n]
toFunParams (FloatV f) kont = kont [CU.VArg f]
toFunParams (DoubleV f) kont = kont [CU.VArg f]
toFunParams (TupleV vals) kont = toFunParams vals kont
toFunParams (ArrayV ptrs sh) kont = toFunParams ptrs $ \fparams_ptrs ->
let fparams_sh = [CU.VArg (fromIntegral i :: Int32) | i <- sh]
in
kont $ fparams_ptrs ++ fparams_sh
toFunParams (FunV {}) _ = error "Cannot pass function value to kernel"
| mainland/nikola | src/Data/Array/Nikola/Backend/CUDA/Haskell/Compile.hs | bsd-3-clause | 11,273 | 0 | 15 | 3,556 | 4,121 | 2,063 | 2,058 | -1 | -1 |
f = head
g = f [f]
--a x y = x + y
h = f | happlebao/Core-Haskell | Hello.hs | bsd-3-clause | 42 | 0 | 6 | 18 | 23 | 13 | 10 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module RunIdea
( exportEnvVars,
JavaVersion(Java7, Java8),
IdeaVersion(Idea14, Idea15)
) where
import Turtle
import Data.Maybe
import Prelude hiding (FilePath)
data JavaVersion
= Java7
| Java8
data IdeaVersion
= Idea14
| Idea15
exportEnvVars :: JavaVersion -> IdeaVersion -> [Text] -> IO ()
exportEnvVars j i gwArgs = do
echo "Setting environment variables.."
export "JAVA_HOME" $ getJavaPath j
export "IDEA_HOME" $ getIdeaPath i
echo $ "export PATH=$PATH:" <> getIdeaPath i <> "/bin"
envVars <- env
printVar "JAVA_HOME" envVars
printVar "IDEA_HOME" envVars
printVar "PATH" envVars
dir <- pwd
cd dir
exitCode <- proc "./gwb" gwArgs empty
print exitCode
where
printVar :: Text -> [(Text, Text)] -> IO ()
printVar a l = echo $ case lookup a l of
Just x -> a <> "=" <> x
Nothing -> "Variable " <> a <> " doesn't appear to be set"
getJavaPath :: JavaVersion -> Text
getJavaPath Java7 = "/usr/lib/jvm/java-7-oracle"
getJavaPath Java8 = "/usr/lib/jvm/java-8-oracle"
getIdeaPath :: IdeaVersion -> Text
getIdeaPath Idea14 = "/opt/idea14/idea-IU-141.3056.4"
getIdeaPath Idea15 = "/opt/idea15/idea-IU-143.2370.31"
| DPakJ989/d-env | src/RunIdea.hs | bsd-3-clause | 1,267 | 0 | 12 | 294 | 349 | 176 | 173 | 43 | 2 |
-- |
-- Copyright : (C) 2012-2013 Parallel Scientific Labs, LLC.
-- License : BSD3
--
-- Support for managing pools of CCI transfer buffers.
{-# LANGUAGE ForeignFunctionInterface #-}
module Network.Transport.CCI.Pool
( Pool
, PoolRef
, Buffer(bHandle)
, newPool
, freePool
, newBuffer
, freeBuffer
, getBufferHandle
, getBufferByteString
, convertBufferToByteString
, spares
, cleanup
, lookupBuffer
, unregisterBuffer
) where
import Control.Applicative ((<$>))
import Control.Monad (when, join)
import Control.Exception (catch, IOException, mask_, bracketOnError)
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.ByteString.Char8 as BSC
import Data.ByteString.Char8 (ByteString)
import Data.ByteString.Unsafe (unsafePackCStringFinalizer)
import Data.IORef
import qualified Data.List as List (find, delete, deleteBy, insertBy)
import Data.Maybe (fromJust)
import Data.Foldable ( forM_, mapM_ )
import Data.List (find)
import Data.Ord (comparing)
import Foreign.C.Types ( CChar, CSize(..), CInt(..) )
import Foreign.C.String (CStringLen)
import Foreign.Marshal.Alloc (mallocBytes, free, alloca)
import Foreign.Ptr (Ptr, castPtr)
import Foreign.Storable ( peek )
import Prelude hiding (mapM_)
foreign import ccall unsafe posix_memalign :: Ptr (Ptr a) -> CSize -> CSize -> IO CInt
type BufferId = Int
-- TODO call spares (somewhere??) to allocate buffers in advance of their need.
-- | A buffer, identified by a handle. With this handle, we can deallocate with
-- 'freeBuffer', we can get its contents with 'getBufferByteString' and we can
-- get its handle value with 'getBufferHandle'.
data Buffer handle = Buffer
{
bId :: BufferId,
bStart :: Ptr CChar,
bSize :: Int,
bHandle :: handle
}
-- | A collection of managed buffers, parameterized by the type of the handle
-- that is created when a buffer is registered. In CCI's case, that is
-- RMALocalHandle.
data Pool handle = Pool
{ pNextId :: !BufferId
-- ^ The generator for buffer identifiers
, pMaxBufferCount :: Int
-- ^ The maximum amount of idle buffers that are kept
, pAlign :: Int
-- ^ Alignment required for buffers
, pRegister :: CStringLen -> IO handle
-- ^ Operation used to register buffers
, pUnregister :: handle -> IO ()
-- ^ Operation used to unregister buffers
, pInUse :: Map BufferId (Buffer handle)
-- ^ Buffers in use
, pAvailableBySize :: [Buffer handle]
-- ^ Idle buffers sorted by size
, pAvailableLru :: [BufferId]
-- ^ Idle buffers in the order they were created or returned
-- (the most recent buffer appears first)
}
type PoolRef handle = IORef (Maybe (Pool handle))
-- | Returns the handle of the given buffer
getBufferHandle :: Buffer handle -> handle
getBufferHandle = bHandle
_dbg :: String -> IO ()
_dbg = putStrLn
-- | Deallocates and unregisters all buffers managed
-- by the given pool.
freePool :: PoolRef handle -> IO ()
freePool rPool = mask_ $ do
mPool <- atomicModifyIORef rPool $ \mPool -> (Nothing, mPool)
forM_ mPool $ \pool -> do
mapM_ (pUnregister pool) $ map bHandle $ Map.elems $ pInUse pool
mapM_ (destroyBuffer pool) $ pAvailableBySize pool
-- | Create a new pool. All buffers will be aligned at the given alignment (or
-- 0 for any alignment). Allocated, but unused buffers will be harvested after
-- the given max count. All, the user provides two functions for registering and
-- registering handles, which are called when buffers are allocated and
-- deallocated.
newPool :: Int -> Int -> (CStringLen -> IO handle) -> (handle -> IO ()) -> Pool handle
newPool alignment maxbuffercount reg unreg =
Pool {pNextId=0,
pMaxBufferCount=maxbuffercount,
pAlign=alignment,
pRegister = reg,
pUnregister = unreg,
pInUse=Map.empty,
pAvailableBySize=[],
pAvailableLru=[]}
-- | Lookups a buffer in a given pool.
lookupBuffer :: Ptr CChar -> PoolRef handle -> IO (Maybe (Buffer handle))
lookupBuffer ptr =
fmap (join . fmap (find ((ptr ==) . bStart) . Map.elems . pInUse))
. readIORef
-- | Unregisters a buffer.
unregisterBuffer :: PoolRef handle -> Buffer handle -> IO ()
unregisterBuffer rPool buf =
atomicModifyIORef rPool (\mPool ->
case mPool of
Nothing -> (mPool,Nothing)
Just pool -> ( Just pool { pInUse = Map.delete (bId buf) (pInUse pool) }
, Just pool
)
)
>>= mapM_ (\pool -> pUnregister pool (bHandle buf))
-- | Release the given buffer. It won't be unregistered and deallocated
-- immediately, but simply placed on the available list.
freeBuffer :: PoolRef handle -> Buffer handle -> IO ()
freeBuffer rPool buffer = mask_ $ do
mPoolOk <- atomicModifyIORef rPool $ \mPool -> case mPool of
Nothing -> (mPool, Right False)
Just pool -> do
case Map.lookup (bId buffer) (pInUse pool) of
Just buf | bSize buf == bSize buffer ->
if pMaxBufferCount pool <= length (pAvailableLru pool)
then let newpool = pool
{ pInUse = Map.delete (bId buffer) (pInUse pool) }
in (Just newpool, Left pool)
else let newpool = pool
{ pInUse = Map.delete (bId buffer) (pInUse pool)
, pAvailableBySize =
List.insertBy (comparing bSize)
buffer
(pAvailableBySize pool)
, pAvailableLru = bId buf : pAvailableLru pool
}
in (Just newpool, Right True)
_ -> (mPool, Right True)
case mPoolOk of
-- The pool is full of idle buffers, so unregister and release.
Left pool -> destroyBuffer pool buffer
-- The pool has been released, so we release the buffer.
Right False -> freeAligned (bStart buffer)
-- The pool accepted the buffer.
Right True -> return ()
-- | Allocate excess buffers up to our limit
spares :: PoolRef handle -> Int -> IO ()
spares rPool defaultsize = mask_ $ do
mPool <- readIORef rPool
forM_ mPool $ \pool ->
if (pMaxBufferCount pool > length (pAvailableLru pool))
then do res <- newBuffer rPool defaultsize
case res of
Just newbuf ->
freeBuffer rPool newbuf
Nothing -> return ()
else return ()
-- | Remove and destroy excess buffers beyond our limit
cleanup :: PoolRef handle -> IO ()
cleanup rPool = mask_ $ do
mPool <- readIORef rPool
forM_ mPool $ \pool ->
if (pMaxBufferCount pool < length (pAvailableLru pool)) then
let killme = let killmeId = last (pAvailableLru pool)
in fromJust $ List.find (\b -> bId b == killmeId) (pAvailableBySize pool)
newpool = pool { pAvailableLru = init $ pAvailableLru pool,
pAvailableBySize = List.deleteBy byId killme (pAvailableBySize pool)}
in do destroyBuffer pool killme
return newpool
else return pool
where
byId a b = bId a == bId b
destroyBuffer :: Pool handle -> Buffer handle -> IO ()
destroyBuffer pool buffer =
do (pUnregister pool) (bHandle buffer)
freeAligned $ bStart buffer
-- | Find an available buffer of the appropriate size, or allocate a new one if
-- such a buffer is not already allocated. You will get back an updated pool and
-- the buffer object. You may provide the size of the desired buffer.
newBuffer :: PoolRef handle -> Int -> IO (Maybe (Buffer handle))
newBuffer rPool rmaSize = mask_ $ do
mres <- atomicModifyIORef rPool $ \mPool -> case mPool of
Nothing -> (mPool, Left Nothing)
Just pool -> case findAndRemove goodSize (pAvailableBySize pool) of
(_newavailable, Nothing) ->
( Just pool { pNextId = pNextId pool + 1 }
, Left mPool
)
(newavailable, Just buf) ->
-- We renew the identifier when recycling the buffer so there is no
-- danger that the GC returns the buffer of a previous incarnation,
-- which could happen if the buffer was returned explicitly.
let newbuf = buf { bId = pNextId pool }
in ( Just pool
{ pNextId = pNextId pool + 1
, pAvailableBySize = newavailable
, pInUse = Map.insert (bId newbuf) newbuf (pInUse pool)
, pAvailableLru = List.delete (bId buf) (pAvailableLru pool)
}
, Right newbuf
)
case mres of
-- reusing a recycled buffer
Right buf -> return $ Just buf
-- the pool has been released
Left Nothing -> return Nothing
-- there are no idle buffers, so we request one
Left (Just pool0) -> bracketOnError
(allocAligned' (pAlign pool0) rmaSize)
(maybe (return ()) $ freeAligned . fst)
$ \mbuf -> case mbuf of
Nothing -> return Nothing
Just cstr@(start,_) -> do
handle <- (pRegister pool0) cstr
let newbuf = Buffer
{ bId = pNextId pool0
, bStart = start
, bSize = rmaSize
, bHandle = handle
}
poolOk <- atomicModifyIORef rPool $ maybe (Nothing,False) $ \pool ->
( Just pool { pInUse = Map.insert (bId newbuf) newbuf (pInUse pool) }
, True
)
if poolOk then return $ Just newbuf
else error "network-transport-cci: PANIC! Pool was released while still in use."
where
goodSize b = bSize b >= rmaSize
freeAligned :: Ptr CChar -> IO ()
freeAligned = free
allocAligned' :: Int -> Int -> IO (Maybe CStringLen)
allocAligned' a s =
catch (Just <$> allocAligned a s) (\x -> const (return Nothing) (x::IOException))
allocAligned :: Int -> Int -> IO CStringLen
allocAligned 0 size = mallocBytes size >>= \p -> return (p,size)
allocAligned align size = alloca $ \ptr ->
do ret <- posix_memalign ptr (fromIntegral align) (fromIntegral size)
when (ret /= 0) $ error $ "allocAligned: " ++ show ret
res <- peek ptr
return (res, size)
-- | View the contents of the buffer as a bytestring. Currently O(n).
getBufferByteString :: Buffer handle -> IO ByteString
getBufferByteString buffer =
BSC.packCStringLen (bStart buffer, bSize buffer) -- TODO use unsafePackCStringLen, unsafePackMallocCString in Pool.getByteString? How to safely avoid copying?
findAndRemove :: (a -> Bool) -> [a] -> ([a], Maybe a)
findAndRemove f xs = go [] xs
where go before [] = (reverse before,Nothing)
go before (x:after) | f x = ((reverse before)++after,Just x)
go before (x:after) = go (x:before) after
-- | A zero-copy alternative to getBufferByteString. The buffer is removed from
-- the pool; after this call, the Buffer object is invalid. The resulting
-- ByteString occupies the same space and will be handled normally by the gc.
convertBufferToByteString :: PoolRef handle -> Buffer handle -> IO ByteString
convertBufferToByteString rPool buffer =
unsafePackCStringFinalizer (castPtr $ bStart buffer) (bSize buffer)
$ freeBuffer rPool buffer
| haskell-distributed/network-transport-cci | src/Network/Transport/CCI/Pool.hs | bsd-3-clause | 11,412 | 82 | 23 | 3,210 | 2,731 | 1,482 | 1,249 | 203 | 7 |
--------------------------------------------------------------------------------
-- |
-- Module : Sequence.Fasta
-- Copyright : (c) [2009..2010] Trevor L. McDonell
-- License : BSD
--
-- Reading sequence data in the FASTA format. Each sequence consists of a head
-- (prefixed by a ''>'') and a set of lines containing the sequence data.
--
--------------------------------------------------------------------------------
module Sequence.Fasta where
import Data.List (isSuffixOf)
import Control.Applicative ((<$>))
import qualified Bio.Sequence as F
import qualified Bio.Sequence.Fasta as F
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Codec.Compression.GZip as GZip
type Protein = F.Sequence F.Amino
--
-- Lazily read sequences from a FASTA-formatted file. This is identical to the
-- code of the bio package, except the sequence type is cast on output and GZip
-- compressed files are deflated as necessary.
--
readFasta :: FilePath -> IO [Protein]
{-# INLINE readFasta #-}
readFasta fp = map F.castToAmino . F.mkSeqs . L.lines . prepare <$> L.readFile fp
where
prepare = if ".gz" `isSuffixOf` fp then GZip.decompress
else id
--
-- Count the number of sequences in a file. Each sequence consist of a header
-- and a set of lines containing the sequence data. GZip compressed files are
-- inflated if necessary, which is the only addition over the bio package
-- function of the same name.
--
countSeqs :: FilePath -> IO Int
{-# INLINE countSeqs #-}
countSeqs fp = length . describe . prepare <$> L.readFile fp
where
describe = filter (('>' ==) . L.head) . filter (not . L.null) . L.lines
prepare = if ".gz" `isSuffixOf` fp then GZip.decompress
else id
| tmcdonell/hfx | src/haskell/Sequence/Fasta.hs | bsd-3-clause | 1,862 | 0 | 12 | 441 | 279 | 171 | 108 | 19 | 2 |
{-# LANGUAGE OverloadedStrings, StandaloneDeriving #-}
module Web.Neo (
-- * Run Neo Actions
runNeoT,defaultRunNeoT,NeoT,NeoError(..),
Hostname,Port,
-- * Basic Types
Node(..),Edge(..),Properties,Label,
-- * Create Nodes and Edges
newNode,setNodeProperty,addNodeLabel,
newEdge,setEdgeProperty,
-- * Get Nodes
nodeById,nodesByLabel,
-- * Get Edges
edgeById,
-- * Get Information about Nodes
allEdges,incomingEdges,outgoingEdges,
nodeLabels,nodeProperties,
-- * Get Information about Edges
source,target,edgeLabel,edgeProperties,
-- * Cypher Queries
cypher,CypherQuery,CypherParameters,CypherResult(..)
) where
import Web.Neo.Internal
import Web.Rest (Hostname,Port)
| phischu/haskell-neo | src/Web/Neo.hs | bsd-3-clause | 747 | 0 | 5 | 147 | 145 | 100 | 45 | 15 | 0 |
--
-- Utils.hs
-- Copyright (C) 2017 jragonfyre <jragonfyre@jragonfyre>
--
-- Distributed under terms of the MIT license.
--
module Utils
( allValues
) where
allValues :: (Bounded a, Enum a) => [a]
allValues = [minBound..]
| jragonfyre/TRPG | src/Utils.hs | bsd-3-clause | 232 | 0 | 6 | 45 | 46 | 30 | 16 | 4 | 1 |
{-# LANGUAGE MultiParamTypeClasses
,FlexibleInstances
,TypeSynonymInstances
,TemplateHaskell #-}
module GivenFind.Chemistry
( SearchChemSymbols(..)
) where
import GivenFind
import GivenFind.Questions
import GivenFind.Geography (listOfTemperatures, listOfDistances)
import Control.Monad
import Control.Applicative
import Radium.Element
import Radium.Formats.Condensed
import Radium.Formats.Smiles
import Data.Maybe
import Data.Char
import Text.Read
import Prelude hiding (lookup)
import qualified Data.Text as DT
import qualified Data.Map.Strict as M
import Data.List
import Data.List.Split
-- density -> g/cm3, g/cm^3, g/mL, kg/l, kg/L, lbs/L, lbs/l
-- mass -> g, kg, mg, gram, grams, L, mL, Liters, liters, ga, oz, ounces
-- temperatures -> ["oC","^oC","°C","°F","oF","^oF","°K","oK","^oK","°N","oN","^oN"]
-- subatomic particles -> electron, electrons, proton, protons, neutron, neutrons
-- pseudo-units -> ppm, parts-per-million, ppb, parts-per-billion, ppt, parts-per-trillion, ppq, parts-per-quadrillion
-- table groups -> 1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, IA, IIA, IIIA, IVA, VA, VIA, VIIA, VIIIA
-- chemical reactions -> combination, decomposition, combustion, single replacement, double replacement
-- atomic mass -> g/mol
-- moles -> mol, moles
-- atoms -> atom, atoms
-- molecules -> molecule, molecules
-- pressure -> atm, torr
-- physical constants -> L-atm/mol-deg, gas constant, gas constants
-- oxidation numbers -> oxidation number, oxidation numbers
class SearchInText s => SearchChemSymbols s where
-- finds for example "5 cm2"
listOfSurfaces :: s -> Maybe [s]
-- finds for example "4 lbs/l"
listOfDens :: s -> Maybe [s]
-- finds for example "5 kg"
listOfMass :: s -> Maybe [s]
-- finds for example "3 neutrons"
listOfSubAtoms :: s -> Maybe [s]
-- finds for example "6 ppt"
listOfPseudoUnits :: s -> Maybe [s]
-- finds for example "2 L-atm/mol-deg"
listOfConstants :: s -> Maybe [s]
-- finds for example "2 atm"
listOfPress :: s -> Maybe [s]
-- finds for example "group IIA"
listOfGroups :: s -> Maybe [s]
-- finds for example "period 1"
listOfPeriods :: s -> Maybe [s]
-- finds for example "7 moles"
listOfMoles :: s -> Maybe [s]
-- finds for example "10 atoms"
listOfAtoms :: s -> Maybe [s]
-- finds for example "6 molecules"
listOfMolecules :: s -> Maybe [s]
-- finds for example "1 oxidation number"
listOfOxNumb :: s -> Maybe [s]
-- finds for example "carbon" or "H"
listOfElem :: s -> Maybe [Element]
instance SearchChemSymbols String where
listOfSurfaces txt = checkIfListEmpty . getUnitsNumber surfaceSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfDens txt = checkIfListEmpty . getUnitsNumber densSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfMass txt = checkIfListEmpty . getUnitsNumber massSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfSubAtoms txt = checkIfListEmpty . getUnitsNumber subAtoms "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfPseudoUnits txt = checkIfListEmpty . getUnitsNumber pseudoUnits "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfConstants txt = checkIfListEmpty . getUnitsNumber physConstants "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfPress txt = checkIfListEmpty . getUnitsNumber pressSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfGroups txt = checkIfListEmpty $ getFromTable ( (return . removelastPuncs . removefirstPuncs) (mapText txt)) ["group","Group","groups","Groups","electron structure of the"]
listOfPeriods txt = checkIfListEmpty $ getFromTable ( (return . removelastPuncs . removefirstPuncs) (mapText txt)) ["period","Period","periods","Periods"]
listOfMoles txt = checkIfListEmpty . getUnitsNumber ["mole","moles"] "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfAtoms txt = checkIfListEmpty . getUnitsNumber ["atom","atoms"] "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfMolecules txt = checkIfListEmpty . getUnitsNumber ["molecule","molecules"] "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfOxNumb txt = checkIfListEmpty . getUnitsNumber ["oxidation number","oxidation numbers"] "" $ return . removelastPuncs . removefirstPuncs $ mapText txt
listOfElem txt = checkIfListEmpty . getElements . appendChemResults chemSymb . removelastPuncs . removefirstPuncs $ mapText txt
instance SearchChemSymbols DT.Text where
listOfSurfaces txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber surfaceSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfDens txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber densSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfMass txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber massSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfSubAtoms txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber subAtoms "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfPseudoUnits txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber pseudoUnits "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfConstants txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber physConstants "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfPress txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber pressSymb "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfGroups txt = checkIfListEmpty $ liftM (map DT.pack) $ getFromTable ( (return . removelastPuncs . removefirstPuncs) (mapText . DT.unpack $ txt)) ["group","Group","groups","Groups","electron structure of the"]
listOfPeriods txt = checkIfListEmpty $ liftM (map DT.pack) $ getFromTable ( (return . removelastPuncs . removefirstPuncs) (mapText . DT.unpack $ txt)) ["period","Period","periods","Periods"]
listOfMoles txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber ["mole","moles"] "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfAtoms txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber ["atom","atoms"] "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfMolecules txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber ["molecule","molecules"] "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfOxNumb txt = checkIfListEmpty . liftM (map DT.pack) . getUnitsNumber ["oxidation number","oxidation numbers"] "" $ return . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
listOfElem txt = checkIfListEmpty . getElements . appendChemResults chemSymb . removelastPuncs . removefirstPuncs $ mapText $ DT.unpack txt
surfaceSymb :: [String]
surfaceSymb = ["cm2","m2","km2","mm2","cm^2","m^2","km^2","mm^2"]
densSymb :: [String]
densSymb = ["g/cm3", "g/cm^3", "g/mL", "kg/l", "kg/L", "lbs/L", "lbs/l"]
massSymb :: [String]
massSymb = ["g", "kg", "mg", "gram", "grams", "L", "mL", "Liters", "liters", "ga", "oz", "ounces"]
subAtoms :: [String]
subAtoms = ["electron", "electrons", "proton", "protons", "neutron", "neutrons"]
pseudoUnits :: [String]
pseudoUnits = ["ppm", "parts-per-million", "ppb", "parts-per-billion", "ppt", "parts-per-trillion", "ppq", "parts-per-quadrillion"]
physConstants :: [String]
physConstants = ["L-atm/mol-deg", "gas constant", "gas constants"]
pressSymb :: [String]
pressSymb = ["atm", "torr"]
tabGroupSymb :: [String]
tabGroupSymb = ["1A", "2A", "3B", "4B", "5B", "6B", "7B", "8", "1B", "2B", "3A", "4A", "5A", "6A", "7A", "8A", "IA", "IIA", "IIIB", "IVB", "VB", "VIB", "VIIB", "VIII", "IB", "IIB", "IIIA", "IVA", "VA", "VIA", "VIIA", "VIIIA"]
chemSymb :: [(String, String)]
chemSymb = ([("H", "hydrogen"), ("He", "helium"),("Li", "lithium"),("Be", "beryllium") ,("B", "boron"),("C", "carbon"),("N", "nitrogen"),("O", "oxygen"),("F", "fluorine"),("Ne", "neon"),("Na", "sodium"),("Mg", "magnesium"),("Al", "alluminium"),("Si", "silicon"),("P", "phosphous"),("S", "sulphur"),("Cl", "chlorine"),("Ar", "argon"),("K", "potassium"),("Ca", "calcium"),("Sc", "scandium"),("Ti", "titanium"),("V", "vanadium"),("Cr", "chromium"),("Mn", "manganese"),("Fe", "iron"),("Co", "cobalt"),("Ni", "nickel"),("Cu", "copper"),("Zn", "zinc"),("Ga", "gallium"),("Ge", "germanium"),("As", "arsenic"),("Se", "selenium"),("Br", "bromine"),("Kr", "krypton"),("Rb", "rubidium"),("Sr", "strontium"),("Y", "yttrium")])
-- finds groups and periods in the periodic table. Finds for example "group IIIA" or "Period 6" or "group IIA and IIIB"
getFromTable :: Maybe [String] -> [String] -> Maybe [String]
getFromTable (Just (x:y:z:s:xs)) wordsList = case any (==True) . map (==x) $ wordsList of
True -> case (any (isDigit) y || (any (=='A') y || any (=='B') y)) && any (isDigit) s || (any (=='A') s || any (=='B') s) of
True -> liftM (y:) $ liftM (s :) (getFromTable (liftM (y :) (liftM (z :) (liftM (s :) (Just xs)))) wordsList)
False -> case any (isDigit) y || (any (=='A') y || any (=='B') y) of
True -> liftM (y :) (getFromTable (liftM (y :) (liftM (z :) (liftM (s :) (Just xs)))) wordsList)
_ -> getFromTable (liftM (y :) (liftM (z :) (liftM (s :) $ Just xs))) wordsList
False -> getFromTable (liftM (y :) (liftM (z :) (liftM (s :) $ Just xs))) wordsList
getFromTable (Just (_:xs)) wordsList = getFromTable (Just xs) wordsList
getFromTable (Just _) wordsList = Just []
getFromTable _ wordsList = Nothing
-- adds to list all keys from Map chemSymb, that were found in text
lookupChemKeys :: [(String,String)] -> [String] -> Maybe [String]
lookupChemKeys list text = if null [key | (key,value) <- list, key `elem` text] then Nothing else Just [key | (key,value) <- list, key `elem` text]
-- adds to list all keys from Map chemSymb, which values were found in text
lookupChemValues :: [(String,String)] -> [String] -> Maybe [String]
lookupChemValues list text = if null [key | (key,value) <- list, value `elem` text] then Nothing else Just [key | (key,value) <- list, value `elem` text]
-- adds two lists with symbols
appendChemResults :: [(String,String)] -> [String] -> Maybe [String]
appendChemResults list text = mappend (lookupChemKeys list text) (lookupChemValues list text)
-- converts String to Element, to use functions from Radium.Element. See https://hackage.haskell.org/package/radium-0.4/candidate/docs/src/Radium-Element.html#Element
getElements :: Maybe [String] -> Maybe [Element]
getElements (Just x) = Just [elementBySymbol value | value <- x, not.null $ value]
getElements _ = Nothing
| juliagoda/givenfind | src/GivenFind/Chemistry.hs | bsd-3-clause | 11,607 | 0 | 24 | 2,437 | 3,394 | 1,873 | 1,521 | 105 | 4 |
{-# LANGUAGE ConstraintKinds, ScopedTypeVariables, TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
module Data.SuffixArray (
suffixSort,
sais,
) where
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Control.Monad.Primitive
import Control.Monad.Trans
import Control.Monad.Trans.Loop
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Data.Word
-- import Debug.Trace
type CharType a = (Integral a)
type IndexType a = (Integral a, Bounded a)
-- | Sort suffixes for given string.
-- | String must not contain the `maxBound :: b` values.
suffixSort :: ( CharType a, IndexType b
, G.Vector v a, G.Vector v b
, G.Vector v (Int, b), G.Vector v Bool, Show (v Bool), Show (v b), Show b )
=> v a -> v b
suffixSort s = runST $ do
sa <- GM.replicate (G.length s) 0
sais s sa $ fromIntegral (G.maximum s) + 1
G.unsafeFreeze sa
sais :: forall a b m s v w.
( CharType a, G.Vector v a
, IndexType b, GM.MVector w b
, G.Vector v b, G.Vector v Bool, G.Vector v (Int, b), Show (v Bool), Show (v b), Show b
, w ~ G.Mutable v
, Functor m, PrimMonad m, s ~ PrimState m )
=> v a -> w s b -> b -> m ()
sais t sa k = do
let n = G.length t
-- create LS-string. L: False, S: True (L < S)
let ls = G.create $ do
mls <- GM.replicate n False
iterateLoopT (n - 2, G.last t, False) $ \(i, n1, b) -> do
let n0 = t G.! i
c | n0 < n1 = True
| n0 > n1 = False
| otherwise = b
lift $ GM.write mls i c
when (i == 0) exit
return (i - 1, n0, c)
return mls
let isLMS ix =
ix /= maxBound && ix > 0 && (ls G.! ix) && not (ls G.! (ix - 1))
-- Stage1:reduce the problem by at least 1/2
-- sort all the S-substrings
bkt <- G.thaw $ getBucket t k True
GM.set sa maxBound
forM_ [1..n-1] $ \i -> do
when (isLMS i) $ do
ix <- pred <$> GM.read bkt (fromIntegral $ t G.! i)
GM.write sa (fromIntegral ix) $ fromIntegral i
GM.write bkt (fromIntegral $ t G.! i) ix
induceSAl t sa k ls
-- (\s -> traceShow (s :: v b) $ return ()) =<< G.unsafeFreeze sa
induceSAs t sa k ls
-- (\s -> traceShow (s :: v b) $ return ()) =<< G.unsafeFreeze sa
-- compact all the sorted substrings into the first n1 items of SA
-- 2*n1 must be not larger than n (proveable)
n1 <- iterateLoopT (0, 0) $ \(i, n1) -> do
when (i >= n) $ exitWith n1
sai <- lift $ GM.read sa i
when (isLMS $ fromIntegral sai) $ do
lift $ GM.write sa n1 sai
continueWith (i + 1, n1 + 1)
continueWith (i + 1, n1)
-- find the lexicographic names of all substrings
forM_ [n1 .. n-1] $ \i -> GM.write sa i maxBound
name <- iterateLoopT (0, 0, maxBound) $ \(i, name, prev) -> do
when (i >= n1) $ exitWith name
pos <- lift $ fromIntegral <$> GM.read sa i
diff <- iterateLoopT 0 $ \d -> do
when (d >= n) $ exitWith False
when (prev == maxBound ||
t G.! (pos + d) /= t G.! (prev + d) ||
ls G.! (pos + d) /= ls G.! (prev + d)) $
exitWith True
when (d > 0 && (isLMS (pos + d) || isLMS (prev + d))) $
exitWith False
return $ d + 1
-- traceShow diff $ return ()
let (nname, nprev) = if diff then (name + 1, pos) else (name, prev)
p = if even pos then pos `div` 2 else (pos - 1) `div` 2
lift $ GM.write sa (n1 + p) $ nname - 1
return (i + 1, nname, nprev)
iterateLoopT (n - 1, n - 1) $ \(i, j) -> do
when (i < n1) exit
sai <- lift $ GM.read sa i
when (sai /= maxBound) $ do
lift $ GM.write sa j sai
continueWith (i - 1, j - 1)
return (i - 1, j)
-- stage 2: solve the reduced problem
let sa1 = GM.take n1 sa
s1 = GM.drop (n - n1) sa
if fromIntegral name < n1
then do -- recurse if names are not yet unique
is1 <- G.freeze s1
-- traceShow is1 $ return ()
sais (is1 :: v b) sa1 name
else do -- generate the suffix array of s1 directly
forM_ [0 .. n1 - 1] $ \i -> do
ix <- fromIntegral <$> GM.read s1 i
GM.write sa1 ix (fromIntegral i)
-- stage 3: induce the result for the original problem
bkt <- G.thaw $ getBucket t k True
iterateLoopT (1, 0) $ \(i, j) -> do
when (i >= n) exit
when (isLMS i) $ do -- get p1
lift $ GM.write s1 j $ fromIntegral i
continueWith (i + 1, j + 1)
return (i + 1, j)
forM_ [0 .. n1 - 1] $ \i -> do
ix <- fromIntegral <$> GM.read sa1 i
GM.write sa1 i =<< GM.read s1 ix
-- init SA[n1..n-1]
forM_ [n1 .. n - 1] $ \i -> do
GM.write sa i maxBound
forM [n1 - 1, n1 - 2 .. 0] $ \i -> do
j <- fromIntegral <$> GM.read sa i
GM.write sa i maxBound
ix <- pred <$> GM.read bkt (fromIntegral $ t G.! j)
GM.write bkt (fromIntegral $ t G.! j) ix
GM.write sa (fromIntegral ix) (fromIntegral j)
induceSAl t sa k ls
induceSAs t sa k ls
induceSAl :: ( Functor m, PrimMonad m, s ~ PrimState m
, CharType a, IndexType b
, G.Vector v a, G.Vector v b, G.Vector v (Int, b), G.Vector v Bool
, GM.MVector w b )
=> v a -> w s b -> b -> v Bool -> m ()
induceSAl t sa k ls = do
bkt <- G.thaw $ getBucket t k False
-- for last letter
let n = G.length t
ix0 <- GM.read bkt (fromIntegral $ t G.! (fromIntegral $ n - 1))
GM.write bkt (fromIntegral $ t G.! (fromIntegral $ n - 1)) $ ix0 + 1
GM.write sa (fromIntegral ix0) (fromIntegral $ n - 1)
-- rest
foreach [0 .. G.length t - 1] $ \i -> do
j0 <- lift $ GM.read sa i
let j = fromIntegral $ j0 - 1
when (j0 == maxBound || j0 == 0) continue
lift $ when (not (ls G.! j)) $ do
ix <- GM.read bkt (fromIntegral $ t G.! j)
GM.write bkt (fromIntegral $ t G.! j) (fromIntegral $ ix + 1)
GM.write sa (fromIntegral ix) (fromIntegral j)
induceSAs :: ( Functor m, PrimMonad m, s ~ PrimState m
, CharType a, IndexType b
, G.Vector v a, G.Vector v b, G.Vector v (Int, b), G.Vector v Bool
, GM.MVector w b )
=> v a -> w s b -> b -> v Bool -> m ()
induceSAs t sa k ls = do
!bkt <- G.thaw $ getBucket t k True
go bkt (G.length t - 1)
where
go !bkt !i = do
!j0 <- GM.unsafeRead sa i
let !j = fromIntegral $ j0 - 1
when (j0 /= maxBound && j0 /= 0 && j >= 0 && ls `G.unsafeIndex` j) $ do
!ix <- pred <$> GM.unsafeRead bkt (fromIntegral $ t `G.unsafeIndex` j)
GM.unsafeWrite bkt (fromIntegral $ t `G.unsafeIndex` j) ix
GM.unsafeWrite sa (fromIntegral ix) (fromIntegral j)
when (i > 0) $ go bkt (i - 1)
{-# SPECIALIZE induceSAs ::
U.Vector Int -> UM.STVector s Int -> Int -> U.Vector Bool -> ST s () #-}
{-
induceSAs t sa k ls = do
bkt <- G.thaw $ getBucket t k True
let n = G.length t
foreach [n - 1, n - 2 .. 0] $ \i -> do
j0 <- lift $ GM.read sa i
let j = fromIntegral $ j0 - 1
when (j0 == maxBound || j0 == 0) continue
lift $ when (j >= 0 && ls G.! j) $ do
ix <- pred <$> GM.read bkt (fromIntegral $ t G.! j)
GM.write bkt (fromIntegral $ t G.! j) ix
GM.write sa (fromIntegral ix) (fromIntegral j)
-}
getBucket :: ( CharType a, G.Vector v a
, IndexType b, G.Vector v b
, G.Vector v (Int, b) )
=> v a -> b -> Bool -> v b
getBucket t k end =
(if end then G.postscanl' else G.prescanl') (+) 0
$ G.accumulate (+) (G.replicate (fromIntegral k) 0)
$ G.map (\c -> (fromIntegral c, 1))
$ t
| tanakh/sufsort | Data/SuffixArray.hs | bsd-3-clause | 7,684 | 20 | 30 | 2,345 | 3,225 | 1,621 | 1,604 | 165 | 4 |
{-# language CPP #-}
-- No documentation found for Chapter "Promoted_From_VK_KHR_maintenance1"
module Vulkan.Core11.Promoted_From_VK_KHR_maintenance1 ( trimCommandPool
, CommandPoolTrimFlags(..)
, Result(..)
, ImageCreateFlagBits(..)
, ImageCreateFlags
, FormatFeatureFlagBits(..)
, FormatFeatureFlags
) where
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Control.Monad.IO.Class (MonadIO)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import Vulkan.Core10.Handles (CommandPool)
import Vulkan.Core10.Handles (CommandPool(..))
import Vulkan.Core11.Enums.CommandPoolTrimFlags (CommandPoolTrimFlags)
import Vulkan.Core11.Enums.CommandPoolTrimFlags (CommandPoolTrimFlags(..))
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkTrimCommandPool))
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Core11.Enums.CommandPoolTrimFlags (CommandPoolTrimFlags(..))
import Vulkan.Core10.Enums.FormatFeatureFlagBits (FormatFeatureFlagBits(..))
import Vulkan.Core10.Enums.FormatFeatureFlagBits (FormatFeatureFlags)
import Vulkan.Core10.Enums.ImageCreateFlagBits (ImageCreateFlagBits(..))
import Vulkan.Core10.Enums.ImageCreateFlagBits (ImageCreateFlags)
import Vulkan.Core10.Enums.Result (Result(..))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkTrimCommandPool
:: FunPtr (Ptr Device_T -> CommandPool -> CommandPoolTrimFlags -> IO ()) -> Ptr Device_T -> CommandPool -> CommandPoolTrimFlags -> IO ()
-- | vkTrimCommandPool - Trim a command pool
--
-- = Description
--
-- Trimming a command pool recycles unused memory from the command pool
-- back to the system. Command buffers allocated from the pool are not
-- affected by the command.
--
-- Note
--
-- This command provides applications with some control over the internal
-- memory allocations used by command pools.
--
-- Unused memory normally arises from command buffers that have been
-- recorded and later reset, such that they are no longer using the memory.
-- On reset, a command buffer can return memory to its command pool, but
-- the only way to release memory from a command pool to the system
-- requires calling 'Vulkan.Core10.CommandPool.resetCommandPool', which
-- cannot be executed while any command buffers from that pool are still in
-- use. Subsequent recording operations into command buffers will re-use
-- this memory but since total memory requirements fluctuate over time,
-- unused memory can accumulate.
--
-- In this situation, trimming a command pool /may/ be useful to return
-- unused memory back to the system, returning the total outstanding memory
-- allocated by the pool back to a more “average” value.
--
-- Implementations utilize many internal allocation strategies that make it
-- impossible to guarantee that all unused memory is released back to the
-- system. For instance, an implementation of a command pool /may/ involve
-- allocating memory in bulk from the system and sub-allocating from that
-- memory. In such an implementation any live command buffer that holds a
-- reference to a bulk allocation would prevent that allocation from being
-- freed, even if only a small proportion of the bulk allocation is in use.
--
-- In most cases trimming will result in a reduction in allocated but
-- unused memory, but it does not guarantee the “ideal” behavior.
--
-- Trimming /may/ be an expensive operation, and /should/ not be called
-- frequently. Trimming /should/ be treated as a way to relieve memory
-- pressure after application-known points when there exists enough unused
-- memory that the cost of trimming is “worth” it.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkTrimCommandPool-device-parameter# @device@ /must/ be a valid
-- 'Vulkan.Core10.Handles.Device' handle
--
-- - #VUID-vkTrimCommandPool-commandPool-parameter# @commandPool@ /must/
-- be a valid 'Vulkan.Core10.Handles.CommandPool' handle
--
-- - #VUID-vkTrimCommandPool-flags-zerobitmask# @flags@ /must/ be @0@
--
-- - #VUID-vkTrimCommandPool-commandPool-parent# @commandPool@ /must/
-- have been created, allocated, or retrieved from @device@
--
-- == Host Synchronization
--
-- - Host access to @commandPool@ /must/ be externally synchronized
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>,
-- 'Vulkan.Core10.Handles.CommandPool',
-- 'Vulkan.Core11.Enums.CommandPoolTrimFlags.CommandPoolTrimFlags',
-- 'Vulkan.Core10.Handles.Device'
trimCommandPool :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device that owns the command pool.
Device
-> -- | @commandPool@ is the command pool to trim.
CommandPool
-> -- | @flags@ is reserved for future use.
CommandPoolTrimFlags
-> io ()
trimCommandPool device commandPool flags = liftIO $ do
let vkTrimCommandPoolPtr = pVkTrimCommandPool (case device of Device{deviceCmds} -> deviceCmds)
unless (vkTrimCommandPoolPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkTrimCommandPool is null" Nothing Nothing
let vkTrimCommandPool' = mkVkTrimCommandPool vkTrimCommandPoolPtr
traceAroundEvent "vkTrimCommandPool" (vkTrimCommandPool' (deviceHandle (device)) (commandPool) (flags))
pure $ ()
| expipiplus1/vulkan | src/Vulkan/Core11/Promoted_From_VK_KHR_maintenance1.hs | bsd-3-clause | 6,089 | 5 | 13 | 1,251 | 656 | 431 | 225 | -1 | -1 |
import Test.Tasty
import Test.Tasty.HUnit
import qualified Data.Vector.Storable.Mutable as MV
import qualified Data.Vector.Storable as V
import Numeric.LinearAlgebra.UnsymmetricEigen
import Control.Monad
import Foreign.C.Types
import System.IO.Unsafe
import Data.Complex
import Data.List
import Data.Ord
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [unitTests]
unitTests = testGroup "Unit tests"
[ testCase "Diagonal Matrix LM" $ diagMatLMCheck @?= True,
testCase "Diagonal Matrix SM" $ diagMatSMCheck @?= True,
testCase "Non-Symmetric Sanity" $ complexEigsCheck @?= True
]
diagMat :: ArpackLinearOp
diagMat x y = do
MV.copy y x
forM [0..999] (\n -> do x' <- MV.read x n
let lambda = fromIntegral (n+1) :: CDouble
y' = x'*(fromIntegral (n+1))
MV.write y n y'
)
return ()
complexEigs :: ArpackLinearOp
complexEigs x y = do
x' <- V.freeze x
MV.write y 0 (3*((V.!) x' 0) + (-2)*((V.!) x' 1))
MV.write y 1 (4*((V.!) x' 0) + (-1)*((V.!) x' 1))
MV.write y 2 (2*((V.!) x' 2))
MV.write y 3 (1*((V.!) x' 3))
MV.write y 4 ((0.5)*((V.!) x' 4))
MV.write y 5 ((0.25)*((V.!) x' 5))
MV.write y 6 ((0.125)*((V.!) x' 6))
return ()
diagMatLMCheck :: Bool
diagMatLMCheck = let (converged, ePairs) = unsafePerformIO $eigs diagMat 1000 LM 6 (0) 6000
evals = map fst ePairs
evecs = map snd ePairs
trueEvals = map (:+0) [1000,999..]
diff = map (realPart . abs) $ zipWith (-) evals trueEvals
in not $ and (map (>=1e-10) diff)
diagMatSMCheck :: Bool
diagMatSMCheck = let (converged, ePairs) = unsafePerformIO $eigs diagMat 1000 SM 6 (0) 6000
evals = map fst ePairs
evecs = map snd ePairs
trueEvals = map (:+0) [1,2..]
diff = map (realPart . abs) $ zipWith (-) evals trueEvals
in not $ and (map (>=1e-10) diff)
complexEigsCheck :: Bool
complexEigsCheck = let (converged, ePairs) = unsafePerformIO $ eigs complexEigs 7 LM 5 (0) 70
evals = map fst ePairs
evecs = map snd ePairs
trueEvals = [1 :+ 2, 1 :+ (-2), 2, 1, 0.5]
diff = map (realPart . abs) $ zipWith (-) evals trueEvals
in not $ and (map (>=1e-10) diff)
| cmiller730/HEigs | test/test-unsymmetric.hs | bsd-3-clause | 2,472 | 1 | 19 | 793 | 1,008 | 531 | 477 | 58 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.