code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
-- The task is to refactor given functions into more Haskell idiomatic style
------------------------ (1) ----------------------------
-- Before:
fun1 :: [Integer] -> Integer
fun1 [] = 1
fun1 (x:xs)
| even x = (x - 2) * fun1 xs
| otherwise = fun1 xs
-- After:
fun1' :: [Integer] -> Integer
fun1' = product . map (subtract 2) . (filter even)
------------------------ (2) ----------------------------
-- Before:
fun2 :: Integer -> Integer
fun2 1 = 0
fun2 n | even n = n + fun2 (n `div` 2)
| otherwise = fun2 (3 * n + 1)
-- After
fun2' :: Integer -> Integer
fun2' = sum
.filter even
.takeWhile (>1)
.iterate (\x -> if (even x) then (x `div` 2) else (3*x + 1))
|
vaibhav276/haskell_cs194_assignments
|
higher_order/Wholemeal.hs
|
Haskell
|
mit
| 702
|
module Instances where
import Language.Haskell.Syntax
import qualified Language.Haskell.Pretty as P
import Niz
import Data.List
-------------------------------------------------------------------------------
---------------- INSTANCE DECLARATIONS ----------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---------------------- LENGTH OF HSEXP --------------------------------------
-------------------------------------------------------------------------------
--class Size a where
-- size :: a -> Int
instance Size HsName where
size _ = 1
instance Size HsQName where
-- size (Special HsCons) = 0
size _ = 1
instance Size HsLiteral where
size (HsInt i) = length $ show i
size _ = 1
instance Size HsQualType where
size _ = 1
instance Size HsQOp where
size (HsQVarOp x) = size x
size (HsQConOp x) = size x
instance Size HsExp where
size e = case e of
HsVar n -> size n
HsCon n -> size n
HsLit x -> size x
HsInfixApp e1 op e2 -> size e1 + size e2 + size op
HsApp (HsVar _) e2 -> size e2 + 1
HsApp (HsCon _) e2 -> size e2 + 1
HsApp e1 e2 -> size e1 + size e2
HsNegApp e -> 1 + size e
HsLambda _ pats e -> size e + size pats
HsLet decs e -> size e + size decs
HsIf e1 e2 e3 -> 1 + size e1 + size e2 + size e3
HsCase e alts -> size e + size alts
HsDo stmts -> size stmts
HsTuple es -> sum $ map size es
HsList [] -> 1
HsList es -> sum $ map size es -- size es
HsParen e -> size e
HsLeftSection e op -> size e + size op
HsRightSection op e -> size e + size op
HsRecConstr n fields -> size n + size fields
HsRecUpdate e fields -> size e + size fields
HsEnumFrom e -> 1 + size e
HsEnumFromTo e1 e2 -> 1 + size e1 + size e2
HsEnumFromThen e1 e2 -> 1 + size e1 + size e2
HsEnumFromThenTo e1 e2 e3 -> 1 + size e1 + size e2 + size e3
HsListComp e stmts -> size e + size stmts
HsExpTypeSig _ e t -> size e + size t
HsAsPat n e -> size n + size e
HsWildCard -> 0
HsIrrPat e -> size e
instance Size HsStmt where
size s = case s of
HsGenerator _ p e -> size p + size e
HsQualifier e -> size e
HsLetStmt decs -> size decs
instance Size HsPat where
size p = case p of
HsPVar n -> size n
HsPLit l -> size l
HsPNeg p -> 1 + size p
HsPInfixApp p1 n p2 -> size p1 + size n + size p2
HsPApp n pats -> 1 + (sum $ map size pats)
HsPTuple pats -> sum $ map size pats
HsPList [] -> 1
HsPList pats -> sum $ map size pats
HsPParen p -> size p
HsPRec n fields -> size n + size fields
HsPAsPat n p -> size n + size p
HsPWildCard -> 0
HsPIrrPat p -> size p
instance Size HsPatField where
size (HsPFieldPat n p) = size n + size p
instance Size HsDecl where
size d = case d of
HsTypeDecl _ name names htype -> size name + size names + size htype
HsDataDecl _ ss name names cons qnames
-> size name + size names + size cons + size qnames + size ss
HsInfixDecl _ assoc _ ops -> 2 + size ops
HsNewTypeDecl _ c name names con qname -> size c + size name + size names + size con + size qname
HsClassDecl _ c name names decs -> size c + size name + size names + size decs
HsInstDecl _ c qname types decs -> size c + size qname + size types + size decs
HsDefaultDecl _ types -> size types
HsTypeSig _ names qtype -> size qtype + size names
HsFunBind ms -> sum $ map size ms
HsPatBind _ pat rhs decs -> size pat + size rhs + size decs
HsForeignImport _ s1 safety s2 hname htype -> 3 + size hname + size htype
HsForeignExport _ s1 s2 name htype -> 2 + size name + size htype
instance Size HsType where
size t = case t of
HsTyFun t1 t2 -> size t1 + size t2
HsTyTuple types -> size types
HsTyApp t1 t2 -> size t1 + size t2
HsTyVar n -> size n
HsTyCon n -> size n
instance (Size a, Size b) => Size (a,b) where
size (a,b) = size a + size b
-- instance Size a => Size [a] where
-- size xs = sum (map size xs)
instance Size HsMatch where
size (HsMatch _ name pats rhs decs) = 1 + sum (map size pats) + size rhs
instance Size HsRhs where
size (HsUnGuardedRhs e) = size e
size (HsGuardedRhss x) = size x
instance Size HsGuardedRhs where
size (HsGuardedRhs _ e1 e2) = size e1 + size e2
instance Size HsConDecl where
size (HsConDecl _ name list) = size name + size list
size (HsRecDecl _ name list) = size name + size list
instance Size HsBangType where
size (HsBangedTy x) = size x
size (HsUnBangedTy x) = size x
instance Size HsOp where
size (HsVarOp x) = size x
size (HsConOp x) = size x
instance Size HsAlt where
size (HsAlt _ pat alts decs) = size pat + size alts + size decs
instance Size HsGuardedAlts where
size (HsUnGuardedAlt exp) = size exp
size (HsGuardedAlts xs) = size xs
instance Size HsGuardedAlt where
size (HsGuardedAlt _ e1 e2) = size e1 + size e2
instance Size HsFieldUpdate where
size (HsFieldUpdate qname exp) = size qname + size exp
instance Ord HsLiteral where
compare (HsChar x) (HsChar y) = compare x y
compare (HsChar _) _ = LT
compare _ (HsChar _) = GT
compare (HsString x) (HsString y) = compare x y
compare (HsString _) _ = LT
compare _ (HsString _) = GT
compare (HsInt x) (HsInt y) = compare x y
compare (HsInt _) _ = LT
compare _ (HsInt _) = GT
compare (HsFrac x) (HsFrac y) = compare x y
compare (HsFrac _) _ = LT
compare _ (HsFrac _) = GT
compare (HsCharPrim x) (HsCharPrim y) = compare x y
compare (HsCharPrim _) _ = LT
compare _ (HsCharPrim _) = GT
compare (HsStringPrim x) (HsStringPrim y) = compare x y
compare (HsStringPrim _) _ = LT
compare _ (HsStringPrim _) = GT
compare (HsIntPrim x) (HsIntPrim y) = compare x y
compare (HsIntPrim _) _ = LT
compare _ (HsIntPrim _) = GT
compare (HsFloatPrim x) (HsFloatPrim y) = compare x y
compare (HsFloatPrim _) _ = LT
compare _ (HsFloatPrim _) = GT
compare (HsDoublePrim x) (HsDoublePrim y) = compare x y
instance Ord HsPat where
compare (HsPVar x) (HsPVar y) = compare x y
compare (HsPVar _) _ = LT
compare _ (HsPVar _) = GT
compare (HsPLit x) (HsPLit y) = compare x y
compare (HsPLit _) _ = LT
compare _ (HsPLit _) = GT
compare (HsPNeg x) (HsPNeg y) = compare x y
compare (HsPNeg _) _ = LT
compare _ (HsPNeg _) = GT
compare (HsPInfixApp p1 n1 q1) (HsPInfixApp p2 n2 q2) | n1 == n2 = compare [p1,q1] [p2,q2]
compare (HsPInfixApp _ n1 _) (HsPInfixApp _ n2 _) = compare n1 n2
compare (HsPInfixApp _ _ _) _ = LT
compare _ (HsPInfixApp _ _ _) = GT
compare (HsPApp n1 p1) (HsPApp n2 p2) | n1 == n2 = compare p1 p2
compare (HsPApp n1 _) (HsPApp n2 _) = compare n1 n2
compare (HsPApp _ _) _ = LT
compare _ (HsPApp _ _) = GT
compare (HsPTuple p1) (HsPTuple p2) = compare p1 p2
compare (HsPTuple _) _ = LT
compare _ (HsPTuple _) = GT
compare (HsPList p1) (HsPList p2) = compare p1 p2
compare (HsPList _) _ = LT
compare _ (HsPList _) = GT
compare (HsPParen p1) (HsPParen p2) = compare p1 p2
compare (HsPParen _) _ = LT
compare _ (HsPParen _) = GT
compare (HsPRec n1 p1) (HsPRec n2 p2) | n1 == n2 = compare p1 p2
compare (HsPRec n1 _) (HsPRec n2 _) = compare n1 n2
compare (HsPRec _ _) _ = LT
compare _ (HsPRec _ _) = GT
compare (HsPAsPat n1 p1) (HsPAsPat n2 p2) | n1 == n2 = compare p1 p2
compare (HsPAsPat n1 _) (HsPAsPat n2 _) = compare n1 n2
compare (HsPAsPat _ _) _ = LT
compare _ (HsPAsPat _ _) = GT
compare HsPWildCard _ = LT
compare _ HsPWildCard = GT
compare (HsPIrrPat x) (HsPIrrPat y) = compare x y
instance Ord HsPatField where
compare (HsPFieldPat n1 p1) (HsPFieldPat n2 p2) | n1 == n2 = compare p1 p2
compare (HsPFieldPat n1 _) (HsPFieldPat n2 _) = compare n1 n2
instance Ord HsExp where
compare (HsLit x) (HsLit y) = compare x y
compare (HsLit _) _ = LT
compare _ (HsLit _) = GT
compare (HsCon x) (HsCon y) = compare x y
compare (HsCon _) _ = LT
compare _ (HsCon _) = GT
compare (HsVar x) (HsVar y) = compare x y
compare (HsVar _) _ = LT
compare _ (HsVar _) = GT
compare (HsParen x) (HsParen y) = compare x y
compare (HsParen _) _ = LT
compare _ (HsParen _) = GT
compare (HsNegApp x) (HsNegApp y) = compare x y
compare (HsNegApp _) _ = LT
compare _ (HsNegApp _) = GT
compare (HsApp x1 x2) (HsApp y1 y2) = compare [x1,x2] [y1,y2]
compare (HsApp _ _) _ = LT
compare _ (HsApp _ _) = GT
compare (HsTuple x) (HsTuple y) = compare x y
compare (HsTuple _) _ = LT
compare _ (HsTuple _) = GT
compare (HsList x) (HsList y) = compare x y
compare (HsList _) _ = LT
compare _ (HsList _) = GT
compare HsWildCard _ = LT
compare _ HsWildCard = GT
compare (HsAsPat n1 x) (HsAsPat n2 y) | n1 == n2 = compare x y
compare (HsAsPat n1 _) (HsAsPat n2 _) = compare n1 n2
compare (HsAsPat _ _) _ = LT
compare _ (HsAsPat _ _) = GT
compare (HsLambda a b c) (HsLambda x y z) | a == x && b == y = compare c z
compare (HsLambda a b c) (HsLambda x y z) | a == x = compare b y
compare (HsLambda a b c) (HsLambda x y z) = compare a x
compare (HsLambda _ _ _) _ = LT
compare _ (HsLambda _ _ _) = GT
compare (HsInfixApp x y z) (HsInfixApp a b c) | y == b = compare [x,z] [a,c]
compare (HsInfixApp x y z) (HsInfixApp a b c) = compare y b
compare (HsInfixApp _ _ _) _ = LT
compare _ (HsInfixApp _ _ _) = GT
compare (HsLet a b) (HsLet x y) = compare (a,b) (x,y)
compare (HsLet _ _) _ = LT
compare _ (HsLet _ _) = GT
compare (HsIf a b c) (HsIf x y z) = compare (a,b,c) (x,y,z)
compare (HsIf _ _ _) _ = LT
compare _ (HsIf _ _ _) = GT
compare (HsCase a b) (HsCase x y) = compare (a,b) (x,y)
compare (HsCase _ _) _ = LT
compare _ (HsCase _ _) = GT
compare (HsDo x) (HsDo y) = compare x y
compare (HsDo _) _ = LT
compare _ (HsDo _) = GT
compare (HsLeftSection a b) (HsLeftSection x y) = compare (a,b) (x,y)
compare (HsLeftSection _ _) _ = LT
compare _ (HsLeftSection _ _) = GT
compare (HsRightSection a b) (HsRightSection x y) = compare (a,b) (x,y)
compare (HsRightSection _ _) _ = LT
compare _ (HsRightSection _ _) = GT
compare (HsRecConstr a b) (HsRecConstr x y) = compare (a,b) (x,y)
compare (HsRecConstr _ _) _ = LT
compare _ (HsRecConstr _ _) = GT
compare (HsRecUpdate a b) (HsRecUpdate x y) = compare (a,b) (x,y)
compare (HsRecUpdate _ _) _ = LT
compare _ (HsRecUpdate _ _) = GT
compare (HsEnumFrom x) (HsEnumFrom y) = compare x y
compare (HsEnumFrom _) _ = LT
compare _ (HsEnumFrom _) = GT
compare (HsEnumFromTo a b) (HsEnumFromTo x y) = compare (a,b) (x,y)
compare (HsEnumFromTo _ _) _ = LT
compare _ (HsEnumFromTo _ _) = GT
compare (HsEnumFromThen a b) (HsEnumFromThen x y) = compare (a,b) (x,y)
compare (HsEnumFromThen _ _) _ = LT
compare _ (HsEnumFromThen _ _) = GT
compare (HsEnumFromThenTo a b c) (HsEnumFromThenTo x y z) = compare (a,b,c) (x,y,z)
compare (HsEnumFromThenTo _ _ _) _ = LT
compare _ (HsEnumFromThenTo _ _ _) = GT
compare (HsListComp a b) (HsListComp x y) = compare (a,b) (x,y)
compare (HsListComp _ _) _ = LT
compare _ (HsListComp _ _) = GT
compare (HsExpTypeSig a b c) (HsExpTypeSig x y z) = compare (a,b,c) (x,y,z)
compare (HsExpTypeSig _ _ _) _ = LT
compare _ (HsExpTypeSig _ _ _) = GT
compare (HsIrrPat x) (HsIrrPat y) = compare x y
instance Ord HsDecl where
compare (HsTypeDecl a b c d) (HsTypeDecl w x y z) = compare (a,b,c,d) (w,x,y,z)
compare (HsTypeDecl _ _ _ _) _ = LT
compare _ (HsTypeDecl _ _ _ _) = GT
compare (HsDataDecl a b c d e f) (HsDataDecl m n o p q r) = compare (a,b,c,d,e,f) (m,n,o,p,q,r)
compare (HsDataDecl _ _ _ _ _ _) _ = LT
compare _ (HsDataDecl _ _ _ _ _ _) = GT
compare (HsInfixDecl a b c d) (HsInfixDecl w x y z) = compare (a,b,c,d) (w,x,y,z)
compare (HsInfixDecl _ _ _ _) _ = LT
compare _ (HsInfixDecl _ _ _ _) = GT
compare (HsNewTypeDecl a b c d e f) (HsNewTypeDecl m n o p q r) = compare (a,b,c,d,e,f) (m,n,o,p,q,r)
compare (HsNewTypeDecl _ _ _ _ _ _) _ = LT
compare _ (HsNewTypeDecl _ _ _ _ _ _) = GT
compare (HsClassDecl a b c d e) (HsClassDecl m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q)
compare (HsClassDecl _ _ _ _ _) _ = LT
compare _ (HsClassDecl _ _ _ _ _) = GT
compare (HsInstDecl a b c d e) (HsInstDecl m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q)
compare (HsInstDecl _ _ _ _ _) _ = LT
compare _ (HsInstDecl _ _ _ _ _) = GT
compare (HsDefaultDecl a b) (HsDefaultDecl x y) = compare (a,b) (x,y)
compare (HsDefaultDecl _ _) _ = LT
compare _ (HsDefaultDecl _ _) = GT
compare (HsTypeSig a b c) (HsTypeSig x y z) = compare (a,b,c) (x,y,z)
compare (HsTypeSig _ _ _) _ = LT
compare _ (HsTypeSig _ _ _) = GT
compare (HsFunBind a) (HsFunBind x) = compare a x
compare (HsFunBind _) _ = LT
compare _ (HsFunBind _) = GT
compare (HsPatBind a b c d) (HsPatBind w x y z) = compare (a,b,c,d) (w,x,y,z)
compare (HsPatBind _ _ _ _) _ = LT
compare _ (HsPatBind _ _ _ _) = GT
compare (HsForeignImport a b c d e f) (HsForeignImport m n o p q r) = compare (a,b,c,d,e,f) (m,n,o,p,q,r)
compare (HsForeignImport _ _ _ _ _ _) _ = LT
compare _ (HsForeignImport _ _ _ _ _ _) = GT
compare (HsForeignExport a b c d e) (HsForeignExport m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q)
instance Ord HsRhs where
compare (HsUnGuardedRhs x) (HsUnGuardedRhs y) = compare x y
compare (HsGuardedRhss x) (HsGuardedRhss y) = compare x y
instance Ord HsGuardedRhs where
compare (HsGuardedRhs a b c) (HsGuardedRhs x y z) = compare (a,b,c) (x,y,z)
instance Ord HsMatch where
compare (HsMatch a b c d e) (HsMatch m n o p q) = compare (a,b,c,d,e) (m,n,o,p,q)
instance Ord HsQualType where
compare (HsQualType a b) (HsQualType x y) = compare (a,b) (x,y)
instance Ord HsType where
compare (HsTyFun a b) (HsTyFun x y) = compare (a,b) (x,y)
compare (HsTyFun _ _) _ = LT
compare _ (HsTyFun _ _) = GT
compare (HsTyTuple x) (HsTyTuple y) = compare x y
compare (HsTyTuple _) _ = LT
compare _ (HsTyTuple _) = GT
compare (HsTyApp a b) (HsTyApp x y) = compare (a,b) (x,y)
compare (HsTyApp _ _) _ = LT
compare _ (HsTyApp _ _) = GT
compare (HsTyVar x) (HsTyVar y) = compare x y
compare (HsTyVar _) _ = LT
compare _ (HsTyVar _) = GT
compare (HsTyCon x) (HsTyCon y) = compare x y
instance Ord HsAssoc where
compare HsAssocNone HsAssocNone = EQ
compare HsAssocNone _ = LT
compare _ HsAssocNone = GT
compare HsAssocLeft HsAssocLeft = EQ
compare HsAssocLeft _ = LT
compare _ HsAssocLeft = GT
compare HsAssocRight HsAssocRight = EQ
instance Ord HsConDecl where
compare (HsConDecl a b c) (HsConDecl x y z) = compare (a,b,c) (x,y,z)
compare (HsConDecl _ _ _) _ = LT
compare _ (HsConDecl _ _ _) = GT
compare (HsRecDecl a b c) (HsRecDecl x y z) = compare (a,b,c) (x,y,z)
instance Ord HsBangType where
compare (HsBangedTy x) (HsBangedTy y) = compare x y
compare (HsBangedTy _) _ = LT
compare _ (HsBangedTy _) = GT
compare (HsUnBangedTy x) (HsUnBangedTy y) = compare x y
instance Ord HsFieldUpdate where
compare (HsFieldUpdate a b) (HsFieldUpdate x y) = compare (a,b) (x,y)
instance Ord HsStmt where
compare (HsGenerator a b c) (HsGenerator x y z) = compare (a,b,c) (x,y,z)
compare (HsGenerator _ _ _) _ = LT
compare _ (HsGenerator _ _ _) = GT
compare (HsQualifier x) (HsQualifier y) = compare x y
compare (HsQualifier _) _ = LT
compare _ (HsQualifier _) = GT
compare (HsLetStmt x) (HsLetStmt y) = compare x y
instance Ord HsAlt where
compare (HsAlt a b c d) (HsAlt w x y z) = compare (a,b,c,d) (w,x,y,z)
instance Ord HsGuardedAlts where
compare (HsUnGuardedAlt x) (HsUnGuardedAlt y) = compare x y
compare (HsUnGuardedAlt _) _ = LT
compare _ (HsUnGuardedAlt _) = GT
compare (HsGuardedAlts x) (HsGuardedAlts y) = compare x y
instance Ord HsGuardedAlt where
compare (HsGuardedAlt a b c) (HsGuardedAlt x y z) = compare (a,b,c) (x,y,z)
class Pretty a where
pretty :: a -> String
instance Pretty HsModule where
pretty x = P.prettyPrint x
instance Pretty HsExportSpec where
pretty x = P.prettyPrint x
instance Pretty HsImportDecl where
pretty x = P.prettyPrint x
instance Pretty HsImportSpec where
pretty x = P.prettyPrint x
instance Pretty HsAssoc where
pretty x = P.prettyPrint x
instance Pretty HsDecl where
pretty x = P.prettyPrint x
instance Pretty HsConDecl where
pretty x = P.prettyPrint x
instance Pretty HsBangType where
pretty x = P.prettyPrint x
instance Pretty HsMatch where
--pretty (HsMatch pos f ps rhs whereDecls)
-- = pretty f ++ " " ++ concat (intersperse " " (map pretty ps)) ++ " = " ++ pretty rhs
pretty x = P.prettyPrint x
instance Pretty HsRhs where
pretty x = P.prettyPrint x
instance Pretty HsGuardedRhs where
pretty x = P.prettyPrint x
instance Pretty HsSafety where
pretty x = P.prettyPrint x
instance Pretty HsQualType where
pretty x = P.prettyPrint x
instance Pretty HsType where
pretty x = P.prettyPrint x
instance Pretty HsExp where
pretty x = case x of
HsVar name -> pretty name
HsCon name -> pretty name
HsList list -> (all isChar list)
? (let s = [c | (HsLit (HsChar c)) <- list]
in P.prettyPrint (HsLit (HsString s)))
$ P.prettyPrint (HsList list)
HsApp x arg -> pretty x ++ " (" ++ pretty arg ++ ")"
HsNegApp e@(HsNegApp _) -> "-(" ++ pretty e ++ ")"
HsNegApp e -> "-" ++ pretty e
HsParen e -> "(" ++ pretty e ++ ")"
HsInfixApp e1 (HsQConOp (Special HsCons)) (HsLit (HsInt i))
-> let p = pretty e1
in if take 1 p == "(" then p ++ ":" ++ show i else p ++ show i
HsInfixApp e1 op e2 -> "(" ++ pretty e1 ++ P.prettyPrint op ++ pretty e2 ++ ")"
e -> P.prettyPrint e
isChar (HsLit (HsChar _)) = True
isChar _ = False
instance Pretty HsStmt where
pretty x = P.prettyPrint x
instance Pretty HsFieldUpdate where
pretty x = P.prettyPrint x
instance Pretty HsAlt where
pretty x = P.prettyPrint x
instance Pretty HsGuardedAlts where
pretty x = P.prettyPrint x
instance Pretty HsGuardedAlt where
pretty x = P.prettyPrint x
instance Pretty HsPat where
pretty x = case x of
(HsPInfixApp p1 op p2) -> "(" ++ pretty p1 ++ P.prettyPrint op ++ pretty p2 ++ ")"
e -> P.prettyPrint e
instance Pretty HsPatField where
pretty x = P.prettyPrint x
instance Pretty HsLiteral where
pretty x = P.prettyPrint x
instance Pretty Module where
pretty x = P.prettyPrint x
instance Pretty HsQName where
pretty x = P.prettyPrint x
instance Pretty HsName where
pretty x = P.prettyPrint x
instance Pretty HsQOp where
pretty o = P.prettyPrint o
instance Pretty HsOp where
pretty o = P.prettyPrint o
instance Pretty HsSpecialCon where
pretty HsUnitCon = "()"
pretty HsListCon = "[]"
pretty HsFunCon = "->"
pretty (HsTupleCon i) = "(" ++ take i (repeat ',') ++ ")"
pretty HsCons = ":"
instance Pretty HsCName where
pretty n = P.prettyPrint n
|
arnizamani/occam
|
Instances.hs
|
Haskell
|
mit
| 19,725
|
{-# LANGUAGE OverloadedStrings,NoImplicitPrelude #-}
module TypePlay.Infer.HM where
import Prelude hiding (map,concat)
import Data.List (map,concat,nub,union,intersect)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Monoid ((<>),mconcat)
type Id = Text
enumId :: Int -> Id
enumId = ("v" <>) . T.pack . show
data Kind
= Star
| Kfun Kind Kind
deriving (Eq,Show)
data Type
= TVar Tyvar
| TCon Tycon
| TAp Type Type
| TGen Int
deriving (Eq,Show)
data Tyvar = Tyvar Id Kind
deriving (Eq,Show)
data Tycon = Tycon Id Kind
deriving (Eq,Show)
type Subst = [(Tyvar, Type)]
data InferenceErr
= SubstMerge
| Unification Type Type
| DoesNotOccur Tyvar [Tyvar]
| KindsDontMatch Kind Kind
| TypesDontMatch Type Type
| ClassMisMatch Id Id
| NoSuperClassFound Id
| NoInstancesOfClass Id
type Infer a = Either InferenceErr a
instance Show InferenceErr where
show SubstMerge = "Substitution Merge Failed"
show (Unification t1 t2)
= "Unable to unify" <> show t1 <> " with " <> show t2
show (DoesNotOccur tv t)
= show t <> " not found in " <> show tv
show (KindsDontMatch k1 k2)
= mconcat
[ "Incorrect Kind.\n Found ("
, show k1
, ").\nExpected ("
, show k2
]
show (TypesDontMatch t t')
= mconcat
[ "Could not match types:\n"
, show t
, " with "
, show t'
]
show (ClassMisMatch i i')
= mconcat
[ "Type Classes differ.\n Found("
, show i
, "). Expected ("
, show i'
, ")."
]
show (NoSuperClassFound i)
= mconcat
[ "No type class matching: "
, show i
, " found."
]
show (NoInstancesOfClass i)
= mconcat
[ "No instances of "
, show i
, " found in current environment."
]
typeConst :: Text -> Kind -> Type
typeConst i = TCon . Tycon i
tUnit = typeConst "()" Star
tChar = typeConst "Char" Star
tInt = typeConst "Int" Star
tInteger = typeConst "Integer" Star
tFloat = typeConst "Float" Star
tDouble = typeConst "Double" Star
tList = typeConst "[]" $ Kfun Star Star
tArrow = typeConst "(->)" $ Kfun Star $ Kfun Star Star
tTuple2 = typeConst "(,)" $ Kfun Star $ Kfun Star Star
tString :: Type
tString = list tChar
infixr 4 `fn`
fn :: Type -> Type -> Type
a `fn` b = TAp (TAp tArrow a) b
list :: Type -> Type
list = TAp tList
pair :: Type -> Type -> Type
pair a b = TAp (TAp tTuple2 a) b
class HasKind t where
kind :: t -> Kind
instance HasKind Tyvar where
kind (Tyvar v k) = k
instance HasKind Tycon where
kind (Tycon v k) = k
instance HasKind Type where
kind (TCon tc) = kind tc
kind (TVar u) = kind u
kind (TAp t _) = case kind t of
(Kfun _ k) -> k
nullSubst :: Subst
nullSubst = []
(+->) :: Tyvar -> Type -> Subst
u +-> t = [(u,t)]
class Types t where
apply :: Subst -> t -> t
tv :: t -> [Tyvar]
instance Types Type where
apply s (TVar u) = case lookup u s of
Just t -> t
Nothing -> TVar u
apply s (TAp l r) = TAp (apply s l) (apply s r)
apply s t = t
tv (TVar u) = [u]
tv (TAp l r) = tv l `union` tv r
tv t = []
instance Types a => Types [a] where
apply s = fmap (apply s)
tv = nub . concat . fmap tv
infixr 4 @@
(@@) :: Subst -> Subst -> Subst
s1 @@ s2 = [ (u, apply s1 t) | (u,t) <- s2] <> s1
merge :: Subst -> Subst -> Infer Subst
merge s1 s2 = if agree
then Right $ s1 <> s2
else Left SubstMerge
where
agree = all (\v -> apply s1 (TVar v) == apply s2 (TVar v))
(gFst s1 `intersect` gFst s2)
gFst = fmap fst
mgu :: Type -> Type -> Infer Subst
mgu (TAp l r) (TAp l' r') = do
s1 <- mgu l l'
s2 <- mgu (apply s1 r) (apply s1 r')
return $ s2 @@ s1
mgu (TVar u) t = varBind u t
mgu t (TVar u) = varBind u t
mgu (TCon tc1) (TCon tc2)
| tc1 == tc2 = return nullSubst
mgu t1 t2 = Left $ Unification t1 t2
varBind :: Tyvar -> Type -> Infer Subst
varBind u t
| t == TVar u = return nullSubst
| u `elem` tv t = Left $ DoesNotOccur u $ tv t
| kind u /= kind t = Left $ KindsDontMatch (kind u) (kind t)
| otherwise = return $ u +-> t
match :: Type -> Type -> Infer Subst
match (TAp l r) (TAp l' r') = do
sl <- match l l'
sr <- match r r'
merge sl sr
match (TVar u) t
| kind u == kind t = return $ u +-> t
match (TCon tcl) (TCon tcr)
| tcl == tcr = return nullSubst
match t1 t2 = Left $ TypesDontMatch t1 t2
-- Type Classes
data Qual t = [Pred] :=> t
deriving (Show,Eq)
data Pred = IsIn Id Type
deriving (Show,Eq)
-- Example 'Num a => a -> Int'
-- [IsIn "Num" (TVar (Tyvar "a" Star))]
-- :=> (TVar (Tyvar "a" Star) 'fn' tInt)
instance Types t => Types (Qual t) where
apply s (ps :=> t) = apply s ps :=> apply s t
tv (ps :=> t) = tv ps `union` tv t
instance Types Pred where
apply s (IsIn i t) = IsIn i (apply s t)
tv (IsIn i t) = tv t
mguPred :: Pred -> Pred -> Infer Subst
mguPred = lift mgu
matchPred :: Pred -> Pred -> Infer Subst
matchPred = lift match
lift
:: (Type -> Type -> Infer b)
-> Pred
-> Pred
-> Infer b
lift m (IsIn i t) (IsIn i' t')
| i == i' = m t t'
| otherwise = Left $ ClassMisMatch i i'
type Class = ([Id], [Inst])
type Inst = Qual Pred
data ClassEnv = ClassEnv
{ classes :: Id -> Maybe Class
, defaults :: [Type]
}
super :: ClassEnv -> Id -> Infer [Id]
super ce i = case classes ce i of
Just (is, its) -> return is
Nothing -> Left $ NoSuperClassFound i
insts :: ClassEnv -> Id -> Infer [Inst]
insts ce i = case classes ce i of
Just (is, its) -> return its
Nothing -> Left $ NoInstancesOfClass i
modify :: ClassEnv -> Id -> Class -> ClassEnv
modify ce i c = ce { classes = \j -> if i == j
then Just c
else classes ce j
}
initialEnv :: ClassEnv
initialEnv = ClassEnv { classes = \i -> Nothing
, defaults = [tInteger, tDouble]
}
|
mankyKitty/TypePlay
|
src/TypePlay/Infer/HM.hs
|
Haskell
|
mit
| 6,014
|
import Data.Tree
import Data.Tree.Zipper
import Data.Maybe
import Test.QuickCheck
import System.Random
import Text.Show.Functions
instance Arbitrary a => Arbitrary (Tree a) where
arbitrary = sized arbTree
where
arbTree n = do lbl <- arbitrary
children <- resize (n-1) arbitrary
return (Node lbl children)
coarbitrary t =
coarbitrary (rootLabel t) .
variant (length (subForest t)) .
flip (foldr coarbitrary) (subForest t)
instance Arbitrary a => Arbitrary (TreeLoc a) where
arbitrary = do
tree <- resize 8 arbitrary
lefts <- resize 5 arbitrary
rights <- resize 5 arbitrary
parents <- resize 3 arbitrary
return (Loc tree lefts rights parents)
prop_LeftRight :: TreeLoc Int -> Property
prop_LeftRight loc = label "prop_LeftRight" $
case left loc of
Just lloc -> right lloc == Just loc
Nothing -> True
prop_LeftFirst :: TreeLoc Int -> Property
prop_LeftFirst loc = label "prop_LeftFirst" $
isFirst loc ==> left loc == Nothing
prop_RightLast :: TreeLoc Int -> Property
prop_RightLast loc = label "prop_RightLast" $
isLast loc ==> right loc == Nothing
prop_RootParent :: TreeLoc Int -> Property
prop_RootParent loc = label "prop_RootParent" $
isRoot loc ==> parent loc == Nothing
prop_FirstChild :: TreeLoc Int -> Property
prop_FirstChild loc = label "prop_FirstChild" $
case firstChild loc of
Just floc -> parent floc == Just loc && left floc == Nothing
Nothing -> isLeaf loc
prop_LastChild :: TreeLoc Int -> Property
prop_LastChild loc = label "prop_LastChild" $
case lastChild loc of
Just lloc -> parent lloc == Just loc && right lloc == Nothing
Nothing -> isLeaf loc
prop_FindChild :: TreeLoc Int -> Property
prop_FindChild loc = label "prop_FindChild" $
forAll arbitrary (\f -> maybe True (\sloc -> f (tree sloc) && parent sloc == Just loc) (findChild f loc))
prop_SetGetLabel :: TreeLoc Int -> Property
prop_SetGetLabel loc = label "prop_SetGetLabel" $
forAll arbitrary (\x -> getLabel (setLabel x loc) == x)
prop_ModifyLabel :: TreeLoc Int -> Property
prop_ModifyLabel loc = label "prop_ModifyLabel" $
forAll arbitrary (\f -> getLabel (modifyLabel f loc) == f (getLabel loc))
prop_UpDown :: TreeLoc Int -> Property
prop_UpDown loc = label "prop_UpDown" $
case parent loc of
Just ploc -> getChild (getNodeIndex loc) ploc == Just loc
Nothing -> True
prop_RootChild :: TreeLoc Int -> Property
prop_RootChild loc = label "prop_RootChild" $
isChild loc == not (isRoot loc)
prop_ChildrenLeaf :: TreeLoc Int -> Property
prop_ChildrenLeaf loc = label "prop_ChildrenLeaf" $
hasChildren loc == not (isLeaf loc)
prop_FromToTree :: TreeLoc Int -> Property
prop_FromToTree loc = label "prop_FromToTree" $
tree (fromTree (toTree loc)) == tree (root loc)
prop_FromToForest :: TreeLoc Int -> Property
prop_FromToForest loc = label "prop_FromToForest" $
isFirst (root loc) ==> fromForest (toForest loc) == Just (root loc)
prop_FromTree :: Tree Int -> Property
prop_FromTree tree = label "prop_FromTree" $
left (fromTree tree) == Nothing &&
right (fromTree tree) == Nothing &&
parent (fromTree tree) == Nothing
prop_FromForest :: Property
prop_FromForest = label "prop_FromForest" $
fromForest ([] :: Forest Int) == Nothing
prop_InsertLeft :: TreeLoc Int -> Property
prop_InsertLeft loc = label "prop_InsertLeft" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertLeft t loc) == t &&
rights (insertLeft t loc) == tree loc : rights loc
prop_InsertRight :: TreeLoc Int -> Property
prop_InsertRight loc = label "prop_InsertRight" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertRight t loc) == t &&
lefts (insertRight t loc) == tree loc : lefts loc
prop_InsertDownFirst :: TreeLoc Int -> Property
prop_InsertDownFirst loc = label "prop_InsertDownFirst" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertDownFirst t loc) == t &&
left (insertDownFirst t loc) == Nothing &&
fmap getLabel (parent (insertDownFirst t loc)) == Just (getLabel loc) &&
fmap tree (right (insertDownFirst t loc)) == fmap tree (firstChild loc)
prop_InsertDownLast :: TreeLoc Int -> Property
prop_InsertDownLast loc = label "prop_InsertDownLast" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertDownLast t loc) == t &&
right (insertDownLast t loc) == Nothing &&
fmap getLabel (parent (insertDownLast t loc)) == Just (getLabel loc) &&
fmap tree (left (insertDownLast t loc)) == fmap tree (lastChild loc)
prop_InsertDownAt :: TreeLoc Int -> Property
prop_InsertDownAt loc = label "prop_InsertDownAt" $
forAll (resize 10 arbitrary) $ \t ->
forAll (resize 10 arbitrary) $ \n ->
maybe t tree (insertDownAt n t loc) == t &&
fmap lefts (getChild n loc) == fmap lefts (insertDownAt n t loc) &&
fmap tree (getChild n loc) == fmap tree (insertDownAt n t loc >>= right) &&
fmap rights (getChild n loc) == fmap rights (insertDownAt n t loc >>= right) &&
maybe (getLabel loc) getLabel (insertDownAt n t loc >>= parent) == getLabel loc
prop_Delete :: TreeLoc Int -> Property
prop_Delete loc = label "prop_Delete" $
if not (isLast loc)
then fmap (\loc -> tree loc : rights loc) (delete loc) == Just (rights loc) &&
fmap lefts (delete loc) == Just (lefts loc)
else if not (isFirst loc)
then fmap rights (delete loc) == Just (rights loc) &&
fmap (\loc -> tree loc : lefts loc) (delete loc) == Just (lefts loc)
else fmap (insertDownFirst (tree loc)) (delete loc) == Just loc
main = do
testProp prop_LeftRight
testProp prop_LeftFirst
testProp prop_RightLast
testProp prop_RootParent
testProp prop_FirstChild
testProp prop_LastChild
testProp prop_FindChild
testProp prop_SetGetLabel
testProp prop_ModifyLabel
testProp prop_UpDown
testProp prop_RootChild
testProp prop_ChildrenLeaf
testProp prop_FromToTree
testProp prop_FromToForest
testProp prop_FromTree
testProp prop_FromForest
testProp prop_InsertLeft
testProp prop_InsertRight
testProp prop_InsertDownFirst
testProp prop_InsertDownLast
testProp prop_InsertDownAt
testProp prop_Delete
testProp :: Testable a => a -> IO ()
testProp = check (defaultConfig{-configEvery = \n args -> ""-})
|
yav/haskell-zipper
|
test.hs
|
Haskell
|
mit
| 6,455
|
-- Examples from chapter 5
-- http://learnyouahaskell.com/recursion
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x:replicate' (n-1) x
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' _ [] = []
take' n (x:xs)
| n <= 0 = []
| otherwise = x : take' (n-1) xs
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
repeat' :: a -> [a]
repeat' x = x : repeat' x
zip' :: [a] -> [b] -> [(a,b)]
zip' [] _ = []
zip' _ [] = []
zip' (x:xs) (y:ys) = (x,y) : zip' xs ys
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ biggerSorted
|
Sgoettschkes/learning
|
haskell/LearnYouAHaskell/05.hs
|
Haskell
|
mit
| 902
|
module Main (main) where
import System.Console.GetOpt
import System.IO
import System.Environment
import System.Exit
import qualified System.IO as SIO
import Data.ByteString
import Data.Word
import Data.ListLike.CharString
import qualified Data.Iteratee as I
import qualified Data.Iteratee.ListLike as IL
import qualified Data.Iteratee.IO.Handle as IOH
import Data.Iteratee.Base.ReadableChunk
import Data.Iteratee ((><>),(<><))
import Data.Iteratee.Char
import qualified Data.Iteratee.Char as IC
main :: IO ()
main =
do let
enum = I.enumPure1Chunk [1..1000::Int]
it = (I.joinI $ (I.take 15 ><> I.take 10) I.stream2list)
rs <- enum it >>= I.run
print rs
--
handle <- openFile "iterdata/source.txt" ReadMode
let
enum2 = IL.take 20
it2 = I.joinI $ enum2 (I.stream2list::I.Iteratee ByteString IO [Word8])
i <- IOH.enumHandle 22 handle it2 >>= I.run
str <- SIO.hGetLine handle
SIO.putStr $ str ++ "\n"
SIO.hClose handle
-- Enumerating a handle over a finished iteratee doesn't read
-- from the handle, and doesn't throw an exception
handle <- openFile "iterdata/source.txt" ReadMode
let
finishediter = I.idone () (I.EOF Nothing::I.Stream [Word8])
i <- IOH.enumHandle 22 handle finishediter >>= I.run
str <- SIO.hGetLine handle
SIO.putStr $ str ++ "\n"
SIO.hClose handle
-- I wonder... can you compose an already "started" iteratee
-- with another iteratee?
handle <- openFile "iterdata/smallfile.txt" ReadMode
let
enum3 = IL.take 4
it3 = I.joinI $ enum3 (I.stream2list::I.Iteratee [Char] IO [Char])
enum4 = IL.take 4
it4 = I.joinI $ enum4 (I.stream2list::I.Iteratee [Char] IO [Char])
ii <- IOH.enumHandle 22 handle it3
SIO.hClose handle
let
combined = ii >> it4
handle <- openFile "iterdata/smallfile2.txt" ReadMode
iii <- IOH.enumHandle 22 handle combined >>= I.run
SIO.hClose handle
print iii
|
danidiaz/haskell-sandbox
|
iteratee.hs
|
Haskell
|
mit
| 2,218
|
-- Primes in numbers
-- http://www.codewars.com/kata/54d512e62a5e54c96200019e/
module Codewars.Kata.PrFactors where
import Data.List (unfoldr, findIndex, group)
import Data.Maybe (fromJust)
prime_factors :: Integer -> String
prime_factors k | isPrime k = "("++ show k ++")"
| otherwise = concatMap g . group . unfoldr f $ (k, 0)
where primes = sieve [2..]
sieve (n:ns) = n : sieve [n' | n' <- ns, n' `mod` n /= 0]
isPrime x = all (\d -> x `mod` d /= 0) [2 .. floor . sqrt . fromIntegral $ x]
f (1, _) = Nothing
f (n, i) | isPrime n = Just (n, (1, 0))
| otherwise = if m == 0 then Just (primes !! i , (d, i)) else Just (primes !! newI, (n `div` (primes !! newI), newI) )
where (d, m) = n `divMod` (primes !! i)
newI :: Int
newI = succ . (+i) . fromJust . findIndex (\x-> n `mod` x == 0) . drop (i+1) $ primes
g :: [Integer] -> String
g ps = "(" ++ (show . head $ ps) ++ (if length ps > 1 then "**" ++ (show . length $ ps) else "") ++ ")"
|
gafiatulin/codewars
|
src/5 kyu/PrFactors.hs
|
Haskell
|
mit
| 1,095
|
module Main where
import Synonyms
import Test.Hspec
main :: IO ()
main = hspec $ do
let d = Definition "foo" ["b"] in
describe "lookupDefinition" $ do
it "returns Nothing when no matches" $
lookupDefinition "a" [d] `shouldBe` Nothing
it "returns Just Definition when found" $
lookupDefinition "foo" [d] `shouldBe` Just d
describe "definitions" $
it "converts a list of definitions" $
definitions ["foo bar baz"] `shouldBe` [Definition "foo" ["bar", "baz"]]
describe "convertToDefinition" $
it "converts to a definition" $
convertToDefinition "foo bar baz" `shouldBe` Definition "foo" ["bar", "baz"]
|
justincampbell/synonyms
|
Spec.hs
|
Haskell
|
mit
| 720
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Simulation.Node.Service.Http
( HttpService
, Service
, Routes (..)
, activate
, as
, toSnapRoutes
, selfStore
, basePrefix
, module Snap.Core
) where
import Control.Applicative (Applicative, Alternative, (<$>))
import Control.Monad (MonadPlus)
import Control.Monad.Reader (ReaderT, MonadIO, runReaderT)
import Control.Monad.Reader.Class (MonadReader, ask)
import Control.Monad.CatchIO (MonadCatchIO)
import qualified Data.ByteString.Char8 as BS
import Snap.Core
import Snap.Http.Server
import System.FilePath ((</>))
-- | The HttpService monad.
newtype HttpService a =
HttpService { extractHttpService :: ReaderT HttpServiceApiParam Snap a }
deriving ( Functor, Applicative, Alternative, Monad
, MonadPlus, MonadReader HttpServiceApiParam
, MonadIO, MonadCatchIO, MonadSnap )
-- | Record with api parameters for the execution of the HttpService monad.
data HttpServiceApiParam =
HttpServiceApiParam { selfStore_ :: !FilePath
, basePrefix_ :: !String}
deriving Show
-- | A type describing a service's route mapping between an url and
-- a handler for the request.
newtype Routes a = Routes [ (BS.ByteString, HttpService a) ]
-- | A type describing a prepared service, ready to install.
newtype Service a = Service [ (BS.ByteString, HttpService a, String) ]
-- | Activate the http services, at the given port, in the current
-- thread.
activate :: Int -> [Service ()] -> IO ()
activate port services = do
let config = setPort port defaultConfig
routes = toSnapRoutes services
httpServe config $ route routes
-- | Convert a set of routes and a prefix to a proper service.
as :: Routes a -> BS.ByteString -> Service a
as (Routes xs) prefix =
let prefix' = prefix `BS.snoc` '/'
in Service $
map (\(url, action) ->
(prefix' `BS.append` url, action, BS.unpack prefix')) xs
-- | Convert a list of installments to a list of proper snap
-- routes. The HttpService monad will be evaluated down to the snap
-- monad in this step.
toSnapRoutes :: [Service a] -> [(BS.ByteString, Snap a)]
toSnapRoutes = concatMap (\(Service xs') -> map toSnap xs')
-- | Fetch own's self store position in the file system (relative to
-- current working directory). E.g. if the service's name is foo the
-- selfStore will return httpServices/foo/ as the directory where
-- static data for the service can be stored.
selfStore :: HttpService FilePath
selfStore = selfStore_ <$> ask
-- | Fetch own's base prefix url. This is to be used for any kind of
-- linking to resources inside the own service to that the service
-- name always become the prefix in the url.
basePrefix :: HttpService String
basePrefix = basePrefix_ <$> ask
-- | Run an HttpService in the Snap monad.
runHttpService :: HttpService a -> HttpServiceApiParam -> Snap a
runHttpService action = runReaderT (extractHttpService action)
toSnap :: (BS.ByteString, HttpService a, String) -> (BS.ByteString, Snap a)
toSnap (url, action, prefix) = (url, runHttpService action makeParam)
where
makeParam :: HttpServiceApiParam
makeParam = HttpServiceApiParam ("httpServices" </> prefix)
('/':prefix)
|
kosmoskatten/programmable-endpoint
|
src/Simulation/Node/Service/Http.hs
|
Haskell
|
mit
| 3,288
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Alder.Html.Internal
( -- * Elements
Node(..)
-- * Attributes
, Id
, Handlers
, Attributes(..)
, defaultAttributes
-- * Html
, Html
, HtmlM(..)
, runHtml
, parent
, leaf
, text
-- * Event handlers
, EventType(..)
, Event(..)
, Handler(..)
-- * Setting attributes
, Attribute
, Attributable
, (!)
, (!?)
, (!#)
, (!.)
, (!?.)
, key
-- * Creating attributes
, attribute
, boolean
, onEvent
) where
import Control.Applicative
import Data.DList as DList
import Data.Hashable
import Data.HashMap.Strict as HashMap hiding ((!))
import Data.Monoid
import Data.Text as Text
import Data.Tree
import Unsafe.Coerce
import Alder.JavaScript
infixl 1 !, !?, !#, !., !?.
data Node
= Element !Text Attributes
| Text !Text
type Id = Text
type Handlers = HashMap EventType (JSObj -> IO ())
data Attributes = Attributes
{ elementId :: !(Maybe Id)
, elementKey :: !(Maybe Int)
, elementClass :: ![Text]
, otherAttributes :: !(HashMap Text Text)
, handlers :: !Handlers
}
defaultAttributes :: Attributes
defaultAttributes = Attributes
{ elementId = Nothing
, elementKey = Nothing
, elementClass = []
, otherAttributes = HashMap.empty
, handlers = HashMap.empty
}
type Html = HtmlM ()
newtype HtmlM a = HtmlM (Attributes -> DList (Tree Node))
deriving (Monoid)
instance Functor HtmlM where
fmap _ = unsafeCoerce
instance Applicative HtmlM where
pure _ = mempty
(<*>) = appendHtml
instance Monad HtmlM where
return _ = mempty
(>>) = appendHtml
m >>= k = m `appendHtml` k (error "Alder.HtmlM: monadic bind")
appendHtml :: HtmlM a -> HtmlM b -> HtmlM c
appendHtml a b = unsafeCoerce a <> unsafeCoerce b
runHtml :: Html -> Forest Node
runHtml (HtmlM f) = DList.toList (f defaultAttributes)
parent :: Text -> Html -> Html
parent t h = HtmlM $ \a -> DList.singleton (Node (Element t a) (runHtml h))
leaf :: Text -> Html
leaf t = HtmlM $ \a -> DList.singleton (Node (Element t a) [])
text :: Text -> Html
text t = HtmlM $ \_ -> DList.singleton (Node (Text t) [])
addAttribute :: Attribute -> HtmlM a -> HtmlM a
addAttribute (Attribute f) (HtmlM g) = HtmlM (g . f)
data EventType
= KeyDown | KeyPress | KeyUp
| Focus | Blur
| Input | Change
| Submit
| MouseDown | MouseUp | Click | DoubleClick | MouseMove | MouseEnter | MouseLeave
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance Hashable EventType where
hashWithSalt s = hashWithSalt s . fromEnum
class Event e where
extractEvent :: JSObj -> IO e
class Handler f where
fire :: f e -> e -> IO ()
newtype Attribute = Attribute (Attributes -> Attributes)
instance Monoid Attribute where
mempty = Attribute id
mappend (Attribute f) (Attribute g) = Attribute (f . g)
class Attributable h where
(!) :: h -> Attribute -> h
instance Attributable (HtmlM a) where
(!) = flip addAttribute
instance Attributable h => Attributable (r -> h) where
f ! a = (! a) . f
(!?) :: Attributable h => h -> (Bool, Attribute) -> h
h !? (p, a) = if p then h ! a else h
(!#) :: Attributable h => h -> Text -> h
h !# v = h ! Attribute addId
where
addId a = a { elementId = Just v }
(!.) :: Attributable h => h -> Text -> h
h !. v = h ! Attribute addClass
where
addClass a = a { elementClass = v : elementClass a }
(!?.) :: Attributable h => h -> (Bool, Text) -> h
h !?. (p, v) = if p then h !. v else h
key :: Int -> Attribute
key i = Attribute $ \a -> a { elementKey = Just i }
attribute :: Text -> Text -> Attribute
attribute k v = Attribute $ \a ->
a { otherAttributes = HashMap.insert k v (otherAttributes a) }
boolean :: Text -> Attribute
boolean k = attribute k ""
onEvent :: (Handler f, Event e) => EventType -> f e -> Attribute
onEvent k handler = Attribute $ \a ->
a { handlers = HashMap.insert k h (handlers a) }
where
h v = do
e <- extractEvent v
fire handler e
|
ghcjs/ghcjs-sodium
|
src/Alder/Html/Internal.hs
|
Haskell
|
mit
| 4,281
|
module Main where
data MyBool = MyTrue | MyFalse
foo a MyFalse b = 0
foo c MyTrue d = 1
bar a = 2
main_ = foo 1 MyFalse 2
|
Ekleog/hasklate
|
examples/BasicPatternMatching.hs
|
Haskell
|
mit
| 126
|
module Propellor.Property.Tor where
import Propellor
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.Service as Service
import Utility.FileMode
import Utility.DataUnits
import System.Posix.Files
import Data.Char
import Data.List
type HiddenServiceName = String
type NodeName = String
-- | Sets up a tor bridge. (Not a relay or exit node.)
--
-- Uses port 443
isBridge :: Property NoInfo
isBridge = configured
[ ("BridgeRelay", "1")
, ("Exitpolicy", "reject *:*")
, ("ORPort", "443")
]
`describe` "tor bridge"
`requires` server
-- | Sets up a tor relay.
--
-- Uses port 443
isRelay :: Property NoInfo
isRelay = configured
[ ("BridgeRelay", "0")
, ("Exitpolicy", "reject *:*")
, ("ORPort", "443")
]
`describe` "tor relay"
`requires` server
-- | Makes the tor node be named, with a known private key.
--
-- This can be moved to a different IP without needing to wait to
-- accumulate trust.
named :: NodeName -> Property HasInfo
named n = configured [("Nickname", n')]
`describe` ("tor node named " ++ n')
`requires` torPrivKey (Context ("tor " ++ n))
where
n' = saneNickname n
torPrivKey :: Context -> Property HasInfo
torPrivKey context = f `File.hasPrivContent` context
`onChange` File.ownerGroup f user (userGroup user)
-- install tor first, so the directory exists with right perms
`requires` Apt.installed ["tor"]
where
f = "/var/lib/tor/keys/secret_id_key"
-- | A tor server (bridge, relay, or exit)
-- Don't use if you just want to run tor for personal use.
server :: Property NoInfo
server = configured [("SocksPort", "0")]
`requires` Apt.installed ["tor", "ntp"]
`describe` "tor server"
-- | Specifies configuration settings. Any lines in the config file
-- that set other values for the specified settings will be removed,
-- while other settings are left as-is. Tor is restarted when
-- configuration is changed.
configured :: [(String, String)] -> Property NoInfo
configured settings = File.fileProperty "tor configured" go mainConfig
`onChange` restarted
where
ks = map fst settings
go ls = sort $ map toconfig $
filter (\(k, _) -> k `notElem` ks) (map fromconfig ls)
++ settings
toconfig (k, v) = k ++ " " ++ v
fromconfig = separate (== ' ')
data BwLimit
= PerSecond String
| PerDay String
| PerMonth String
-- | Limit incoming and outgoing traffic to the specified
-- amount each.
--
-- For example, PerSecond "30 kibibytes" is the minimum limit
-- for a useful relay.
bandwidthRate :: BwLimit -> Property NoInfo
bandwidthRate (PerSecond s) = bandwidthRate' s 1
bandwidthRate (PerDay s) = bandwidthRate' s (24*60*60)
bandwidthRate (PerMonth s) = bandwidthRate' s (31*24*60*60)
bandwidthRate' :: String -> Integer -> Property NoInfo
bandwidthRate' s divby = case readSize dataUnits s of
Just sz -> let v = show (sz `div` divby) ++ " bytes"
in configured [("BandwidthRate", v)]
`describe` ("tor BandwidthRate " ++ v)
Nothing -> property ("unable to parse " ++ s) noChange
hiddenServiceAvailable :: HiddenServiceName -> Int -> Property NoInfo
hiddenServiceAvailable hn port = hiddenServiceHostName prop
where
prop = configured
[ ("HiddenServiceDir", varLib </> hn)
, ("HiddenServicePort", unwords [show port, "127.0.0.1:" ++ show port])
]
`describe` "hidden service available"
hiddenServiceHostName p = adjustPropertySatisfy p $ \satisfy -> do
r <- satisfy
h <- liftIO $ readFile (varLib </> hn </> "hostname")
warningMessage $ unwords ["hidden service hostname:", h]
return r
hiddenService :: HiddenServiceName -> Int -> Property NoInfo
hiddenService hn port = configured
[ ("HiddenServiceDir", varLib </> hn)
, ("HiddenServicePort", unwords [show port, "127.0.0.1:" ++ show port])
]
`describe` unwords ["hidden service available:", hn, show port]
hiddenServiceData :: IsContext c => HiddenServiceName -> c -> Property HasInfo
hiddenServiceData hn context = combineProperties desc
[ installonion "hostname"
, installonion "private_key"
]
where
desc = unwords ["hidden service data available in", varLib </> hn]
installonion f = withPrivData (PrivFile $ varLib </> hn </> f) context $ \getcontent ->
property desc $ getcontent $ install $ varLib </> hn </> f
install f content = ifM (liftIO $ doesFileExist f)
( noChange
, ensureProperties
[ property desc $ makeChange $ do
createDirectoryIfMissing True (takeDirectory f)
writeFileProtected f content
, File.mode (takeDirectory f) $ combineModes
[ownerReadMode, ownerWriteMode, ownerExecuteMode]
, File.ownerGroup (takeDirectory f) user (userGroup user)
, File.ownerGroup f user (userGroup user)
]
)
restarted :: Property NoInfo
restarted = Service.restarted "tor"
mainConfig :: FilePath
mainConfig = "/etc/tor/torrc"
varLib :: FilePath
varLib = "/var/lib/tor"
varRun :: FilePath
varRun = "/var/run/tor"
user :: User
user = User "debian-tor"
type NickName = String
-- | Convert String to a valid tor NickName.
saneNickname :: String -> NickName
saneNickname s
| null n = "unnamed"
| otherwise = n
where
legal c = isNumber c || isAsciiUpper c || isAsciiLower c
n = take 19 $ filter legal s
|
sjfloat/propellor
|
src/Propellor/Property/Tor.hs
|
Haskell
|
bsd-2-clause
| 5,177
|
{-# LANGUAGE TypeFamilies, OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Xournal.Map
-- Copyright : (c) 2011, 2012 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
module Data.Xournal.Map where
import Data.IntMap
import Data.Xournal.Simple
import Data.Xournal.Generic
import Data.Xournal.BBox
type TPageMap = GPage Background IntMap TLayerSimple
type TXournalMap = GXournal [] TPageMap
type TPageBBoxMap = GPage Background IntMap TLayerBBox
type TXournalBBoxMap = GXournal IntMap TPageBBoxMap
type TPageBBoxMapBkg b = GPage b IntMap TLayerBBox
type TXournalBBoxMapBkg b = GXournal IntMap (TPageBBoxMapBkg b)
emptyGXournalMap :: GXournal IntMap a
emptyGXournalMap = GXournal "" empty
|
wavewave/xournal-types
|
src/Data/Xournal/Map.hs
|
Haskell
|
bsd-2-clause
| 875
|
module Interface.LpSolve where
-- standard modules
-- local modules
import Helpful.Process
--import Data.Time.Clock (diffUTCTime, getCurrentTime)
--import Debug.Trace
zeroObjective :: String -> Maybe Bool
zeroObjective p = case head answer of
"This problem is infeasible" -> Nothing
"This problem is unbounded" -> Just False
otherwise -> do
let (chattering, value) = splitAt 29 (answer!!1)
if chattering == "Value of objective function: " then
if (read value :: Float) == 0.0 then
Just True
else
Just False
else
error $ "lp_solve answered in an unexpected way.\n" ++
"Expected Answer: \"Value of objective function: " ++
"NUMBER\"\nActual Answer: " ++ lpAnswer
where
lpAnswer = unsafeReadProcess "lp_solve" [] p
answer = lines lpAnswer
-- old version
--zeroObjective :: String -> Maybe Bool
--zeroObjective p = unsafePerformIO $ do
---- start <- getCurrentTime
-- (_, clpAnswer, _) <- readProcessWithExitCode "lp_solve" [] p
-- let answer = lines clpAnswer
---- end <- getCurrentTime
---- print $ (show (end `diffUTCTime` start) ++ " elapsed. ") ++ clpAnswer
-- case head answer of
-- "This problem is infeasible" -> return Nothing
-- "This problem is unbounded" -> return $ Just False
-- otherwise -> do
-- let (chattering, value) = splitAt 29 (answer!!1)
-- if chattering == "Value of objective function: " then
-- if (read value :: Float) == 0.0 then
-- return $ Just True
-- else
-- return $ Just False
-- else
-- error $ "lp_solve answered in an unexpected way.\n" ++
-- "Expected Answer: \"Value of objective function: " ++
-- "NUMBER\"\nActual Answer: " ++ clpAnswer
--{-# NOINLINE zeroObjective #-}
|
spatial-reasoning/zeno
|
src/Interface/LpSolve.hs
|
Haskell
|
bsd-2-clause
| 1,952
|
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances #-}
module Lambda.DataType.SExpr where
import DeepControl.Applicative
import DeepControl.Monad
import Lambda.DataType.Common
import Lambda.DataType.PatternMatch (PM)
import qualified Lambda.DataType.PatternMatch as PM
import Lambda.DataType.Type (Type((:->)))
import qualified Lambda.DataType.Type as Ty
import Util.Pseudo
import qualified Util.LISP as L
import Data.List (unwords, intersperse)
import Data.Foldable (fold)
-- | sugared expression
data SExpr = BOOL Bool MSP
| INT Integer MSP
| CHAR Char MSP
| UNIT MSP
| VAR Name MSP -- variable
| OPR String MSP -- symbolic operator
-- tuple
| TUPLE [SExpr] MSP
| TPLPrj SExpr Index
-- tag
| TAGPrj SExpr (Name, Index)
--
| FIX SExpr MSP
-- syntax
| IF SExpr SExpr SExpr MSP
| CASE SExpr [(PM, SExpr)] MSP
-- sentence
| TYPESig (Name, Type) MSP
| DEF Name [([PM], SExpr, MSP)]
| BNF Name [(Name, [Type])] MSP
-- quote
| QUT SExpr MSP -- quote
| QQUT SExpr MSP -- quasi-quote
| UNQUT SExpr MSP -- unquote
-- syntactic-sugar
| APP SExpr [SExpr] MSP -- application
| APPSeq [SExpr] MSP -- infix application sequence
| LAM [(PM, Type)] SExpr MSP -- lambda
| LAMM [(PM, Type)] SExpr MSP -- lambda-macro
| AS (SExpr, Type) MSP -- ascription
| LET (PM, Type) SExpr SExpr MSP
| LETREC (Name, Type) SExpr SExpr MSP
-- list
| NIL MSP
| CONS SExpr SExpr MSP
| HEAD SExpr
| TAIL SExpr
deriving (Eq)
unit = UNIT Nothing
var name = VAR name Nothing
bool b = BOOL b Nothing
int n = INT n Nothing
char c = CHAR c Nothing
nil = NIL Nothing
cons a d = CONS a d Nothing
tuple xs = TUPLE xs Nothing
fix x = FIX x Nothing
app x xs = APP x xs Nothing
appseq xs = APPSeq xs Nothing
lam ps x = LAM ps x Nothing
lamm ps x = LAMM ps x Nothing
let_ p x1 x2 = LET p x1 x2 Nothing
letrec p x1 x2 = LETREC p x1 x2 Nothing
instance L.LISP SExpr where
car (CONS a _ _) = a
car _ = error "car: empty structure"
cdr (CONS _ d _) = d
cdr _ = error "cdr: empty structure"
cons a d = CONS a d Nothing
nil = NIL Nothing
isCell (CONS _ _ _) = True
isCell _ = False
instance Show SExpr where
-- value
show (BOOL bool _) = show bool
show (INT n _) = show n
show (CHAR c _) = "'"++ [c] ++"'"
-- variable
show (UNIT _) = "_"
show (VAR name _) = if isSymbolic name
then "("++ name ++")"
else name
show (OPR sym _) = sym
-- tuple
show (TUPLE xs _) = show |$> xs
>- (intersperse ", " >-> fold)
>- \s -> "("++ s ++ ")"
-- apply
show (FIX lambda _) = "(fix " ++ show lambda ++")"
show (TPLPrj x n) = show x ++"."++ show n
show (TAGPrj x (name,n)) = "("++ show x ++")."++ name ++"["++ show n ++"]"
-- syntax
show (IF e1 e2 e3 _) = "if "++ show e1 ++" then "++ show e2 ++" else "++ show e3
show (CASE e pairs _) = "case "++ show e ++" of "++ (pairs <$| (\(pm,e) -> show pm ++" -> "++ show e)
>- (intersperse " | " >-> fold))
-- sentence
show (TYPESig (name, ty) _) = if isSymbolic name
then "("++ name ++") :: "++ show ty
else name ++" :: "++ show ty
show (DEF name defs) = fold $ intersperse "\n" $ defs <$| showdef
where
showdef ([],s,_) = showname ++" = "++ show s
showdef (pms,s,_) = showname ++" "++ (unwords $ pms <$| show) ++" = "++ show s
showname = if isSymbolic name
then "("++ name ++")"
else name
show (BNF name tags _) = "data "++ name ++" = "++ ((showTag |$> tags) >- (intersperse " | " >-> fold))
where
showTag (name, []) = name
showTag (name, tys) = name ++" "++ ((show |$> tys) >- (intersperse " " >-> fold))
-- quote
show (QUT t _) = "{"++ show t ++ "}"
show (QQUT t _) = "`"++ show t
show (UNQUT t _) = ","++ show t
-- syntactic-sugar
show (APP e [] _) = error "APP: empty args"
show (APP e args _) = "("++ show e ++" "++ (unwords $ args <$| show) ++")"
show (APPSeq [] _) = error "APPSeq: empty seq"
show (APPSeq (x:[]) _) = show x
show (APPSeq seq _) = "("++ (unwords $ seq <$| show) ++")"
show (LAM [] e _) = error "LAM: empty params"
show (LAM params e _) = "(\\"++ showParams ++"."++ show e ++")"
where
showParams = fold $ params <$| (\(pm, ty) -> show pm ++ showType ty)
>- intersperse " "
where
showType ty@(_ :-> _) = "::"++ "("++ show ty ++")"
showType Ty.UNIT = ""
showType ty = "::"++ show ty
show (LAMM [] e _) = error "LAMM: empty params"
show (LAMM params e _) = "("++ showParams ++ show e ++")"
where
showParams = fold $ params <$| (\(pm, ty) -> "#"++ show pm ++ showType ty ++ ".")
where
showType ty@(_ :-> _) = "::"++ "("++ show ty ++")"
showType Ty.UNIT = ""
showType ty = "::"++ show ty
show (AS (e, ty@(_ :-> _)) _) = show e ++"::("++ show ty ++")"
show (AS (e, ty) _) = show e ++"::"++ show ty
show (LET (pm,Ty.UNIT) e1 e2 _) = "let "++ show pm ++" = "++ show e1 ++" in "++ show e2
show (LET (pm,ty) e1 e2 _) = "let "++ show pm ++"::"++ show ty ++" = "++ show e1 ++" in "++ show e2
show (LETREC (var,ty) e1 e2 _) = "letrec "++ var ++"::"++ show ty ++" = "++ show e1 ++" in "++ show e2
-- list
show (NIL _) = "[]"
show x@(CONS a d _) =
if L.isList x
then case a of
CHAR _ _ -> show $ toString $ L.toList x
_ -> show $ L.toList x
else showParens a ++ ":"++ showParens d
where
toString [] = []
toString ((CHAR c _):cs) = c : toString cs
showParens x@(LAM _ _ _) = "("++ show x ++")"
showParens x@(FIX _ _) = "("++ show x ++")"
showParens x@(APP _ _ _) = "("++ show x ++")"
showParens x@(IF _ _ _ _) = "("++ show x ++")"
showParens x@(CASE _ _ _) = "("++ show x ++")"
showParens x = show x
show (HEAD x) = "(head " ++ show x ++")"
show (TAIL x) = "(tail " ++ show x ++")"
|
ocean0yohsuke/Simply-Typed-Lambda
|
src/Lambda/DataType/SExpr.hs
|
Haskell
|
bsd-3-clause
| 6,954
|
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
-- | Model for wiki.
module HL.Model.Wiki where
import HL.Controller
import Control.Exception.Lifted (catch)
import Control.Spoon
import Data.Conduit
import Data.Maybe
import Data.Monoid
import Data.Text (unpack)
import Network.HTTP.Conduit
import Prelude hiding (readFile)
import Text.Pandoc.Definition
import Text.Pandoc.Options
import Text.Pandoc.Readers.MediaWiki
import Text.XML
import Text.XML.Cursor
-- | Get the MediaWiki markup of a wiki page and then convert it to
-- HTML.
getWikiPage :: Text -> IO (Either Text (Text,Pandoc))
getWikiPage article =
do request <- parseUrl ("http://wiki.haskell.org/api.php?action=query&\
\prop=revisions&rvprop=content&format=xml&titles=" <>
unpack article)
withManager
(\manager ->
do response <- http request manager
doc <- catch (fmap Just (responseBody response $$+- sinkDoc def))
(\(_::UnresolvedEntityException) -> return Nothing)
case doc >>= parse of
Nothing -> return (Left "Unable to parse XML from wiki.haskell.org.")
Just (title,pan) ->
return
(fromMaybe (Left ("Unable to parse XML from wiki.haskell.org! \
\And the parser gave us an impure exception! \
\Can you believe it?"))
(showSpoon (Right (title,pan)))))
where
parse doc =
do let cursor = fromDocument doc
title <- listToMaybe (getTitle cursor)
text <- listToMaybe (getText cursor)
return (title,readMediaWiki def (unpack text))
name n =
Name {nameLocalName = n
,nameNamespace = Nothing
,namePrefix = Nothing}
getText cursor =
element (name "api") cursor >>=
descendant >>=
element (name "query") >>=
descendant >>=
element (name "pages") >>=
descendant >>=
element (name "page") >>=
descendant >>=
element (name "revisions") >>=
descendant >>=
element (name "rev") >>=
descendant >>=
content
getTitle cursor =
element (name "api") cursor >>=
descendant >>=
element (name "query") >>=
descendant >>=
element (name "pages") >>=
descendant >>=
element (name "page") >>=
attribute (name "title")
-- | Make a spoon using the Show instance.
showSpoon :: Show a => a -> Maybe a
showSpoon a =
(fmap (const a)
(spoon (length (show a))))
|
erantapaa/hl
|
src/HL/Model/Wiki.hs
|
Haskell
|
bsd-3-clause
| 2,701
|
{-# LANGUAGE CPP #-}
#include "overlapping-compat.h"
module Servant.ForeignSpec where
import Data.Monoid ((<>))
import Data.Proxy
import Servant.Foreign
import Test.Hspec
spec :: Spec
spec = describe "Servant.Foreign" $ do
camelCaseSpec
listFromAPISpec
camelCaseSpec :: Spec
camelCaseSpec = describe "camelCase" $ do
it "converts FunctionNames to camelCase" $ do
camelCase (FunctionName ["post", "counter", "inc"])
`shouldBe` "postCounterInc"
camelCase (FunctionName ["get", "hyphen-ated", "counter"])
`shouldBe` "getHyphenatedCounter"
----------------------------------------------------------------------
data LangX
instance HasForeignType LangX String NoContent where
typeFor _ _ _ = "voidX"
instance HasForeignType LangX String Int where
typeFor _ _ _ = "intX"
instance HasForeignType LangX String Bool where
typeFor _ _ _ = "boolX"
instance OVERLAPPING_ HasForeignType LangX String String where
typeFor _ _ _ = "stringX"
instance OVERLAPPABLE_ HasForeignType LangX String a => HasForeignType LangX String [a] where
typeFor lang ftype _ = "listX of " <> typeFor lang ftype (Proxy :: Proxy a)
type TestApi
= "test" :> Header "header" [String] :> QueryFlag "flag" :> Get '[JSON] Int
:<|> "test" :> QueryParam "param" Int :> ReqBody '[JSON] [String] :> Post '[JSON] NoContent
:<|> "test" :> QueryParams "params" Int :> ReqBody '[JSON] String :> Put '[JSON] NoContent
:<|> "test" :> Capture "id" Int :> Delete '[JSON] NoContent
:<|> "test" :> CaptureAll "ids" Int :> Get '[JSON] [Int]
testApi :: [Req String]
testApi = listFromAPI (Proxy :: Proxy LangX) (Proxy :: Proxy String) (Proxy :: Proxy TestApi)
listFromAPISpec :: Spec
listFromAPISpec = describe "listFromAPI" $ do
it "generates 4 endpoints for TestApi" $ do
length testApi `shouldBe` 5
let [getReq, postReq, putReq, deleteReq, captureAllReq] = testApi
it "collects all info for get request" $ do
shouldBe getReq $ defReq
{ _reqUrl = Url
[ Segment $ Static "test" ]
[ QueryArg (Arg "flag" "boolX") Flag ]
, _reqMethod = "GET"
, _reqHeaders = [HeaderArg $ Arg "header" "listX of stringX"]
, _reqBody = Nothing
, _reqReturnType = Just "intX"
, _reqFuncName = FunctionName ["get", "test"]
}
it "collects all info for post request" $ do
shouldBe postReq $ defReq
{ _reqUrl = Url
[ Segment $ Static "test" ]
[ QueryArg (Arg "param" "intX") Normal ]
, _reqMethod = "POST"
, _reqHeaders = []
, _reqBody = Just "listX of stringX"
, _reqReturnType = Just "voidX"
, _reqFuncName = FunctionName ["post", "test"]
}
it "collects all info for put request" $ do
shouldBe putReq $ defReq
{ _reqUrl = Url
[ Segment $ Static "test" ]
-- Shoud this be |intX| or |listX of intX| ?
[ QueryArg (Arg "params" "listX of intX") List ]
, _reqMethod = "PUT"
, _reqHeaders = []
, _reqBody = Just "stringX"
, _reqReturnType = Just "voidX"
, _reqFuncName = FunctionName ["put", "test"]
}
it "collects all info for delete request" $ do
shouldBe deleteReq $ defReq
{ _reqUrl = Url
[ Segment $ Static "test"
, Segment $ Cap (Arg "id" "intX") ]
[]
, _reqMethod = "DELETE"
, _reqHeaders = []
, _reqBody = Nothing
, _reqReturnType = Just "voidX"
, _reqFuncName = FunctionName ["delete", "test", "by", "id"]
}
it "collects all info for capture all request" $ do
shouldBe captureAllReq $ defReq
{ _reqUrl = Url
[ Segment $ Static "test"
, Segment $ Cap (Arg "ids" "listX of intX") ]
[]
, _reqMethod = "GET"
, _reqHeaders = []
, _reqBody = Nothing
, _reqReturnType = Just "listX of intX"
, _reqFuncName = FunctionName ["get", "test", "by", "ids"]
}
|
zerobuzz/servant
|
servant-foreign/test/Servant/ForeignSpec.hs
|
Haskell
|
bsd-3-clause
| 4,035
|
{-
(c) The University of Glasgow 2011
The deriving code for the Generic class
(equivalent to the code in TcGenDeriv, for other classes)
-}
{-# LANGUAGE CPP, ScopedTypeVariables, TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
module TcGenGenerics (canDoGenerics, canDoGenerics1,
GenericKind(..),
MetaTyCons, genGenericMetaTyCons,
gen_Generic_binds, get_gen1_constrained_tys) where
import DynFlags
import HsSyn
import Type
import Kind ( isKind )
import TcType
import TcGenDeriv
import DataCon
import TyCon
import FamInstEnv ( FamInst, FamFlavor(..), mkSingleCoAxiom )
import FamInst
import Module ( Module, moduleName, moduleNameString
, modulePackageKey, packageKeyString, getModule )
import IfaceEnv ( newGlobalBinder )
import Name hiding ( varName )
import RdrName
import BasicTypes
import TysWiredIn
import PrelNames
import InstEnv
import TcEnv
import MkId
import TcRnMonad
import HscTypes
import ErrUtils( Validity(..), andValid )
import BuildTyCl
import SrcLoc
import Bag
import VarSet (elemVarSet)
import Outputable
import FastString
import Util
import Control.Monad (mplus,forM)
#include "HsVersions.h"
{-
************************************************************************
* *
\subsection{Bindings for the new generic deriving mechanism}
* *
************************************************************************
For the generic representation we need to generate:
\begin{itemize}
\item A Generic instance
\item A Rep type instance
\item Many auxiliary datatypes and instances for them (for the meta-information)
\end{itemize}
-}
gen_Generic_binds :: GenericKind -> TyCon -> MetaTyCons -> Module
-> TcM (LHsBinds RdrName, FamInst)
gen_Generic_binds gk tc metaTyCons mod = do
repTyInsts <- tc_mkRepFamInsts gk tc metaTyCons mod
return (mkBindsRep gk tc, repTyInsts)
genGenericMetaTyCons :: TyCon -> TcM (MetaTyCons, BagDerivStuff)
genGenericMetaTyCons tc =
do let
tc_name = tyConName tc
mod = nameModule tc_name
tc_cons = tyConDataCons tc
tc_arits = map dataConSourceArity tc_cons
tc_occ = nameOccName tc_name
d_occ = mkGenD mod tc_occ
c_occ m = mkGenC mod tc_occ m
s_occ m n = mkGenS mod tc_occ m n
mkTyCon name = ASSERT( isExternalName name )
buildAlgTyCon name [] [] Nothing [] distinctAbstractTyConRhs
NonRecursive
False -- Not promotable
False -- Not GADT syntax
NoParentTyCon
loc <- getSrcSpanM
-- we generate new names in current module
currentMod <- getModule
d_name <- newGlobalBinder currentMod d_occ loc
c_names <- forM (zip [0..] tc_cons) $ \(m,_) ->
newGlobalBinder currentMod (c_occ m) loc
s_names <- forM (zip [0..] tc_arits) $ \(m,a) -> forM [0..a-1] $ \n ->
newGlobalBinder currentMod (s_occ m n) loc
let metaDTyCon = mkTyCon d_name
metaCTyCons = map mkTyCon c_names
metaSTyCons = map (map mkTyCon) s_names
metaDts = MetaTyCons metaDTyCon metaCTyCons metaSTyCons
(,) metaDts `fmap` metaTyConsToDerivStuff tc metaDts
-- both the tycon declarations and related instances
metaTyConsToDerivStuff :: TyCon -> MetaTyCons -> TcM BagDerivStuff
metaTyConsToDerivStuff tc metaDts =
do dflags <- getDynFlags
dClas <- tcLookupClass datatypeClassName
d_dfun_name <- newDFunName' dClas tc
cClas <- tcLookupClass constructorClassName
c_dfun_names <- sequence [ (conTy,) <$> newDFunName' cClas tc
| conTy <- metaC metaDts ]
sClas <- tcLookupClass selectorClassName
s_dfun_names <-
sequence (map sequence [ [ (selector,) <$> newDFunName' sClas tc
| selector <- selectors ]
| selectors <- metaS metaDts ])
fix_env <- getFixityEnv
let
(dBinds,cBinds,sBinds) = mkBindsMetaD fix_env tc
mk_inst clas tc dfun_name
= mkLocalInstance (mkDictFunId dfun_name [] [] clas tys)
OverlapFlag { overlapMode = (NoOverlap "")
, isSafeOverlap = safeLanguageOn dflags }
[] clas tys
where
tys = [mkTyConTy tc]
-- Datatype
d_metaTycon = metaD metaDts
d_inst = mk_inst dClas d_metaTycon d_dfun_name
d_binds = InstBindings { ib_binds = dBinds
, ib_tyvars = []
, ib_pragmas = []
, ib_extensions = []
, ib_derived = True }
d_mkInst = DerivInst (InstInfo { iSpec = d_inst, iBinds = d_binds })
-- Constructor
c_insts = [ mk_inst cClas c ds | (c, ds) <- c_dfun_names ]
c_binds = [ InstBindings { ib_binds = c
, ib_tyvars = []
, ib_pragmas = []
, ib_extensions = []
, ib_derived = True }
| c <- cBinds ]
c_mkInst = [ DerivInst (InstInfo { iSpec = is, iBinds = bs })
| (is,bs) <- myZip1 c_insts c_binds ]
-- Selector
s_insts = map (map (\(s,ds) -> mk_inst sClas s ds)) s_dfun_names
s_binds = [ [ InstBindings { ib_binds = s
, ib_tyvars = []
, ib_pragmas = []
, ib_extensions = []
, ib_derived = True }
| s <- ss ] | ss <- sBinds ]
s_mkInst = map (map (\(is,bs) -> DerivInst (InstInfo { iSpec = is
, iBinds = bs})))
(myZip2 s_insts s_binds)
myZip1 :: [a] -> [b] -> [(a,b)]
myZip1 l1 l2 = ASSERT(length l1 == length l2) zip l1 l2
myZip2 :: [[a]] -> [[b]] -> [[(a,b)]]
myZip2 l1 l2 =
ASSERT(and (zipWith (>=) (map length l1) (map length l2)))
[ zip x1 x2 | (x1,x2) <- zip l1 l2 ]
return $ mapBag DerivTyCon (metaTyCons2TyCons metaDts)
`unionBags` listToBag (d_mkInst : c_mkInst ++ concat s_mkInst)
{-
************************************************************************
* *
\subsection{Generating representation types}
* *
************************************************************************
-}
get_gen1_constrained_tys :: TyVar -> Type -> [Type]
-- called by TcDeriv.inferConstraints; generates a list of types, each of which
-- must be a Functor in order for the Generic1 instance to work.
get_gen1_constrained_tys argVar
= argTyFold argVar $ ArgTyAlg { ata_rec0 = const []
, ata_par1 = [], ata_rec1 = const []
, ata_comp = (:) }
{-
Note [Requirements for deriving Generic and Rep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the following, T, Tfun, and Targ are "meta-variables" ranging over type
expressions.
(Generic T) and (Rep T) are derivable for some type expression T if the
following constraints are satisfied.
(a) T = (D v1 ... vn) with free variables v1, v2, ..., vn where n >= 0 v1
... vn are distinct type variables. Cf #5939.
(b) D is a type constructor *value*. In other words, D is either a type
constructor or it is equivalent to the head of a data family instance (up to
alpha-renaming).
(c) D cannot have a "stupid context".
(d) The right-hand side of D cannot include unboxed types, existential types,
or universally quantified types.
(e) T :: *.
(Generic1 T) and (Rep1 T) are derivable for some type expression T if the
following constraints are satisfied.
(a),(b),(c),(d) As above.
(f) T must expect arguments, and its last parameter must have kind *.
We use `a' to denote the parameter of D that corresponds to the last
parameter of T.
(g) For any type-level application (Tfun Targ) in the right-hand side of D
where the head of Tfun is not a tuple constructor:
(b1) `a' must not occur in Tfun.
(b2) If `a' occurs in Targ, then Tfun :: * -> *.
-}
canDoGenerics :: TyCon -> [Type] -> Validity
-- canDoGenerics rep_tc tc_args determines if Generic/Rep can be derived for a
-- type expression (rep_tc tc_arg0 tc_arg1 ... tc_argn).
--
-- Check (b) from Note [Requirements for deriving Generic and Rep] is taken
-- care of because canDoGenerics is applied to rep tycons.
--
-- It returns Nothing if deriving is possible. It returns (Just reason) if not.
canDoGenerics tc tc_args
= mergeErrors (
-- Check (c) from Note [Requirements for deriving Generic and Rep].
(if (not (null (tyConStupidTheta tc)))
then (NotValid (tc_name <+> text "must not have a datatype context"))
else IsValid) :
-- Check (a) from Note [Requirements for deriving Generic and Rep].
--
-- Data family indices can be instantiated; the `tc_args` here are
-- the representation tycon args
(if (all isTyVarTy (filterOut isKind tc_args))
then IsValid
else NotValid (tc_name <+> text "must not be instantiated;" <+>
text "try deriving `" <> tc_name <+> tc_tys <>
text "' instead"))
-- See comment below
: (map bad_con (tyConDataCons tc)))
where
-- The tc can be a representation tycon. When we want to display it to the
-- user (in an error message) we should print its parent
(tc_name, tc_tys) = case tyConParent tc of
FamInstTyCon _ ptc tys -> (ppr ptc, hsep (map ppr
(tys ++ drop (length tys) tc_args)))
_ -> (ppr tc, hsep (map ppr (tyConTyVars tc)))
-- Check (d) from Note [Requirements for deriving Generic and Rep].
--
-- If any of the constructors has an unboxed type as argument,
-- then we can't build the embedding-projection pair, because
-- it relies on instantiating *polymorphic* sum and product types
-- at the argument types of the constructors
bad_con dc = if (any bad_arg_type (dataConOrigArgTys dc))
then (NotValid (ppr dc <+> text "must not have unlifted or polymorphic arguments"))
else (if (not (isVanillaDataCon dc))
then (NotValid (ppr dc <+> text "must be a vanilla data constructor"))
else IsValid)
-- Nor can we do the job if it's an existential data constructor,
-- Nor if the args are polymorphic types (I don't think)
bad_arg_type ty = isUnLiftedType ty || not (isTauTy ty)
mergeErrors :: [Validity] -> Validity
mergeErrors [] = IsValid
mergeErrors (NotValid s:t) = case mergeErrors t of
IsValid -> NotValid s
NotValid s' -> NotValid (s <> text ", and" $$ s')
mergeErrors (IsValid : t) = mergeErrors t
-- A datatype used only inside of canDoGenerics1. It's the result of analysing
-- a type term.
data Check_for_CanDoGenerics1 = CCDG1
{ _ccdg1_hasParam :: Bool -- does the parameter of interest occurs in
-- this type?
, _ccdg1_errors :: Validity -- errors generated by this type
}
{-
Note [degenerate use of FFoldType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We use foldDataConArgs here only for its ability to treat tuples
specially. foldDataConArgs also tracks covariance (though it assumes all
higher-order type parameters are covariant) and has hooks for special handling
of functions and polytypes, but we do *not* use those.
The key issue is that Generic1 deriving currently offers no sophisticated
support for functions. For example, we cannot handle
data F a = F ((a -> Int) -> Int)
even though a is occurring covariantly.
In fact, our rule is harsh: a is simply not allowed to occur within the first
argument of (->). We treat (->) the same as any other non-tuple tycon.
Unfortunately, this means we have to track "the parameter occurs in this type"
explicitly, even though foldDataConArgs is also doing this internally.
-}
-- canDoGenerics1 rep_tc tc_args determines if a Generic1/Rep1 can be derived
-- for a type expression (rep_tc tc_arg0 tc_arg1 ... tc_argn).
--
-- Checks (a) through (d) from Note [Requirements for deriving Generic and Rep]
-- are taken care of by the call to canDoGenerics.
--
-- It returns Nothing if deriving is possible. It returns (Just reason) if not.
canDoGenerics1 :: TyCon -> [Type] -> Validity
canDoGenerics1 rep_tc tc_args =
canDoGenerics rep_tc tc_args `andValid` additionalChecks
where
additionalChecks
-- check (f) from Note [Requirements for deriving Generic and Rep]
| null (tyConTyVars rep_tc) = NotValid $
ptext (sLit "Data type") <+> quotes (ppr rep_tc)
<+> ptext (sLit "must have some type parameters")
| otherwise = mergeErrors $ concatMap check_con data_cons
data_cons = tyConDataCons rep_tc
check_con con = case check_vanilla con of
j@(NotValid {}) -> [j]
IsValid -> _ccdg1_errors `map` foldDataConArgs (ft_check con) con
bad :: DataCon -> SDoc -> SDoc
bad con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
check_vanilla :: DataCon -> Validity
check_vanilla con | isVanillaDataCon con = IsValid
| otherwise = NotValid (bad con existential)
bmzero = CCDG1 False IsValid
bmbad con s = CCDG1 True $ NotValid $ bad con s
bmplus (CCDG1 b1 m1) (CCDG1 b2 m2) = CCDG1 (b1 || b2) (m1 `andValid` m2)
-- check (g) from Note [degenerate use of FFoldType]
ft_check :: DataCon -> FFoldType Check_for_CanDoGenerics1
ft_check con = FT
{ ft_triv = bmzero
, ft_var = caseVar, ft_co_var = caseVar
-- (component_0,component_1,...,component_n)
, ft_tup = \_ components -> if any _ccdg1_hasParam (init components)
then bmbad con wrong_arg
else foldr bmplus bmzero components
-- (dom -> rng), where the head of ty is not a tuple tycon
, ft_fun = \dom rng -> -- cf #8516
if _ccdg1_hasParam dom
then bmbad con wrong_arg
else bmplus dom rng
-- (ty arg), where head of ty is neither (->) nor a tuple constructor and
-- the parameter of interest does not occur in ty
, ft_ty_app = \_ arg -> arg
, ft_bad_app = bmbad con wrong_arg
, ft_forall = \_ body -> body -- polytypes are handled elsewhere
}
where
caseVar = CCDG1 True IsValid
existential = text "must not have existential arguments"
wrong_arg = text "applies a type to an argument involving the last parameter"
$$ text "but the applied type is not of kind * -> *"
{-
************************************************************************
* *
\subsection{Generating the RHS of a generic default method}
* *
************************************************************************
-}
type US = Int -- Local unique supply, just a plain Int
type Alt = (LPat RdrName, LHsExpr RdrName)
-- GenericKind serves to mark if a datatype derives Generic (Gen0) or
-- Generic1 (Gen1).
data GenericKind = Gen0 | Gen1
-- as above, but with a payload of the TyCon's name for "the" parameter
data GenericKind_ = Gen0_ | Gen1_ TyVar
-- as above, but using a single datacon's name for "the" parameter
data GenericKind_DC = Gen0_DC | Gen1_DC TyVar
forgetArgVar :: GenericKind_DC -> GenericKind
forgetArgVar Gen0_DC = Gen0
forgetArgVar Gen1_DC{} = Gen1
-- When working only within a single datacon, "the" parameter's name should
-- match that datacon's name for it.
gk2gkDC :: GenericKind_ -> DataCon -> GenericKind_DC
gk2gkDC Gen0_ _ = Gen0_DC
gk2gkDC Gen1_{} d = Gen1_DC $ last $ dataConUnivTyVars d
-- Bindings for the Generic instance
mkBindsRep :: GenericKind -> TyCon -> LHsBinds RdrName
mkBindsRep gk tycon =
unitBag (mkRdrFunBind (L loc from01_RDR) from_matches)
`unionBags`
unitBag (mkRdrFunBind (L loc to01_RDR) to_matches)
where
from_matches = [mkSimpleHsAlt pat rhs | (pat,rhs) <- from_alts]
to_matches = [mkSimpleHsAlt pat rhs | (pat,rhs) <- to_alts ]
loc = srcLocSpan (getSrcLoc tycon)
datacons = tyConDataCons tycon
(from01_RDR, to01_RDR) = case gk of
Gen0 -> (from_RDR, to_RDR)
Gen1 -> (from1_RDR, to1_RDR)
-- Recurse over the sum first
from_alts, to_alts :: [Alt]
(from_alts, to_alts) = mkSum gk_ (1 :: US) tycon datacons
where gk_ = case gk of
Gen0 -> Gen0_
Gen1 -> ASSERT(length tyvars >= 1)
Gen1_ (last tyvars)
where tyvars = tyConTyVars tycon
--------------------------------------------------------------------------------
-- The type synonym instance and synonym
-- type instance Rep (D a b) = Rep_D a b
-- type Rep_D a b = ...representation type for D ...
--------------------------------------------------------------------------------
tc_mkRepFamInsts :: GenericKind -- Gen0 or Gen1
-> TyCon -- The type to generate representation for
-> MetaTyCons -- Metadata datatypes to refer to
-> Module -- Used as the location of the new RepTy
-> TcM (FamInst) -- Generated representation0 coercion
tc_mkRepFamInsts gk tycon metaDts mod =
-- Consider the example input tycon `D`, where data D a b = D_ a
-- Also consider `R:DInt`, where { data family D x y :: * -> *
-- ; data instance D Int a b = D_ a }
do { -- `rep` = GHC.Generics.Rep or GHC.Generics.Rep1 (type family)
fam_tc <- case gk of
Gen0 -> tcLookupTyCon repTyConName
Gen1 -> tcLookupTyCon rep1TyConName
; let -- `tyvars` = [a,b]
(tyvars, gk_) = case gk of
Gen0 -> (all_tyvars, Gen0_)
Gen1 -> ASSERT(not $ null all_tyvars)
(init all_tyvars, Gen1_ $ last all_tyvars)
where all_tyvars = tyConTyVars tycon
tyvar_args = mkTyVarTys tyvars
appT :: [Type]
appT = case tyConFamInst_maybe tycon of
-- `appT` = D Int a b (data families case)
Just (famtycon, apps) ->
-- `fam` = D
-- `apps` = [Int, a, b]
let allApps = case gk of
Gen0 -> apps
Gen1 -> ASSERT(not $ null apps)
init apps
in [mkTyConApp famtycon allApps]
-- `appT` = D a b (normal case)
Nothing -> [mkTyConApp tycon tyvar_args]
-- `repTy` = D1 ... (C1 ... (S1 ... (Rec0 a))) :: * -> *
; repTy <- tc_mkRepTy gk_ tycon metaDts
-- `rep_name` is a name we generate for the synonym
; rep_name <- let mkGen = case gk of Gen0 -> mkGenR; Gen1 -> mkGen1R
in newGlobalBinder mod (mkGen (nameOccName (tyConName tycon)))
(nameSrcSpan (tyConName tycon))
; let axiom = mkSingleCoAxiom Nominal rep_name tyvars fam_tc appT repTy
; newFamInst SynFamilyInst axiom }
--------------------------------------------------------------------------------
-- Type representation
--------------------------------------------------------------------------------
-- | See documentation of 'argTyFold'; that function uses the fields of this
-- type to interpret the structure of a type when that type is considered as an
-- argument to a constructor that is being represented with 'Rep1'.
data ArgTyAlg a = ArgTyAlg
{ ata_rec0 :: (Type -> a)
, ata_par1 :: a, ata_rec1 :: (Type -> a)
, ata_comp :: (Type -> a -> a)
}
-- | @argTyFold@ implements a generalised and safer variant of the @arg@
-- function from Figure 3 in <http://dreixel.net/research/pdf/gdmh.pdf>. @arg@
-- is conceptually equivalent to:
--
-- > arg t = case t of
-- > _ | isTyVar t -> if (t == argVar) then Par1 else Par0 t
-- > App f [t'] |
-- > representable1 f &&
-- > t' == argVar -> Rec1 f
-- > App f [t'] |
-- > representable1 f &&
-- > t' has tyvars -> f :.: (arg t')
-- > _ -> Rec0 t
--
-- where @argVar@ is the last type variable in the data type declaration we are
-- finding the representation for.
--
-- @argTyFold@ is more general than @arg@ because it uses 'ArgTyAlg' to
-- abstract out the concrete invocations of @Par0@, @Rec0@, @Par1@, @Rec1@, and
-- @:.:@.
--
-- @argTyFold@ is safer than @arg@ because @arg@ would lead to a GHC panic for
-- some data types. The problematic case is when @t@ is an application of a
-- non-representable type @f@ to @argVar@: @App f [argVar]@ is caught by the
-- @_@ pattern, and ends up represented as @Rec0 t@. This type occurs /free/ in
-- the RHS of the eventual @Rep1@ instance, which is therefore ill-formed. Some
-- representable1 checks have been relaxed, and others were moved to
-- @canDoGenerics1@.
argTyFold :: forall a. TyVar -> ArgTyAlg a -> Type -> a
argTyFold argVar (ArgTyAlg {ata_rec0 = mkRec0,
ata_par1 = mkPar1, ata_rec1 = mkRec1,
ata_comp = mkComp}) =
-- mkRec0 is the default; use it if there is no interesting structure
-- (e.g. occurrences of parameters or recursive occurrences)
\t -> maybe (mkRec0 t) id $ go t where
go :: Type -> -- type to fold through
Maybe a -- the result (e.g. representation type), unless it's trivial
go t = isParam `mplus` isApp where
isParam = do -- handles parameters
t' <- getTyVar_maybe t
Just $ if t' == argVar then mkPar1 -- moreover, it is "the" parameter
else mkRec0 t -- NB mkRec0 instead of the conventional mkPar0
isApp = do -- handles applications
(phi, beta) <- tcSplitAppTy_maybe t
let interesting = argVar `elemVarSet` exactTyVarsOfType beta
-- Does it have no interesting structure to represent?
if not interesting then Nothing
else -- Is the argument the parameter? Special case for mkRec1.
if Just argVar == getTyVar_maybe beta then Just $ mkRec1 phi
else mkComp phi `fmap` go beta -- It must be a composition.
tc_mkRepTy :: -- Gen0_ or Gen1_, for Rep or Rep1
GenericKind_
-- The type to generate representation for
-> TyCon
-- Metadata datatypes to refer to
-> MetaTyCons
-- Generated representation0 type
-> TcM Type
tc_mkRepTy gk_ tycon metaDts =
do
d1 <- tcLookupTyCon d1TyConName
c1 <- tcLookupTyCon c1TyConName
s1 <- tcLookupTyCon s1TyConName
nS1 <- tcLookupTyCon noSelTyConName
rec0 <- tcLookupTyCon rec0TyConName
rec1 <- tcLookupTyCon rec1TyConName
par1 <- tcLookupTyCon par1TyConName
u1 <- tcLookupTyCon u1TyConName
v1 <- tcLookupTyCon v1TyConName
plus <- tcLookupTyCon sumTyConName
times <- tcLookupTyCon prodTyConName
comp <- tcLookupTyCon compTyConName
let mkSum' a b = mkTyConApp plus [a,b]
mkProd a b = mkTyConApp times [a,b]
mkComp a b = mkTyConApp comp [a,b]
mkRec0 a = mkTyConApp rec0 [a]
mkRec1 a = mkTyConApp rec1 [a]
mkPar1 = mkTyConTy par1
mkD a = mkTyConApp d1 [metaDTyCon, sumP (tyConDataCons a)]
mkC i d a = mkTyConApp c1 [d, prod i (dataConInstOrigArgTys a $ mkTyVarTys $ tyConTyVars tycon)
(null (dataConFieldLabels a))]
-- This field has no label
mkS True _ a = mkTyConApp s1 [mkTyConTy nS1, a]
-- This field has a label
mkS False d a = mkTyConApp s1 [d, a]
-- Sums and products are done in the same way for both Rep and Rep1
sumP [] = mkTyConTy v1
sumP l = ASSERT(length metaCTyCons == length l)
foldBal mkSum' [ mkC i d a
| (d,(a,i)) <- zip metaCTyCons (zip l [0..])]
-- The Bool is True if this constructor has labelled fields
prod :: Int -> [Type] -> Bool -> Type
prod i [] _ = ASSERT(length metaSTyCons > i)
ASSERT(length (metaSTyCons !! i) == 0)
mkTyConTy u1
prod i l b = ASSERT(length metaSTyCons > i)
ASSERT(length l == length (metaSTyCons !! i))
foldBal mkProd [ arg d t b
| (d,t) <- zip (metaSTyCons !! i) l ]
arg :: Type -> Type -> Bool -> Type
arg d t b = mkS b d $ case gk_ of
-- Here we previously used Par0 if t was a type variable, but we
-- realized that we can't always guarantee that we are wrapping-up
-- all type variables in Par0. So we decided to stop using Par0
-- altogether, and use Rec0 all the time.
Gen0_ -> mkRec0 t
Gen1_ argVar -> argPar argVar t
where
-- Builds argument represention for Rep1 (more complicated due to
-- the presence of composition).
argPar argVar = argTyFold argVar $ ArgTyAlg
{ata_rec0 = mkRec0, ata_par1 = mkPar1,
ata_rec1 = mkRec1, ata_comp = mkComp}
metaDTyCon = mkTyConTy (metaD metaDts)
metaCTyCons = map mkTyConTy (metaC metaDts)
metaSTyCons = map (map mkTyConTy) (metaS metaDts)
return (mkD tycon)
--------------------------------------------------------------------------------
-- Meta-information
--------------------------------------------------------------------------------
data MetaTyCons = MetaTyCons { -- One meta datatype per datatype
metaD :: TyCon
-- One meta datatype per constructor
, metaC :: [TyCon]
-- One meta datatype per selector per constructor
, metaS :: [[TyCon]] }
instance Outputable MetaTyCons where
ppr (MetaTyCons d c s) = ppr d $$ vcat (map ppr c) $$ vcat (map ppr (concat s))
metaTyCons2TyCons :: MetaTyCons -> Bag TyCon
metaTyCons2TyCons (MetaTyCons d c s) = listToBag (d : c ++ concat s)
-- Bindings for Datatype, Constructor, and Selector instances
mkBindsMetaD :: FixityEnv -> TyCon
-> ( LHsBinds RdrName -- Datatype instance
, [LHsBinds RdrName] -- Constructor instances
, [[LHsBinds RdrName]]) -- Selector instances
mkBindsMetaD fix_env tycon = (dtBinds, allConBinds, allSelBinds)
where
mkBag l = foldr1 unionBags
[ unitBag (mkRdrFunBind (L loc name) matches)
| (name, matches) <- l ]
dtBinds = mkBag ( [ (datatypeName_RDR, dtName_matches)
, (moduleName_RDR, moduleName_matches)
, (packageName_RDR, pkgName_matches)]
++ ifElseEmpty (isNewTyCon tycon)
[ (isNewtypeName_RDR, isNewtype_matches) ] )
allConBinds = map conBinds datacons
conBinds c = mkBag ( [ (conName_RDR, conName_matches c)]
++ ifElseEmpty (dataConIsInfix c)
[ (conFixity_RDR, conFixity_matches c) ]
++ ifElseEmpty (length (dataConFieldLabels c) > 0)
[ (conIsRecord_RDR, conIsRecord_matches c) ]
)
ifElseEmpty p x = if p then x else []
fixity c = case lookupFixity fix_env (dataConName c) of
Fixity n InfixL -> buildFix n leftAssocDataCon_RDR
Fixity n InfixR -> buildFix n rightAssocDataCon_RDR
Fixity n InfixN -> buildFix n notAssocDataCon_RDR
buildFix n assoc = nlHsApps infixDataCon_RDR [nlHsVar assoc
, nlHsIntLit (toInteger n)]
allSelBinds = map (map selBinds) datasels
selBinds s = mkBag [(selName_RDR, selName_matches s)]
loc = srcLocSpan (getSrcLoc tycon)
mkStringLHS s = [mkSimpleHsAlt nlWildPat (nlHsLit (mkHsString s))]
datacons = tyConDataCons tycon
datasels = map dataConFieldLabels datacons
tyConName_user = case tyConFamInst_maybe tycon of
Just (ptycon, _) -> tyConName ptycon
Nothing -> tyConName tycon
dtName_matches = mkStringLHS . occNameString . nameOccName
$ tyConName_user
moduleName_matches = mkStringLHS . moduleNameString . moduleName
. nameModule . tyConName $ tycon
pkgName_matches = mkStringLHS . packageKeyString . modulePackageKey
. nameModule . tyConName $ tycon
isNewtype_matches = [mkSimpleHsAlt nlWildPat (nlHsVar true_RDR)]
conName_matches c = mkStringLHS . occNameString . nameOccName
. dataConName $ c
conFixity_matches c = [mkSimpleHsAlt nlWildPat (fixity c)]
conIsRecord_matches _ = [mkSimpleHsAlt nlWildPat (nlHsVar true_RDR)]
selName_matches s = mkStringLHS (occNameString (nameOccName s))
--------------------------------------------------------------------------------
-- Dealing with sums
--------------------------------------------------------------------------------
mkSum :: GenericKind_ -- Generic or Generic1?
-> US -- Base for generating unique names
-> TyCon -- The type constructor
-> [DataCon] -- The data constructors
-> ([Alt], -- Alternatives for the T->Trep "from" function
[Alt]) -- Alternatives for the Trep->T "to" function
-- Datatype without any constructors
mkSum _ _ tycon [] = ([from_alt], [to_alt])
where
from_alt = (nlWildPat, mkM1_E (makeError errMsgFrom))
to_alt = (mkM1_P nlWildPat, makeError errMsgTo)
-- These M1s are meta-information for the datatype
makeError s = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString s))
tyConStr = occNameString (nameOccName (tyConName tycon))
errMsgFrom = "No generic representation for empty datatype " ++ tyConStr
errMsgTo = "No values for empty datatype " ++ tyConStr
-- Datatype with at least one constructor
mkSum gk_ us _ datacons =
-- switch the payload of gk_ to be datacon-centric instead of tycon-centric
unzip [ mk1Sum (gk2gkDC gk_ d) us i (length datacons) d
| (d,i) <- zip datacons [1..] ]
-- Build the sum for a particular constructor
mk1Sum :: GenericKind_DC -- Generic or Generic1?
-> US -- Base for generating unique names
-> Int -- The index of this constructor
-> Int -- Total number of constructors
-> DataCon -- The data constructor
-> (Alt, -- Alternative for the T->Trep "from" function
Alt) -- Alternative for the Trep->T "to" function
mk1Sum gk_ us i n datacon = (from_alt, to_alt)
where
gk = forgetArgVar gk_
-- Existentials already excluded
argTys = dataConOrigArgTys datacon
n_args = dataConSourceArity datacon
datacon_varTys = zip (map mkGenericLocal [us .. us+n_args-1]) argTys
datacon_vars = map fst datacon_varTys
us' = us + n_args
datacon_rdr = getRdrName datacon
from_alt = (nlConVarPat datacon_rdr datacon_vars, from_alt_rhs)
from_alt_rhs = mkM1_E (genLR_E i n (mkProd_E gk_ us' datacon_varTys))
to_alt = (mkM1_P (genLR_P i n (mkProd_P gk us' datacon_vars)), to_alt_rhs)
-- These M1s are meta-information for the datatype
to_alt_rhs = case gk_ of
Gen0_DC -> nlHsVarApps datacon_rdr datacon_vars
Gen1_DC argVar -> nlHsApps datacon_rdr $ map argTo datacon_varTys
where
argTo (var, ty) = converter ty `nlHsApp` nlHsVar var where
converter = argTyFold argVar $ ArgTyAlg
{ata_rec0 = const $ nlHsVar unK1_RDR,
ata_par1 = nlHsVar unPar1_RDR,
ata_rec1 = const $ nlHsVar unRec1_RDR,
ata_comp = \_ cnv -> (nlHsVar fmap_RDR `nlHsApp` cnv)
`nlHsCompose` nlHsVar unComp1_RDR}
-- Generates the L1/R1 sum pattern
genLR_P :: Int -> Int -> LPat RdrName -> LPat RdrName
genLR_P i n p
| n == 0 = error "impossible"
| n == 1 = p
| i <= div n 2 = nlConPat l1DataCon_RDR [genLR_P i (div n 2) p]
| otherwise = nlConPat r1DataCon_RDR [genLR_P (i-m) (n-m) p]
where m = div n 2
-- Generates the L1/R1 sum expression
genLR_E :: Int -> Int -> LHsExpr RdrName -> LHsExpr RdrName
genLR_E i n e
| n == 0 = error "impossible"
| n == 1 = e
| i <= div n 2 = nlHsVar l1DataCon_RDR `nlHsApp` genLR_E i (div n 2) e
| otherwise = nlHsVar r1DataCon_RDR `nlHsApp` genLR_E (i-m) (n-m) e
where m = div n 2
--------------------------------------------------------------------------------
-- Dealing with products
--------------------------------------------------------------------------------
-- Build a product expression
mkProd_E :: GenericKind_DC -- Generic or Generic1?
-> US -- Base for unique names
-> [(RdrName, Type)] -- List of variables matched on the lhs and their types
-> LHsExpr RdrName -- Resulting product expression
mkProd_E _ _ [] = mkM1_E (nlHsVar u1DataCon_RDR)
mkProd_E gk_ _ varTys = mkM1_E (foldBal prod appVars)
-- These M1s are meta-information for the constructor
where
appVars = map (wrapArg_E gk_) varTys
prod a b = prodDataCon_RDR `nlHsApps` [a,b]
wrapArg_E :: GenericKind_DC -> (RdrName, Type) -> LHsExpr RdrName
wrapArg_E Gen0_DC (var, _) = mkM1_E (k1DataCon_RDR `nlHsVarApps` [var])
-- This M1 is meta-information for the selector
wrapArg_E (Gen1_DC argVar) (var, ty) = mkM1_E $ converter ty `nlHsApp` nlHsVar var
-- This M1 is meta-information for the selector
where converter = argTyFold argVar $ ArgTyAlg
{ata_rec0 = const $ nlHsVar k1DataCon_RDR,
ata_par1 = nlHsVar par1DataCon_RDR,
ata_rec1 = const $ nlHsVar rec1DataCon_RDR,
ata_comp = \_ cnv -> nlHsVar comp1DataCon_RDR `nlHsCompose`
(nlHsVar fmap_RDR `nlHsApp` cnv)}
-- Build a product pattern
mkProd_P :: GenericKind -- Gen0 or Gen1
-> US -- Base for unique names
-> [RdrName] -- List of variables to match
-> LPat RdrName -- Resulting product pattern
mkProd_P _ _ [] = mkM1_P (nlNullaryConPat u1DataCon_RDR)
mkProd_P gk _ vars = mkM1_P (foldBal prod appVars)
-- These M1s are meta-information for the constructor
where
appVars = map (wrapArg_P gk) vars
prod a b = prodDataCon_RDR `nlConPat` [a,b]
wrapArg_P :: GenericKind -> RdrName -> LPat RdrName
wrapArg_P Gen0 v = mkM1_P (k1DataCon_RDR `nlConVarPat` [v])
-- This M1 is meta-information for the selector
wrapArg_P Gen1 v = m1DataCon_RDR `nlConVarPat` [v]
mkGenericLocal :: US -> RdrName
mkGenericLocal u = mkVarUnqual (mkFastString ("g" ++ show u))
mkM1_E :: LHsExpr RdrName -> LHsExpr RdrName
mkM1_E e = nlHsVar m1DataCon_RDR `nlHsApp` e
mkM1_P :: LPat RdrName -> LPat RdrName
mkM1_P p = m1DataCon_RDR `nlConPat` [p]
nlHsCompose :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName
nlHsCompose x y = compose_RDR `nlHsApps` [x, y]
-- | Variant of foldr1 for producing balanced lists
foldBal :: (a -> a -> a) -> [a] -> a
foldBal op = foldBal' op (error "foldBal: empty list")
foldBal' :: (a -> a -> a) -> a -> [a] -> a
foldBal' _ x [] = x
foldBal' _ _ [y] = y
foldBal' op x l = let (a,b) = splitAt (length l `div` 2) l
in foldBal' op x a `op` foldBal' op x b
|
ghc-android/ghc
|
compiler/typecheck/TcGenGenerics.hs
|
Haskell
|
bsd-3-clause
| 37,323
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Email.EN.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.Email.Types
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (EmailData "alice@exAmple.io")
[ "alice at exAmple.io"
]
, examples (EmailData "yo+yo@blah.org")
[ "yo+yo at blah.org"
]
, examples (EmailData "1234+abc@x.net")
[ "1234+abc at x.net"
]
, examples (EmailData "jean-jacques@stuff.co.uk")
[ "jean-jacques at stuff.co.uk"
]
]
|
rfranek/duckling
|
Duckling/Email/EN/Corpus.hs
|
Haskell
|
bsd-3-clause
| 983
|
module SimpleLang.Syntax where
import Data.Functor.Identity
import Data.Maybe (fromMaybe)
import qualified SimpleLang.Parser as P
import Text.Parsec
import qualified Text.Parsec.Expr as Ex
import qualified Text.Parsec.Token as Tok
data Expr =
Tr
| Fl
| Zero
| IsZero Expr
| Succ Expr
| Pred Expr
| If Expr Expr Expr
deriving (Eq, Show)
-----------------
-- Parsing --
-----------------
prefixOp :: String -> (a -> a) -> Ex.Operator String () Identity a
prefixOp s f = Ex.Prefix (P.reservedOp s >> return f)
-- table of operations for our language
table :: Ex.OperatorTable String () Identity Expr
table = [
[
prefixOp "succ" Succ
, prefixOp "pred" Pred
, prefixOp "iszero" IsZero
]
]
-- Constants :
true, false, zero :: P.Parser Expr
true = P.reserved "true" >> return Tr
false = P.reserved "false" >> return Fl
zero = P.reserved "0" >> return Zero
ifthen :: P.Parser Expr
ifthen = do
P.reserved "if"
cond <- expr
P.reservedOp "then"
tr <- expr
P.reserved "else"
fl <- expr
return (If cond tr fl)
factor :: P.Parser Expr
factor =
true
<|> false
<|> zero
<|> ifthen
<|> P.parens expr
expr :: P.Parser Expr
expr = Ex.buildExpressionParser table factor
contents :: P.Parser a -> P.Parser a
contents p = do
Tok.whiteSpace P.lexer
r <- p
eof
return r
-- The toplevel function we'll expose from our Parse module is parseExpr
-- which will be called as the entry point in our REPL.
parseExpr :: String -> Either ParseError Expr
parseExpr = parse (contents expr) "<stdin>"
-----------------
-- Evaluation --
-----------------
isNum :: Expr -> Bool
isNum Zero = True
isNum (Succ t) = isNum t
isNum _ = False
isVal :: Expr -> Bool
isVal Tr = True
isVal Fl = True
isVal t | isNum t = True
isVal _ = False
eval' :: Expr -> Maybe Expr
eval' x = case x of
IsZero Zero -> Just Tr
IsZero (Succ t) | isNum t -> Just Fl
IsZero t -> IsZero <$> eval' t
Succ t -> Succ <$> eval' t
Pred Zero -> Just Zero
Pred (Succ t) | isNum t -> Just t
Pred t -> Pred <$> eval' t
If Tr c _ -> Just c
If Fl _ a -> Just a
If t c a -> (\t' -> If t' c a) <$> eval' t
_ -> Nothing
-- we need that function to be able to evaluate multiple times
nf :: Expr -> Expr
nf x = fromMaybe x (nf <$> eval' x)
eval :: Expr -> Maybe Expr
eval t = case nf t of
nft | isVal nft -> Just nft
| otherwise -> Nothing -- term is "stuck"
|
AlphaMarc/WYAH
|
src/SimpleLang/Syntax.hs
|
Haskell
|
bsd-3-clause
| 2,692
|
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
module Config where
import Control.Applicative
import Control.Exception
import Data.ByteString (ByteString)
import Data.Configurator as C
import HFlags
import System.Directory
import System.FilePath
import System.IO
import Paths_sproxy_web
defineFlag "c:config" ("sproxy-web.config" :: String) "config file"
data Config = Config {
dbConnectionString :: ByteString,
port :: Int,
staticDir :: FilePath
}
deriving (Show, Eq)
-- | Get the connection string and the port
-- from the config file
getConfig :: FilePath -> IO Config
getConfig configFile = do
conf <- C.load [C.Required configFile]
Config <$>
C.require conf "db_connection_string" <*>
C.require conf "port" <*>
getStaticDir
getStaticDir :: IO FilePath
getStaticDir = do
currentDir <- getCurrentDirectory
staticExists <- doesDirectoryExist (currentDir </> "static")
if staticExists then do
hPutStrLn stderr ("Serving static files from " ++ currentDir ++
" -- This is bad since it probably allows to publicly access source code files.")
return currentDir
else do
cabalDataDir <- getDataDir
cabalDataDirExists <- doesDirectoryExist cabalDataDir
if cabalDataDirExists
then return cabalDataDir
else throwIO (ErrorCall "directory for static files not found.")
|
alpmestan/spw
|
src/Config.hs
|
Haskell
|
bsd-3-clause
| 1,432
|
module Module1.Task10 where
fibonacci :: Integer -> Integer
fibonacci n
| n == 0 = 0
| n == 1 = 1
| n < 0 = -(-1) ^ (-n) * fibonacci (-n)
| n > 0 = fibonacciIter 0 1 (n - 2)
fibonacciIter acc1 acc2 0 = acc1 + acc2
fibonacciIter acc1 acc2 n =
fibonacciIter (acc2) (acc1 + acc2) (n - 1)
|
dstarcev/stepic-haskell
|
src/Module1/Task10.hs
|
Haskell
|
bsd-3-clause
| 309
|
{-# LANGUAGE BangPatterns #-}
module Network.HPACK.Table.DoubleHashMap (
DoubleHashMap
, empty
, insert
, delete
, fromList
, deleteList
, Res(..)
, search
) where
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as H
import Data.List (foldl')
import Network.HPACK.Types
newtype DoubleHashMap a =
DoubleHashMap (HashMap HeaderName (HashMap HeaderValue a)) deriving Show
empty :: DoubleHashMap a
empty = DoubleHashMap H.empty
insert :: Ord a => Header -> a -> DoubleHashMap a -> DoubleHashMap a
insert (k,v) p (DoubleHashMap m) = case H.lookup k m of
Nothing -> let inner = H.singleton v p
in DoubleHashMap $ H.insert k inner m
Just inner -> let inner' = H.insert v p inner
in DoubleHashMap $ H.adjust (const inner') k m
delete :: Ord a => Header -> DoubleHashMap a -> DoubleHashMap a
delete (k,v) dhm@(DoubleHashMap outer) = case H.lookup k outer of
Nothing -> dhm -- Non-smart implementation makes duplicate keys.
-- It is likely to happen to delete the same key
-- in multiple times.
Just inner -> case H.lookup v inner of
Nothing -> dhm -- see above
_ -> delete' inner
where
delete' inner
| H.null inner' = DoubleHashMap $ H.delete k outer
| otherwise = DoubleHashMap $ H.adjust (const inner') k outer
where
inner' = H.delete v inner
fromList :: Ord a => [(a,Header)] -> DoubleHashMap a
fromList alist = hashinner
where
ins !hp (!a,!dhm) = insert dhm a hp
!hashinner = foldl' ins empty alist
deleteList :: Ord a => [Header] -> DoubleHashMap a -> DoubleHashMap a
deleteList hs hp = foldl' (flip delete) hp hs
data Res a = N | K a | KV a
search :: Ord a => Header -> DoubleHashMap a -> Res a
search (k,v) (DoubleHashMap outer) = case H.lookup k outer of
Nothing -> N
Just inner -> case H.lookup v inner of
Nothing -> case top inner of
Nothing -> error "DoubleHashMap.search"
Just a -> K a
Just a -> KV a
-- | Take an arbitrary entry. O(1) thanks to lazy evaluation.
top :: HashMap k v -> Maybe v
top = H.foldr (\v _ -> Just v) Nothing
|
bergmark/http2
|
Network/HPACK/Table/DoubleHashMap.hs
|
Haskell
|
bsd-3-clause
| 2,210
|
{-# LANGUAGE OverloadedStrings #-}
module Network.IRC.Bot.Part.Channels where
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (TVar, newTVar, readTVar, writeTVar)
import Control.Monad.Trans (MonadIO(liftIO))
import Data.Monoid ((<>))
import Data.Set (Set, insert, toList)
import Data.ByteString (ByteString)
import Data.ByteString.Char8(unpack)
import Network.IRC (Message(..), joinChan)
import Network.IRC.Bot.BotMonad (BotMonad(..))
import Network.IRC.Bot.Log (LogLevel(..))
initChannelsPart :: (BotMonad m) => Set ByteString -> IO (TVar (Set ByteString), m ())
initChannelsPart chans =
do channels <- atomically $ newTVar chans
return (channels, channelsPart channels)
channelsPart :: (BotMonad m) => TVar (Set ByteString) -> m ()
channelsPart channels =
do msg <- askMessage
let cmd = msg_command msg
case cmd of
"005" -> do chans <- liftIO $ atomically $ readTVar channels
mapM_ doJoin (toList chans)
_ -> return ()
where
doJoin :: (BotMonad m) => ByteString -> m ()
doJoin chan =
do sendMessage (joinChan chan)
logM Normal $ "Joining room " <> chan
joinChannel :: (BotMonad m) => ByteString -> TVar (Set ByteString) -> m ()
joinChannel chan channels =
do liftIO $ atomically $
do cs <- readTVar channels
writeTVar channels (insert chan cs)
sendMessage (joinChan chan)
|
eigengrau/haskell-ircbot
|
Network/IRC/Bot/Part/Channels.hs
|
Haskell
|
bsd-3-clause
| 1,451
|
{-# LANGUAGE MultiParamTypeClasses #-}
-- |
-- Module: $HEADER$
-- Description: Command line tool that generates random passwords.
-- Copyright: (c) 2013 Peter Trsko
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: non-portable (FlexibleContexts, depends on non-portable
-- module)
--
-- Command line tool that generates random passwords.
module Main.Application (runApp, processOptions)
where
import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.Char (isDigit)
import Data.Maybe (fromMaybe)
import Data.Version (Version)
import Data.Word (Word32)
import System.Console.GetOpt
( OptDescr(Option)
, ArgDescr(NoArg)
, ArgOrder(Permute)
, getOpt
)
import System.Exit (exitFailure)
import System.IO (Handle, stderr, stdout)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS (hPutStrLn, unwords)
import Data.Default.Class (Default(def))
import Data.Monoid.Endo hiding ((<>))
import Data.Semigroup (Semigroup((<>)))
import System.Console.Terminal.Size as Terminal (Window(..), size)
import System.Console.GetOpt.UsageInfo
( UsageInfoConfig(outputHandle)
, renderUsageInfo
)
import Main.ApplicationMode
( ApplicationMode(..)
, SimpleMode(..)
, changeAction
, updateConfiguration
)
import Main.ApplicationMode.SimpleAction (SimpleAction(..))
import qualified Main.ApplicationMode.SimpleAction as SimpleAction (optErrors)
import Main.Common (Parameters(..), printHelp, printVersion, printOptErrors)
import Main.MiniLens (E, L, get, mkL, set)
import Main.Random (withGenRand)
import qualified Text.Pwgen.Pronounceable as Pronounceable (genPwConfigBS)
import Text.Pwgen (genPassword)
import Paths_hpwgen (version)
-- | Default length of password.
defaultPwlen :: Word32
defaultPwlen = 8
-- | Default number of lines, this is used when printing passwords in columns,
-- but number of passwords wasn't specified.
defaultNumberOfLines :: Int
defaultNumberOfLines = 20
-- | Line length used when printing in columns, but to a handle that isn't a
-- terminal.
defaultLineLength :: Int
defaultLineLength = 80
type HpwgenMode = SimpleMode SimpleAction Config
instance ApplicationMode SimpleMode SimpleAction Config where
optErrors msgs = case SimpleAction.optErrors msgs of
Nothing -> mempty
Just a -> changeAction a
`mappend` updateConfiguration (set outHandleL stderr)
data Config = Config
{ cfgProgName :: String
, cfgVersion :: Version
, cfgPasswordLength :: Word32
, cfgNumberOfPasswords :: Maybe Int
, cfgPrintInColumns :: Maybe Bool
-- ^ If 'Nothing' then it's determined depending on the fact if output is
-- a terminal. When 'True' and output is not a terminal 80 character width
-- is assumed. And when 'False' then only one password is printed per line.
, cfgGeneratePronounceable :: Bool
, cfgIncludeNumbers :: Bool
, cfgIncludeSymbols :: Bool
, cfgIncludeUppers :: Bool
, cfgOutHandle :: Handle
}
instance Default Config where
def = Config
{ cfgProgName = ""
, cfgVersion = version
, cfgPasswordLength = defaultPwlen
, cfgNumberOfPasswords = Nothing
, cfgPrintInColumns = Nothing
, cfgGeneratePronounceable = True
, cfgIncludeNumbers = True
, cfgIncludeSymbols = True
, cfgIncludeUppers = True
, cfgOutHandle = stdout
}
outHandleL :: L Config Handle
outHandleL = mkL cfgOutHandle $ \ h c -> c{cfgOutHandle = h}
progNameL :: L Config String
progNameL = mkL cfgProgName $ \ pn c -> c{cfgProgName = pn}
generatePronounceableL :: L Config Bool
generatePronounceableL =
mkL cfgGeneratePronounceable $ \ b c -> c{cfgGeneratePronounceable = b}
passwordLengthL :: L Config Word32
passwordLengthL = mkL cfgPasswordLength $ \ n c -> c{cfgPasswordLength = n}
numberOfPasswordsL :: L Config (Maybe Int)
numberOfPasswordsL =
mkL cfgNumberOfPasswords $ \ n c -> c{cfgNumberOfPasswords = n}
includeNumbersL :: L Config Bool
includeNumbersL = mkL cfgIncludeNumbers $ \ b c -> c{cfgIncludeNumbers = b}
includeSymbolsL :: L Config Bool
includeSymbolsL = mkL cfgIncludeSymbols $ \ b c -> c{cfgIncludeSymbols = b}
includeUppersL :: L Config Bool
includeUppersL = mkL cfgIncludeUppers $ \ b c -> c{cfgIncludeUppers = b}
printInColumnsL :: L Config (Maybe Bool)
printInColumnsL = mkL cfgPrintInColumns $ \ b c -> c{cfgPrintInColumns = b}
params :: Parameters Config
params = def
{ paramOutputHandle = get outHandleL
, paramProgName = get progNameL
, paramCommand = get progNameL
, paramVersion = cfgVersion
, paramUsage = const
[ "[OPTIONS] [PASSWORD_LENGTH [NUMBER_OF_PASSWORDS]]"
, "{-h|--help|-V|--version|--numeric-version}"
]
}
options :: [OptDescr (Endo HpwgenMode)]
options =
{- TODO
[ Option "s" ["secure"]
(NoArg . updateConfiguration $ set generatePronounceableL False)
"Generate completely random passwords."
-}
[ Option "cu" ["capitalize", "upper"]
(NoArg . updateConfiguration $ set includeUppersL True)
$ defaultMark (get includeUppersL)
"Upper case letters will be included in passwords."
, Option "CU" ["no-capitalize", "no-upper"]
(NoArg . updateConfiguration $ set includeUppersL False)
$ defaultMark (not . get includeUppersL)
"Upper case letters won't be included in passwords."
, Option "n" ["numerals", "numbers"]
(NoArg . updateConfiguration $ set includeNumbersL True)
$ defaultMark (get includeNumbersL)
"Numbers will be included in passwords."
, Option "N0" [ "no-numerals", "no-numbers"]
(NoArg . updateConfiguration $ set includeNumbersL False)
$ defaultMark (not . get includeNumbersL)
"Numbers won't be included in passwords."
, Option "y" [ "symbols"]
(NoArg . updateConfiguration $ set includeSymbolsL True)
$ defaultMark (get includeSymbolsL)
"Special symbols will be included in passwords."
, Option "Y" [ "no-symbols"]
(NoArg . updateConfiguration $ set includeSymbolsL False)
$ defaultMark (not . get includeSymbolsL)
"Special symbols won't be included in passwords."
, Option "1" ["one-column"]
(NoArg . updateConfiguration . set printInColumnsL $ Just False)
"Passwords will be printed in only one column. If number of passwords\
\ is not specified, then only one password will be printed."
, Option "h" ["help"]
(NoArg $ changeAction PrintHelp)
"Print this help and exit."
, Option "V" ["version"]
(NoArg . changeAction $ PrintVersion False)
"Print version number and exit."
, Option "" ["numeric-version"]
(NoArg . changeAction $ PrintVersion True)
"Print version number (numeric form only) and exit. Useful for batch\
\ processing."
]
where
defaultMark :: (Config -> Bool) -> String -> String
defaultMark p
| p def = (++ " (default)")
| otherwise = id
processOptions :: String -> [String] -> Endo HpwgenMode
processOptions progName = mconcat . processOptions' . getOpt Permute options
where
processOptions' (endos, nonOpts, errs) =
optErrors errs
: processNonOpts nonOpts
: updateConfiguration (set progNameL progName)
: reverse endos
setNum :: Read a => (a -> E Config) -> String -> String -> Endo HpwgenMode
setNum setter what s
| all isDigit s = updateConfiguration . setter $ read s
| otherwise = optError
$ "Incorrect " ++ what ++ ": Expecting number, but got: " ++ show s
setPwNum, setPwLen :: String -> Endo HpwgenMode
setPwNum = setNum (set numberOfPasswordsL . Just) "number of passwords"
setPwLen = setNum (set passwordLengthL) "password length"
processNonOpts opts = case opts of
[] -> mempty
[n] -> setPwLen n
[n, m] -> setPwLen n <> setPwNum m
_ -> optError . ("Too many options: " ++) . unwords $ drop 2 opts
-- | Print passwords in columns.
printPasswords
:: Handle
-> Int
-- ^ Number of columns to print passwords in.
-> [ByteString]
-- ^ List of generated passwords.
-> IO ()
printPasswords _ _ [] = return ()
printPasswords h n pws = do
BS.hPutStrLn h $ BS.unwords x
printPasswords h n xs
where
(x, xs) = splitAt n pws
-- | Calculate number of columns to print passwords in and number of passwords
-- that should be generated.
numberOfColumnsAndPasswords
:: Config
-> Maybe Int
-- ^ Terminal width or 'Nothing' if not a terminal.
-> (Int, Int)
-- ^ Number of columns to print passwords in and number of passowrds that
-- will be generated.
numberOfColumnsAndPasswords cfg s = case (get printInColumnsL cfg, s) of
(Nothing, Nothing) -> (1, fromMaybe 1 pwNum)
-- In auto mode and output is not a terminal.
(Just False, _) -> (1, fromMaybe 1 pwNum)
-- Forcing one column mode, then by default just one password shouls be
-- printed.
(Just True, Nothing) -> let cols = numberOfColumns defaultLineLength
in (cols, fromMaybe (cols * defaultNumberOfLines) pwNum)
-- Forced to print in columns, but output is not a terminal, assuming
-- defaultLineLength character width.
(_, Just n) -> let cols = numberOfColumns n
in (cols, fromMaybe (cols * defaultNumberOfLines) pwNum)
-- Either in auto mode or forced to print in columns, output is a
-- terminal.
where
pwNum = fromIntegral <$> get numberOfPasswordsL cfg
-- n * pwlen + n - 1 <= terminalWidth
-- n * (pwlen + 1) - 1 <= terminalWidth
--
-- terminalWidth + 1
-- n <= -------------------
-- pwlen + 1
numberOfColumns n
| n <= pwlen = 1
| otherwise = case (n + 1) `div` (pwlen + 1) of
d | d <= 1 -> 1
| otherwise -> d
where
pwlen = fromIntegral $ get passwordLengthL cfg
runApp :: SimpleAction -> Config -> IO ()
runApp a cfg = case a of
PrintVersion numericOnly -> printVersion' numericOnly
PrintHelp -> printHelp'
OptErrors errs -> printOptErrors' errs >> printHelp' >> exitFailure
Action -> generatePasswords cfg
where
withParams f = f params cfg
printVersion' = withParams printVersion
printOptErrors' = withParams printOptErrors
printHelp' = do
str <- renderUsageInfo usageInfoCfg "" options
withParams printHelp (\ _ _ -> unlines [str])
where usageInfoCfg = def{outputHandle = get outHandleL cfg}
generatePasswords :: Config -> IO ()
generatePasswords cfg = do
(cols, pwNum) <- numberOfColumnsAndPasswords cfg . fmap width
<$> Terminal.size
printPasswords handle cols =<< withGenRand (\ genRandom ->
replicateM pwNum $ genPassword genPwCfg genRandom pwLen)
where
pwLen = get passwordLengthL cfg
handle = get outHandleL cfg
genPwCfg = (if get generatePronounceableL cfg
then Pronounceable.genPwConfigBS
else Pronounceable.genPwConfigBS)
(get includeUppersL cfg)
(get includeNumbersL cfg)
(get includeSymbolsL cfg)
-- secureCfg cfg =
|
trskop/hpwgen
|
src/Main/Application.hs
|
Haskell
|
bsd-3-clause
| 11,354
|
{-# LANGUAGE ViewPatterns #-}
module Plunge.Analytics.C2CPP
( lineAssociations
) where
import Data.List
import Plunge.Types.PreprocessorOutput
-- Fill in any gaps left by making associations out of CPP spans.
lineAssociations :: [Section] -> [LineAssociation]
lineAssociations ss = concat $ snd $ mapAccumL fillGap 1 assocs
where
fillGap :: LineNumber -> LineAssociation -> (LineNumber, [LineAssociation])
fillGap n (LineAssociation Nothing Nothing) = (n, [])
fillGap n a@(LineAssociation Nothing (Just _)) = (n, [a])
fillGap _ a@(LineAssociation (Just clr) Nothing) = (toLine clr, [a])
fillGap n a@(LineAssociation (Just clr) (Just _)) | n < cFrom = (cTo, [gap, a])
| n == cFrom = (cTo, [a])
| otherwise = (n, []) -- n > cFrom
where cTo = toLine clr
cFrom = fromLine clr
gap = LineAssociation (Just $ LineRange n cFrom) Nothing
assocs = sectionLineAssociations ss
sectionLineAssociations :: [Section] -> [LineAssociation]
sectionLineAssociations ss = map lineAssoc ss
where
lineAssoc (Block bls sl lr) =
LineAssociation { cppRange = Just lr
, cRange = Just $ LineRange sl (sl + (length bls))
}
lineAssoc (MiscDirective _ lr) =
LineAssociation { cppRange = Just lr
, cRange = Nothing
}
lineAssoc (Expansion _ (CppDirective stop _ _) n _ lr) =
LineAssociation { cppRange = Just lr
, cRange = Just $ LineRange n stop
}
|
sw17ch/plunge
|
src/Plunge/Analytics/C2CPP.hs
|
Haskell
|
bsd-3-clause
| 1,653
|
{-# LANGUAGE GADTs, TypeOperators #-}
module Compiler.InstantiateLambdas (instantiate, dump) where
import Compiler.Generics
import Compiler.Expression
import Control.Applicative
import Control.Arrow hiding (app)
import Control.Monad.Reader
import Data.List (intercalate)
import qualified Lang.Value as V
instantiate :: Arrow (~>) => V.Val l i ~> Expression
instantiate = arr (flip runReader 0 . tr)
where
tr :: V.Val l i -> Reader Integer Expression
tr (V.App f a ) = app <$> tr f <*> tr a
tr (V.Con c ) = pure (con c)
tr (V.Lam f ) = local (+1) (ask >>= \r -> let v = 'v':show r in lam [v] <$> tr (f (V.Var v)))
tr (V.Name n e ) = name n <$> tr e
tr (V.Prim s vs) = pure (prim s vs)
tr (V.Var v ) = pure (var v)
dump :: Arrow (~>) => Expression ~> String
dump = arr rec
where
tr (App f e ) = rec f ++ "(\n" ++ indent (rec e) ++ ")"
tr (Con c ) = c
tr (Lam as e) = "(function (" ++ intercalate ", " as ++ ")" ++ "\n{\n" ++ indent ("return " ++ rec e ++ ";") ++ "\n})"
tr (Name n e ) = "/* " ++ n ++ "*/ " ++ rec e
tr (Prim s vs) = s vs ++ " /* free: " ++ intercalate ", " vs ++ " */"
tr (Var v ) = v
rec = tr . unId . out
indent = unlines . map (" "++) . lines
|
tomlokhorst/AwesomePrelude
|
src/Compiler/InstantiateLambdas.hs
|
Haskell
|
bsd-3-clause
| 1,251
|
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
import Db
import Parser
import Trains
import Result
import Data.List
import System.IO
import System.Directory
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Writer
import Data.Monoid
import Data.Maybe
import Debug.Trace
todo = error "TODO"
{- a action parsed from user input,
- takes a Db, produces a new Db and some output to print
- and a flag telling us if we are done
-}
type Command = (Db -> (Db, String))
commands = Commands {
show_all_trains = todo,
show_all_routes = todo,
show_train = \id -> executeQuery (find_train_by_id id) (tell . show),
show_traincar = \id -> executeQuery (find_traincar_by_id id) (tell . show),
show_route = \id -> executeQuery (find_route_by_id id) (tell . show),
show_city = todo,
show_reservation = \id -> executeQuery (find_reservation_by_id id) (tell . show),
cmd_query2 = \start stop -> executeQuery (query2_query start stop) query2_printer,
cmd_query3 = \train car seat -> executeQuery (query3_query train car seat) query3_printer,
cmd_query4 = \trains -> executeQuery (query4_query trains) query4_printer,
unknown_command = \cmd db -> (db, "Unknown command: '" ++ cmd ++ "'")
}
-- | Get train car from train by index.
-- | Start counting at 1.
-- | So a train has cars [1 .. num-cars]
get_nth_car_of_train :: Train -> Int -> Maybe TrainCar
get_nth_car_of_train train n = do
guard (n >= 1)
guard (length (train_cars train) >= n)
return (train_cars train !! (n - 1))
-- | Compute all trains that pass a given station
transfers :: City -> Db -> [Train]
transfers city = db_trains -- get all trains
>>> filter (elem city . route_cities . train_route) -- filter out trains for city
executeQuery :: (Db -> Result a) -> (a -> Writer String b) -> Db -> (Db, String)
executeQuery query printer db = case query db of
(Ok a) -> (db, snd (runWriter (printer a)))
(Err msg) -> (db, "Error: " ++ msg)
train_printer train = tell (show train)
-- Mindestanzahl der freien und maximale Anzahl der durch Reservierung belegten Plätze pro Zug
-- und Waggon zwischen je zwei Stationen (wobei sich Minimum und Maximum darauf beziehen,
-- dass Reservierungen möglicherweise nur auf Teilen der abgefragten Strecke existieren);
-- Input: Eine List von Stationen
-- Output: Für jeden Wagon jeden Zuges, Anzahl der freien und reservierten Plätze zwischen den Stationen.
query2_query :: City -> City -> Db -> Result [(TrainId, [(TrainCarId, Int, Int)])]
query2_query start stop db = do
route <- route_from_endpoints start stop db
-- actual query runs in list monad
return $ do
train <- db_trains db
let cars = do
traincar <- train_cars train
-- filter out reservations for this train, car and route
let rs = do
r <- db_reservations db
guard (reservation_train r == train_id train) -- filter for this train
guard (reservation_traincar r == traincar_id traincar) -- filter for this traincar
guard (routes_overlap route (reservation_route r)) -- filter for this route
return r
let free = num_free_seats_for_car traincar (map reservation_slot rs)
let reserved = num_reserved_seats_for_car traincar (map reservation_slot rs)
return (traincar_id traincar, free, reserved)
return (train_id train, cars)
query2_printer :: [(TrainId, [(TrainCarId, Int, Int)])] -> Writer String ()
query2_printer trains = do
tell ("QUERY 2 FOUND " ++ show (length trains) ++ " RECORD(S)")
forM trains $ \(train, cars) -> do
tell ("TRAIN: " ++ tId train ++ "\n")
forM cars $ \(traincar, free_seats, reserved_seats) -> do
tell ("\tTRAIN CAR: " ++ tcId traincar ++ "\n")
tell ("\t\tFREE SEATS: " ++ show free_seats ++ "\n")
tell ("\t\tRESERVED SEATS: " ++ show reserved_seats ++ "\n")
return ()
-- Reservierungen für einen bestimmten Platz in einem Zug, wobei das Ergebnis die Stationen angibt,
-- zwischen denen Reservierungen bestehen;
-- Input: Ein Zug, ein Wagon, eine Sitznummer
-- Output: Alle Routen für die diser Sitz reserviert wurde.
--query3_query :: Train -> TrainCar -> Int -> Db -> Result [[City]]
query3_query train_id traincar_id seat db = do
train <- find_train_by_id train_id db -- validate train
traincar <- find_traincar_by_id traincar_id db -- validate traincar
return $ db_reservations -- get reservations from db
>>> filter ((train_id ==) . reservation_train) -- filter for this train
>>> filter ((traincar_id ==) . reservation_traincar) -- filter for this train
>>> filter ((slot_contains_seat seat) . reservation_slot) -- filter for `seat'
>>> map reservation_route -- get cities of reservation
$ db
query3_printer routes = do
tell ("QUERY 3 FOUND " ++ show (length routes) ++ " RECORD(S)")
forM routes $ \route -> do
tell (concat (intersperse ", " (map city_name route)))
tell "\n"
return ()
-- Mindestanzahl der zwischen zwei Stationen freien und der noch reservierbaren Plätze sowie die maximale Gruppengröße
-- (= maximale Zahl der Personen pro Reservierung) für einen Zug oder mehrere gegebene Züge (wenn Umsteigen nötig ist).
-- Input: Eine Liste von (Zug, Startstation, Endstation) Tupeln
-- Output: Für jeden Tupel, Anzahl der freien und reservierbaren Plätze, sowie Länge des größten freien Bereichs in einem Wagon,
-- zwischen den Stationen.
query4_query :: [(TrainId, City, City)] -> Db -> Result [(TrainId, Int, Int, Int)]
query4_query trains db = do
forM trains $ \(train_id, start, stop) -> do
train <- find_train_by_id train_id db
route <- route_from_endpoints start stop db
let cars = do
traincar <- train_cars train
-- filter out reservations for this train, car and route
let rs = do
r <- db_reservations db
guard (reservation_train r == train_id) -- filter for this train
guard (reservation_traincar r == traincar_id traincar) -- filter for this traincar
guard (routes_overlap route (reservation_route r)) -- filter for this route
return r
let free = num_free_seats_for_car traincar (map reservation_slot rs)
let max_group_size = max_group_size_for_car traincar (map reservation_slot rs)
return (free, max_group_size)
let free = sum (map fst cars) -- add up free seats from all cars
let reservable = free - (train_res_free_seats train) -- cannot reserve seats in free quota
let max_group_size = maximum (map snd cars) -- get biggest free slot
return (train_id, free, reservable, max_group_size)
query4_printer trains = do
tell ("QUERY 4 FOUND " ++ show (length trains) ++ " RECORD(S)")
forM trains $ \(train, free, reservable, max_group_size) -> do
tell ("\tTRAIN " ++ show (tId train) ++ "\n")
tell ("\t\tFREE SEATS: " ++ show free ++ "\n")
tell ("\t\tRESERVABLE SEATS: " ++ show reservable ++ "\n")
tell ("\t\tMAXIMUM GROUP SIZE: " ++ show max_group_size ++ "\n")
return ()
num_free_seats_for_train train db = do
let rs = db_reservations db
let free = do
car <- train_cars train
let rs' = filter (\r -> reservation_traincar r == traincar_id car) rs
let slots = map reservation_slot rs'
return (num_free_seats_for_car car slots)
return (sum free)
-- | Computes the number of free seats for a traincar
num_free_seats_for_car :: TrainCar -> [Slot] -> Int
num_free_seats_for_car traincar = traincar_status traincar -- compute free/reserved bitmap
>>> filter (==Free) -- filter for `free' bits
>>> length -- count `free' bits
-- | Computes the number of reserved seats for a traincar
num_reserved_seats_for_car :: TrainCar -> [Slot] -> Int
num_reserved_seats_for_car traincar = traincar_status traincar -- compute free/reserved bitmap
>>> filter (==Reserved) -- folter for `reserved' bits
>>> length -- count `reserved' bits
-- | Computes the size of the biggest free slot in a train car
max_group_size_for_car :: TrainCar -> [Slot] -> Int
max_group_size_for_car traincar = traincar_status traincar -- create free/reserved bitmap
>>> run_length_encode -- run length encode
>>> filter (\(a,_) -> a==Free) -- discard reserved slots
>>> map snd -- discard Free tags
>>> maximum -- get maximum
where
run_length_encode :: Eq a => [a] -> [(a, Int)]
run_length_encode [] = []
run_length_encode (l:ls) = encode l 0 (l:ls)
where
encode a n [] = [(a,n)]
encode a n (l:ls) | a == l = encode a (n+1) ls
| otherwise = (a,n) : encode l 0 (l:ls)
-- | A bitmap that shows which seats of a TrainCar are reserved or free
type TrainCarStatus = [SeatStatus]
data SeatStatus = Free | Reserved deriving (Show, Eq)
-- | Computes a bitmap telling us which seats are free or reserved from a list of reservations
-- | Works by computing a bitmap for each slot and just `or'ing together the bitmaps
traincar_status :: TrainCar -> [Slot] -> TrainCarStatus
traincar_status traincar reservations = foldl (zipWith or) initial_status (map slot_to_status reservations)
where
-- initially all seats are free
initial_status = times Free (traincar_num_seats traincar)
-- create bitmaps from reservation
slot_to_status s = times Free (slot_first_seat s - 1) ++ times Reserved (slot_num_seats s) ++ repeat Free
or Free Free = Free
or _ _ = Reserved
-- | Create a list that contains element `a' `n' times.
times :: a -> Int -> [a]
times a n = take n (repeat a)
-- | Given a route try to get the subroute starting at station `start' and ending at station `stop'
try_find_subroute :: City -> City -> [City] -> Maybe [City]
try_find_subroute start stop cities = do
a <- findIndex (start==) cities
b <- findIndex (stop ==) cities
guard (a < b)
return (drop a (take b cities))
main :: IO ()
main = do
let db_path = "zug.db"
putStrLn ">> STARTING APP"
db_exists <- doesFileExist db_path
when (not db_exists) $ do
putStrLn ">> CREATING DATABASE"
writeDb db_path db
putStrLn ">> READING DATABASE"
db' <- readDb db_path
putStrLn ">> READ DATABASE"
db'' <- mainLoop db'
putStrLn ">> WRITING DATABASE"
writeDb db_path db'' -- process changes in DB
putStrLn ">> WROTE DATABASE"
putStrLn ">> DONE"
_PROMPT = "$ "
mainLoop :: Db -> IO Db
mainLoop db = do
eof <- isEOF
if eof then
return db
else do
input <- getLine
cmd <- return (parse_command commands (id $! input))
(db', output) <- return (cmd db)
putStrLn output
mainLoop db'
readDb :: FilePath -> IO Db
readDb path = do
text <- readFile path
return $! read $! text -- $! makes sure file is fully read
writeDb :: FilePath -> Db -> IO ()
writeDb file db = writeFile file (show db)
|
fadeopolis/prog-spr-ue3
|
ue3.hs
|
Haskell
|
bsd-3-clause
| 11,533
|
a :: Int
a = 123
unittest "quote" [
(show {a}, "a"),
(show {,a}, ",a"),
(show {pred ,a}, "pred ,a"),
]
unittest "quasiquote" [
(`a, a),
(`(,a), 123),
(`(pred ,a), pred 123),
(let x = `(pred ,a) in x , 122),
]
-- quine
x = "x"
q = \x. `(,x {,x})
-- godel
isunprovable = "isunprovable"
valueof = "valueof"
g = \x -> `(isunprovable (valueof (,x {,x})))
unittest "quine & godel" [
(q {x}, x {x}),
(q {q}, q {q}),
(g {x}, isunprovable (valueof (x {x}))),
(g {g}, isunprovable (valueof (g {g}))),
]
{--}
|
ocean0yohsuke/Simply-Typed-Lambda
|
Start/UnitTest/Quote.hs
|
Haskell
|
bsd-3-clause
| 650
|
module Test.Pos.Crypto.Gen
(
-- Protocol Magic Generator
genProtocolMagic
, genProtocolMagicId
, genRequiresNetworkMagic
-- Sign Tag Generator
, genSignTag
-- Key Generators
, genKeypair
, genPublicKey
, genSecretKey
, genEncryptedSecretKey
-- Redeem Key Generators
, genRedeemKeypair
, genRedeemPublicKey
, genRedeemSecretKey
, genUnitRedeemSignature
-- VSS Key Generators
, genVssKeyPair
, genVssPublicKey
-- Proxy Cert and Key Generators
, genProxyCert
, genProxySecretKey
, genProxySignature
, genUnitProxyCert
, genUnitProxySecretKey
, genUnitProxySignature
-- Signature Generators
, genSignature
, genSignatureEncoded
, genSigned
, genRedeemSignature
, genUnitSignature
-- Secret Generators
, genDecShare
, genEncShare
, genSharedSecretData
, genSecret
, genSecretProof
-- Hash Generators
, genAbstractHash
, genWithHash
, genUnitAbstractHash
-- SafeSigner Generators
, genSafeSigner
-- PassPhrase Generators
, genPassPhrase
-- HD Generators
, genHDPassphrase
, genHDAddressPayload
) where
import Universum
import qualified Data.ByteArray as ByteArray
import Data.List.NonEmpty (fromList)
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Crypto.Hash (Blake2b_256)
import Pos.Binary.Class (Bi)
import Pos.Crypto (PassPhrase)
import Pos.Crypto.Configuration (ProtocolMagic (..),
ProtocolMagicId (..), RequiresNetworkMagic (..))
import Pos.Crypto.Hashing (AbstractHash (..), HashAlgorithm, WithHash,
abstractHash, withHash)
import Pos.Crypto.HD (HDAddressPayload (..), HDPassphrase (..))
import Pos.Crypto.Random (deterministic)
import Pos.Crypto.SecretSharing (DecShare, EncShare, Secret,
SecretProof, VssKeyPair, VssPublicKey, decryptShare,
deterministicVssKeyGen, genSharedSecret, toVssPublicKey)
import Pos.Crypto.Signing (EncryptedSecretKey, ProxyCert,
ProxySecretKey, ProxySignature, PublicKey,
SafeSigner (..), SecretKey, SignTag (..), Signature,
Signed, createPsk, deterministicKeyGen, mkSigned,
noPassEncrypt, proxySign, safeCreateProxyCert,
safeCreatePsk, sign, signEncoded, toPublic)
import Pos.Crypto.Signing.Redeem (RedeemPublicKey, RedeemSecretKey,
RedeemSignature, redeemDeterministicKeyGen, redeemSign)
----------------------------------------------------------------------------
-- Protocol Magic Generator
----------------------------------------------------------------------------
genProtocolMagic :: Gen ProtocolMagic
genProtocolMagic = ProtocolMagic <$> genProtocolMagicId
<*> genRequiresNetworkMagic
genProtocolMagicId :: Gen ProtocolMagicId
genProtocolMagicId = ProtocolMagicId <$> Gen.int32 Range.constantBounded
genRequiresNetworkMagic :: Gen RequiresNetworkMagic
genRequiresNetworkMagic = Gen.element [RequiresNoMagic, RequiresMagic]
----------------------------------------------------------------------------
-- Sign Tag Generator
----------------------------------------------------------------------------
genSignTag :: Gen SignTag
genSignTag = Gen.element
[ SignForTestingOnly
, SignTx
, SignRedeemTx
, SignVssCert
, SignUSProposal
, SignCommitment
, SignUSVote
, SignMainBlock
, SignMainBlockLight
, SignMainBlockHeavy
, SignProxySK
]
----------------------------------------------------------------------------
-- Key Generators
----------------------------------------------------------------------------
genKeypair :: Gen (PublicKey, SecretKey)
genKeypair = deterministicKeyGen <$> gen32Bytes
genPublicKey :: Gen PublicKey
genPublicKey = fst <$> genKeypair
genSecretKey :: Gen SecretKey
genSecretKey = snd <$> genKeypair
genEncryptedSecretKey :: Gen EncryptedSecretKey
genEncryptedSecretKey = noPassEncrypt <$> genSecretKey
----------------------------------------------------------------------------
-- Redeem Key Generators
----------------------------------------------------------------------------
genRedeemKeypair :: Gen (Maybe (RedeemPublicKey, RedeemSecretKey))
genRedeemKeypair = redeemDeterministicKeyGen <$> gen32Bytes
genRedeemPublicKey :: Gen (RedeemPublicKey)
genRedeemPublicKey = do
rkp <- genRedeemKeypair
case rkp of
Nothing -> error "Error generating a RedeemPublicKey."
Just (pk, _) -> return pk
genRedeemSecretKey :: Gen (RedeemSecretKey)
genRedeemSecretKey = do
rkp <- genRedeemKeypair
case rkp of
Nothing -> error "Error generating a RedeemSecretKey."
Just (_, sk) -> return sk
genUnitRedeemSignature :: Gen (RedeemSignature ())
genUnitRedeemSignature = do pm <- genProtocolMagic
genRedeemSignature pm (pure ())
----------------------------------------------------------------------------
-- VSS Key Generators
----------------------------------------------------------------------------
genVssKeyPair :: Gen VssKeyPair
genVssKeyPair = deterministicVssKeyGen <$> gen32Bytes
genVssPublicKey :: Gen VssPublicKey
genVssPublicKey = toVssPublicKey <$> genVssKeyPair
----------------------------------------------------------------------------
-- Proxy Cert and Key Generators
----------------------------------------------------------------------------
genProxyCert :: Bi w => ProtocolMagic -> Gen w -> Gen (ProxyCert w)
genProxyCert pm genW =
safeCreateProxyCert pm <$> genSafeSigner <*> genPublicKey <*> genW
genProxySecretKey :: Bi w => ProtocolMagic -> Gen w -> Gen (ProxySecretKey w)
genProxySecretKey pm genW =
safeCreatePsk pm <$> genSafeSigner <*> genPublicKey <*> genW
genProxySignature
:: (Bi w, Bi a)
=> ProtocolMagic
-> Gen a
-> Gen w
-> Gen (ProxySignature w a)
genProxySignature pm genA genW = do
delegateSk <- genSecretKey
issuerSk <- genSecretKey
w <- genW
a <- genA
let psk = createPsk pm issuerSk (toPublic delegateSk) w
return $ proxySign pm SignProxySK delegateSk psk a
genUnitProxyCert :: Gen (ProxyCert ())
genUnitProxyCert = do pm <- genProtocolMagic
genProxyCert pm $ pure ()
genUnitProxySecretKey :: Gen (ProxySecretKey ())
genUnitProxySecretKey = do pm <- genProtocolMagic
genProxySecretKey pm $ pure ()
genUnitProxySignature :: Gen (ProxySignature () ())
genUnitProxySignature = do
pm <- genProtocolMagic
genProxySignature pm (pure ()) (pure ())
----------------------------------------------------------------------------
-- Signature Generators
----------------------------------------------------------------------------
genSignature :: Bi a => ProtocolMagic -> Gen a -> Gen (Signature a)
genSignature pm genA =
sign pm <$> genSignTag <*> genSecretKey <*> genA
genSignatureEncoded :: Gen ByteString -> Gen (Signature a)
genSignatureEncoded genB =
signEncoded <$> genProtocolMagic <*> genSignTag <*> genSecretKey <*> genB
genSigned :: Bi a => Gen a -> Gen (Signed a)
genSigned genA =
mkSigned <$> genProtocolMagic <*> genSignTag <*> genSecretKey <*> genA
genRedeemSignature
:: Bi a
=> ProtocolMagic
-> Gen a
-> Gen (RedeemSignature a)
genRedeemSignature pm genA =
redeemSign pm <$> gst <*> grsk <*> genA
where
gst = genSignTag
grsk = genRedeemSecretKey
genUnitSignature :: Gen (Signature ())
genUnitSignature = do pm <- genProtocolMagic
genSignature pm (pure ())
----------------------------------------------------------------------------
-- Secret Generators
----------------------------------------------------------------------------
genDecShare :: Gen DecShare
genDecShare = do
(_, _, xs) <- genSharedSecretData
case fmap fst (uncons xs) of
Just (vkp, es) -> return $ deterministic "ds" $ decryptShare vkp es
Nothing -> error "Error generating a DecShare."
genEncShare :: Gen EncShare
genEncShare = do
(_, _, xs) <- genSharedSecretData
case fmap fst (uncons xs) of
Just (_, es) -> return es
Nothing -> error "Error generating an EncShare."
genSharedSecretData :: Gen (Secret, SecretProof, [(VssKeyPair, EncShare)])
genSharedSecretData = do
let numKeys = 128 :: Int
parties <- Gen.integral (Range.constant 4 (fromIntegral numKeys)) :: Gen Integer
threshold <- Gen.integral (Range.constant 2 (parties - 2)) :: Gen Integer
vssKeyPairs <- replicateM numKeys genVssKeyPair
let vssPublicKeys = map toVssPublicKey vssKeyPairs
(s, sp, xs) = deterministic "ss" $ genSharedSecret threshold (fromList vssPublicKeys)
ys = zipWith (\(_, y) x -> (x, y)) xs vssKeyPairs
return (s, sp, ys)
genSecret :: Gen Secret
genSecret = do
(s, _, _) <- genSharedSecretData
return s
genSecretProof :: Gen SecretProof
genSecretProof = do
(_, sp, _) <- genSharedSecretData
return sp
----------------------------------------------------------------------------
-- Hash Generators
----------------------------------------------------------------------------
genAbstractHash
:: (Bi a, HashAlgorithm algo)
=> Gen a
-> Gen (AbstractHash algo a)
genAbstractHash genA = abstractHash <$> genA
genUnitAbstractHash :: Gen (AbstractHash Blake2b_256 ())
genUnitAbstractHash = genAbstractHash $ pure ()
genWithHash :: Bi a => Gen a -> Gen (WithHash a)
genWithHash genA = withHash <$> genA
----------------------------------------------------------------------------
-- PassPhrase Generators
----------------------------------------------------------------------------
genPassPhrase :: Gen PassPhrase
genPassPhrase = ByteArray.pack <$> genWord8List
where
genWord8List :: Gen [Word8]
genWord8List =
Gen.list (Range.singleton 32) (Gen.word8 Range.constantBounded)
----------------------------------------------------------------------------
-- SafeSigner Generators
----------------------------------------------------------------------------
genSafeSigner :: Gen SafeSigner
genSafeSigner = Gen.choice gens
where
gens = [ SafeSigner <$> genEncryptedSecretKey <*> genPassPhrase
, FakeSigner <$> genSecretKey
]
----------------------------------------------------------------------------
-- HD Generators
----------------------------------------------------------------------------
genHDPassphrase :: Gen HDPassphrase
genHDPassphrase = HDPassphrase <$> gen32Bytes
genHDAddressPayload :: Gen HDAddressPayload
genHDAddressPayload = HDAddressPayload <$> gen32Bytes
----------------------------------------------------------------------------
-- Helper Generators
----------------------------------------------------------------------------
genBytes :: Int -> Gen ByteString
genBytes n = Gen.bytes (Range.singleton n)
gen32Bytes :: Gen ByteString
gen32Bytes = genBytes 32
|
input-output-hk/pos-haskell-prototype
|
crypto/test/Test/Pos/Crypto/Gen.hs
|
Haskell
|
mit
| 11,486
|
{-
--Task 4
--power x*y =
--if x*y==0
--then 0
--else if (x*y) != 0
--then x+(x*(y-1))
--These are home tasks
--bb bmi
--| bmi <= 10 ="a"
--| bmi <= 5 = "b"
--| otherwise = bmi
slope (x1,y1) (x2,y2) = dy / dx
where dy = y2-y1
dx = x2 - x1
--Task 2
reci x = 1/x;
--Task 3
--abst x
--Task 4
sign x
| x<0 = -1
| x>0 = 1
| x==0 = 0
|otherwise = 0
signNum x =
if x>0
then 1
else if x<0
then -1
else 0
--Task 5
threeDifferent x y z
| x==y && y==z && x==z = True
| otherwise = False
--Task 6
maxofThree x y z
| x>y && x>z = x
| y>x && y>z = y
| otherwise = z
--Task 7
numString x
| x==1 ="One"
| x==2 ="Two"
| x==3 ="Three"
| x==4 ="Four"
| x==5 ="Five"
| otherwise = "Your input in not less than 6 "
(!) _ True = True
(!) True _ = True
--This is fibnanci funciton
fib:: Int -> Int
fib 0 = 1
fib 1 = 1
fib x = fib(x-1) + fib(x-2)
charName ::Char -> String
charName 'a' = "Albert"
charName 'b' = "Broseph"
cahrName 'c' = "Cecil"
-}
|
badarshahzad/Learn-Haskell
|
week 2 & 3/function.hs
|
Haskell
|
mit
| 974
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TupleSections #-}
#if MIN_VERSION_base(4,8,0)
{-# LANGUAGE PatternSynonyms #-}
#endif
module Succinct.Sequence (
-- $intro
WaveletTree(..),
Encoding(..),
buildOptimizedAlphabeticalSearchTree,
huTucker,
validHuTuckerTree,
) where
import Control.Applicative
import Control.Monad
import Data.Profunctor
import Data.Bifunctor
import Data.Bits
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Data.Ord
import Data.List
import Data.Function
import Succinct.Tree.Types
import Succinct.Dictionary.Builder
import Succinct.Internal.Building
import Succinct.Dictionary.Class
import Succinct.Dictionary.Rank9
import Data.Bitraversable
import qualified Data.PriorityQueue.FingerTree as PQ
import qualified Data.Map as M
import qualified Data.Sequence as S
import qualified Data.IntSet as IS
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import Data.Maybe
import Control.Monad.ST (runST)
import Control.Monad.ST.Unsafe
import Data.Monoid
import Debug.Trace
-- $setup
-- >>> :set -XFlexibleContexts
-- The members of the alphabet need an encoding
newtype Encoding a = Encoding { runEncoding :: Labelled () a } deriving Show
directionToBool :: Direction -> Bool
#if MIN_VERSION_base(4,8,0)
-- We have pattern synonyms
newtype Direction = Direction Bool
instance Show Direction where
show (Direction False) = show "L"
show (Direction True) = show "R"
pattern L = Direction False
pattern R = Direction True
directionToBool (Direction x) = x
#else
data Direction = L | R deriving Show
directionToBool L = False
directionToBool R = True
#endif
-- endif MIN_VERSION_base(4,8,0)
{-# INLINE directionToBool #-}
-- | O(nlog(n)). Given elements in a dictionary and their probability of occuring,
-- produce a huffman encoding.
huffmanEncoding :: (Num n, Ord n, Functor m, Monad m) => [(a, n)] -> m (Encoding a)
huffmanEncoding input =
let initial = PQ.fromList $ fmap (\(a, b) -> (b, LabelledTip a)) input
in Encoding <$> huffmanHeapToTree initial
huffmanHeapToTree :: (Ord n, Num n, Monad m) => PQ.PQueue n (Labelled () a) -> m (Labelled () a)
huffmanHeapToTree pq = case PQ.minViewWithKey pq of
Just ((k, v), rest) -> case PQ.minViewWithKey rest of
Just ((k2, v2), rest2) -> huffmanHeapToTree $ PQ.insert (k+k2) (LabelledBin () v v2) rest2
Nothing -> return v
Nothing -> fail "huffmanEncoding: No elements received"
buildHistogram :: (Ord a, Num n) => Builder a (M.Map a n)
buildHistogram = Builder $ Building stop step start
where
stop = pure
step x c = pure $ M.insertWith (+) c 1 x
start = pure M.empty
buildHuffmanEncoding :: forall a. (Ord a) => Builder a (Encoding a)
buildHuffmanEncoding = fmap (fromJust . huffmanEncoding . M.toList) (buildHistogram :: Builder a (M.Map a Int))
-- | O(n^2). Given a list of characters of an alphabet with a
-- frequency, produce an encoding that respects the order provided.
-- TODO: this is an implementation of Knuth's O(n^2) dynamic
-- programming solution. Hu-Tucker can solve this in O(nlogn) in
-- general.
buildOptimalAlphabeticSearchTree :: [(a, n)] -> Builder a (Encoding a)
buildOptimalAlphabeticSearchTree = undefined
diagonalIndex n i j | trace ("(i, j) = " <> show (i,j)) False = undefined
diagonalIndex n i j = n * i - i * (i + 1) `div` 2 + j
-- data KnuthBuilder s a = KnuthBuilder { weight :: V.STVector s a
-- , root :: V.STVector s a
-- , path :: V.STVector s a
-- }
foldableLength :: F.Foldable f => f a -> Int
#if MIN_VERSION_base(4,8,0)
foldableLength = F.length
#else
foldableLength = length . F.toList
#endif
-- --buildOptimalSearchTree :: (Functor f, F.Foldable f, n ~ Int) => f (a, n) -> Labelled () a
-- buildOptimalSearchTree input = runST $ do
-- let n = foldableLength input
-- space = (n+1) * (n+2) `div` 2
-- index = diagonalIndex (n+1)
-- get v (i, j) = if j < i then error (show (i, j)) else MV.read v (index i j)
-- -- no checks
-- grab v (i, j) = MV.read v (index i j)
-- weight <- MV.new space
-- root <- MV.replicate space (-1)
-- path <- MV.new space
-- forM_ (zip [1..n] $ F.toList $ fmap snd input) $ \(k, p) -> do
-- let i = index k k
-- MV.write weight i p
-- MV.write root i k
-- MV.write path i p
-- MV.write path (index k (k-1)) 0
-- MV.write path (index (n+1) n) 0
-- forM_ [1..n-1] $ \diagonal -> do
-- forM_ [1..n-diagonal] $ \j -> do
-- let k = j + diagonal
-- MV.write weight (index j k) =<< ((+) <$> (weight `get` (j, k-1)) <*> (weight `get` (k, k)))
-- root1 <- root `get` (j, k-1)
-- root2 <- root `get` (j+1, k)
-- (p, _) <- F.minimumBy (comparing snd) <$> (
-- forM [root1..root2] $ \p -> do
-- a <- path `grab` (j, p-1)
-- b <- path `grab` (p+1, k)
-- return (p, a + b))
-- unsafeIOToST $ putStrLn $ "p: " <> show p
-- unsafeIOToST $ putStrLn $ "root" <> show (j,k) <> ": " <> show p
-- MV.write root (index j k) p
-- MV.write path (index j k) =<< liftA3 (\a b c -> a + b + c) (path `grab` (j, p-1)) (path `grab` (p+1, k)) (weight `get` (j, k))
-- let go (i, j) | i > j = error $ "creating tree found i > j: " <> show (i, j)
-- go (i, j) | i == j = pure $ LabelledTip $ i-1
-- go (i, j) = do
-- split <- root `grab` (i, j)
-- LabelledBin (split - 1) <$> go (i, split-1) <*> go (split+1, j)
-- let depth _ (i, j) | i > j = error $ "creating tree found i > j: " <> show (i, j)
-- depth !d (i, j) | i == j = pure $ [(d, i-1)]
-- depth !d (i, j) = do
-- split <- root `grab` (i, j)
-- lefties <- depth (d+1) (i, split-1)
-- righties <- depth (d+1) (split+1, j)
-- return $ [(d, split - 1)] ++ lefties ++ righties
-- depth 0 (1, n)
data Attraction = PreviousPrevious | Previous | Self | Next | NextNext deriving (Show, Eq, Ord)
data Elem heap b a = Elem (Either a (heap b)) [Attraction]
| LeftBoundary
| RightBoundary
deriving (Eq)
instance (Show a, Show b, F.Foldable heap) => Show (Elem heap b a) where
show (Elem (Left x) a) = "Elem " <> show x <> " " <> show a
show (Elem (Right h) a) = "Elem " <> show (F.toList h) <> " " <> show a
show LeftBoundary = "LeftBoundary"
show RightBoundary = "RightBoundary"
attraction (Elem _ a) = a
attraction LeftBoundary = [Previous]
attraction RightBoundary = [Next]
isBoundary LeftBoundary = True
isBoundary RightBoundary = True
isBoundary _ = False
decideAttraction xs = map f $ filter ok $ tails $ Nothing : fmap Just xs ++ [Nothing]
where f (Nothing:_:_:_) = Next
f (_:_:Nothing:_) = Previous
f (Just a:Just _:Just c:_) = case compare a c of
LT -> Previous
_ -> Next
ok (_:_:_:_) = True
ok _ = False
--huTucker ::
huTucker = constructTree . breadthFirstSearch . buildOptimizedAlphabeticalSearchTree
-- return tree in increasing depth
breadthFirstSearch :: Labelled () a -> [(a, Int)]
breadthFirstSearch t = go $ S.singleton (t, 0)
where go to_visit = case S.viewl to_visit of
S.EmptyL -> []
(LabelledTip a, !l) S.:< rest -> (a, l) : go rest
(LabelledBin _ left right, !l) S.:< rest ->
go (rest S.|> (left, l+1) S.|> (right, l+1))
pair :: [a] -> [(a, a)]
pair [] = []
pair [x] = error "pair: odd man out"
pair (a:b:rest) = (a, b) : pair rest
iterateN :: Int -> (a -> a) -> (a -> a)
iterateN n f = foldl (.) id $ replicate n f
constructTree :: [((Int, a), Int)] -> Labelled () a
constructTree = snd . pairUp . snd . foldl1 (\(old_level, acc) (new_level, new) -> (new_level, merge new $ iterateN (old_level - new_level) bin acc)) . map (\l -> (snd $ head l, map fst l)) . map (sortBy (comparing (fst.fst))) . reverse . groupBy ((==) `on` snd) . map (\((index, value), height) -> ((index, LabelledTip value), height))
where
bin x = map (\((i,a), (_,b)) -> (i, LabelledBin () a b)) . pair $ x
pairUp [] = error "nothing to pair"
pairUp [x] = x
pairUp xs = pairUp (bin xs)
merge a b = sortBy (comparing fst) $ a <> b
codewords :: Labelled () a -> [(a, [Bool])]
codewords t = fmap (\(a, code) -> (a, reverse code)) $ go $ S.singleton (t, [])
where go to_visit = case S.viewl to_visit of
S.EmptyL -> []
(LabelledTip a, code) S.:< rest -> (a, code) : go rest
(LabelledBin _ left right, code) S.:< rest ->
go (rest S.|> (left, False:code) S.|> (right, True:code))
buildOptimizedAlphabeticalSearchTree :: forall a n. (Show a, Eq a, Show n, Ord n, Num n, Bounded n) => [(a, n)] -> Labelled () a
buildOptimizedAlphabeticalSearchTree [] = error "Cannot build with empty list of elements"
buildOptimizedAlphabeticalSearchTree input = go (repeat LeftBoundary) $ (<> repeat RightBoundary) $ fmap (\((a, freq), attract) -> Elem (Left (freq, LabelledTip a)) [attract]) $ zip input $ decideAttraction $ fmap snd $ input
where
go past [] = error $ "Internal error: empty future. Past: " <> show (takeWhile (not . isBoundary) past)
go past (RightBoundary:_) = error $ "Internal error: no current. Past: " <> show (takeWhile (not . isBoundary) past)
go (LeftBoundary:_) (Elem (Left (_, x)) _:RightBoundary:_) = x
go (LeftBoundary:_) (Elem (Right h) _:RightBoundary:_) = fromJust $ huffmanHeapToTree h
-- If the person I like likes me back, then we deal with it now.
go past@(p:past1@(p2:ps)) (x:future@(next:future1@(next2:xs))) =
case head $ attraction x of
PreviousPrevious | NextNext `elem` attraction p2 ->
combine ps (merge (contents p) (fix (contents p2) (contents x))) future
Previous | Next `elem` attraction p ->
combine past1 (fix (contents p) (contents x)) future
Self | Elem (Right heap) _ <- x ->
let heap' = case PQ.minViewWithKey heap of
Just ((k, v), rest) -> case PQ.minViewWithKey rest of
Just ((k2, v2), rest2) -> PQ.insert (k+k2) (LabelledBin () v v2) rest2
Nothing -> error "You shouldn't self attract if you only have one element in the heap"
Nothing -> error "heap cannot be empty"
in adjust past (Right heap') future
Next | Previous `elem` attraction next ->
combine past (fix (contents x) (contents next)) future1
NextNext | PreviousPrevious `elem` attraction next2 ->
let c = merge (fix (contents x) (contents next2)) (contents next)
in combine past c xs
-- She loves me not
_ -> go (x:past) future
value (Elem (Left (freq, _)) _) = freq
value (Elem (Right h) _) = heapValue h
value RightBoundary = maxBound
value LeftBoundary = maxBound
contents (Elem x _) = x
-- Guaranteed that heap is non-empty
heapValue h = case PQ.minViewWithKey h of
Just ((k, v), rest) -> k
secondSmallestElement h = fst <$> (PQ.minViewWithKey =<< snd <$> PQ.minView h)
combine past@(p:past2) x future@(f:future2) =
case (isBlocked p, isBlocked f) of
(False, False) -> adjust past2 (merge (contents p) $ merge x (contents f)) future2
(False, True) -> adjust past2 (merge (contents p) x) future
(True, False) -> adjust past (merge x (contents f)) future2
(True, True) -> adjust past x future
adjust past x future =
let e = calculate past x future
(a:past') = fixPast past (e:future)
future' = e : fixFuture (e:past) future
in go past' (a:future')
fixPast rest@(LeftBoundary:_) _ = rest
fixPast (Elem heap _:rest@(LeftBoundary:_)) future =
calculate rest heap future : rest
fixPast (e1@(Elem heap1 _):rest@(Elem heap2 _:rest2)) future =
calculate rest heap1 future : calculate rest2 heap2 (e1 : future) : rest2
fixFuture _ rest@(RightBoundary:_) = rest
fixFuture past (Elem heap _:rest@(RightBoundary:_)) = calculate past heap rest : rest
fixFuture past (e1@(Elem heap1 _):rest@(Elem heap2 _:rest2)) = calculate past heap1 rest : calculate (e1 : past) heap2 rest2 : rest2
ff (Left x) = "Left " <> show x
ff (Right x) = "Right " <> show (F.toList x)
calculate (p:p2:_) heap (f:f2:_) =
Elem heap $
if can_skip
then best $ [(value p, Previous), (value f, Next)] ++
(if not $ isBlocked p then [(value p2, PreviousPrevious)] else []) ++
(if not $ isBlocked f then [(value f2, NextNext)] else [])
else case secondSmallestValue of
Just (k, _) -> best [(value p, Previous), (k, Self), (value f, Next)]
Nothing -> best [(value p, Previous), (value f, Next)]
where secondSmallestValue = case heap of
Left _ -> Nothing
Right h -> secondSmallestElement h
can_skip = case heap of
Left _ -> True
Right _ -> False
best = map snd . head . groupBy ((==) `on` fst) . sortBy (comparing fst)
fix a = Right . fix' a
fix' (Left (k1, v1)) (Left (k2, v2)) = PQ.singleton (k1 + k2) $ LabelledBin () v1 v2
fix' (Left (k1, v1)) (Right h) = case PQ.minViewWithKey h of
Just ((k2, v2), rest) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) rest
fix' (Right h) (Left (k2, v2)) = case PQ.minViewWithKey h of
Just ((k1, v1), rest) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) rest
fix' (Right h1) (Right h2) = case PQ.minViewWithKey h1 of
Just ((k1, v1), rest) -> case PQ.minViewWithKey h2 of
Just ((k2, v2), rest2) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) $ rest <> rest2
merge a b = Right $ f a <> f b
where f = either (uncurry PQ.singleton) id
isBlocked (Elem (Right _) _) = False
isBlocked _ = True
validHuTuckerTree :: (Eq a, Ord a) => Labelled () a -> Bool
validHuTuckerTree t = let nodes = inOrderTraversal t
in nodes == sort nodes
inOrderTraversal :: Labelled () a -> [a]
inOrderTraversal (LabelledTip a) = [a]
inOrderTraversal (LabelledBin () l r) = inOrderTraversal l ++ inOrderTraversal r
data WaveletTree f a = WaveletTree { bits :: Labelled f a
, alphabet :: a -> Int -> Direction -- ^ For a given level, is the element to the right or to the left?
}
instance (Access Bool f, Ranked f) => F.Foldable (WaveletTree f) where
foldMap f t = F.foldMap f $ map (t !) [0 .. size t - 1]
-- mapBits f (WaveletTree bits alphabet) = WaveletTree (first f bits) alphabet
instance (Access Bool f, Ranked f) => Access a (WaveletTree f a) where
size (WaveletTree t _) = case t of
LabelledTip _ -> 0
LabelledBin x _ _ -> size x
(!) (WaveletTree t0 _) index0 = go t0 index0
where go t index = case t of
LabelledTip a -> a
LabelledBin x left right ->
if x ! index
then go right (rank1 x index)
else go left (rank0 x index)
instance (Access Bool f, Select0 f, Select1 f, Ranked f) => Dictionary a (WaveletTree f a) where
rank a (WaveletTree t0 find) i0 = go 0 t0 i0
where finda = find a
go level t i = case t of
LabelledTip _ -> i
LabelledBin x left right ->
case finda level of
L -> go (level+1) left (rank0 x i)
R -> go (level+1) right (rank1 x i)
select a (WaveletTree t0 find) i0 = findPath 0 t0 i0
where finda = find a
findPath level t = case t of
LabelledTip _ -> id
LabelledBin x left right ->
case finda level of
L -> (select0 x) . findPath (level+1) left
R -> (select1 x) . findPath (level+1) right
-- $intro
-- >>> :{
-- let abracadabraFind 'a' = const False
-- abracadabraFind 'b' = odd
-- abracadabraFind 'c' = (> 0)
-- abracadabraFind 'd' = even
-- abracadabraFind 'r' = const True
-- :}
--
-- >>> :{
-- let bin = LabelledBin ()
-- tip = LabelledTip
-- abracadabraEncoding =
-- bin (bin (tip 'a') (bin (tip 'b') (tip 'c'))) (bin (tip 'd') (tip 'r'))
-- :}
--
-- >>> :{
-- let (t, f) = (True, False)
-- tree = LabelledBin (build [f, f, t, f, f, f, t, f, f, t, f])
-- -- a & (b & c)
-- (LabelledBin (build [f, t, f, t, f, f, t, f]) (LabelledTip 'a')
-- -- b & c
-- (LabelledBin (build [f, t, f]) (LabelledTip 'b') (LabelledTip 'c')))
-- -- d & r
-- (LabelledBin (build [t, f, t]) (LabelledTip 'd') (LabelledTip 'r'))
-- exampleWaveletTree :: WaveletTree Rank9 Char
-- exampleWaveletTree = WaveletTree tree abracadabraFind
-- :}
--
-- Inefficient foldable
--
-- >>> F.toList exampleWaveletTree
-- "abracadabra"
--
-- >>> [(c, map (select c exampleWaveletTree) [1.. rank c exampleWaveletTree (size exampleWaveletTree)]) | c <- "abcdr"]
-- [('a',[1,4,6,8,11]),('b',[2,9]),('c',[5]),('d',[7]),('r',[3,10])]
--
-- >>> [(c, map (rank c exampleWaveletTree) [0.. size exampleWaveletTree]) | c <- "abcdr"]
-- [('a',[0,1,1,1,2,2,3,3,4,4,4,5]),('b',[0,0,1,1,1,1,1,1,1,2,2,2]),('c',[0,0,0,0,0,1,1,1,1,1,1,1]),('d',[0,0,0,0,0,0,0,1,1,1,1,1]),('r',[0,0,0,1,1,1,1,1,1,1,2,2])]
asListOfNumbers :: Access Bool t => t -> [Int]
asListOfNumbers t = concat [ [x | t ! x] | x <- [0 .. size t - 1] ]
buildWithEncoding :: forall a f. Buildable Bool f => Encoding a -> (a -> Int -> Direction) -> Builder a (Labelled f a)
buildWithEncoding (Encoding e) f = Builder $ case builder :: Builder Bool f of
Builder (Building stop' step' start') ->
Building stop step start
where
start = bifor e (const start') pure
stop x = bifor x stop' pure
step x0 c0 = walk c0 0 x0
where walk _ _ a@(LabelledTip{}) = pure a
walk c !l (LabelledBin v a b) =
let dir = f c l
q = LabelledBin <$> step' v (directionToBool dir)
in case dir of
L -> q <*> walk c (l+1) a <*> pure b
R -> q <*> pure a <*> walk c (l+1) b
decidingFunction :: Eq a => Encoding a -> (a -> Int -> Direction)
decidingFunction (Encoding enc0) = \c -> let Just t = fmap reverse $ go enc0 c [] in (t !!)
where go (LabelledTip c') c visited = do
guard $ c == c'
return $ visited
go (LabelledBin _ l _) c visited | Just x <- go l c (L:visited ) = Just x
go (LabelledBin _ _ r) c visited | Just x <- go r c (R:visited ) = Just x
go _ _ _ = Nothing
instance (Ord a, Buildable Bool f) => Buildable a (WaveletTree f a) where
builder = runNonStreaming $ do
enc <- NonStreaming $ buildHuffmanEncoding
let fun = decidingFunction enc
NonStreaming $ WaveletTree <$> buildWithEncoding enc fun <*> pure fun
|
Gabriel439/succinct
|
src/Succinct/Sequence.hs
|
Haskell
|
bsd-2-clause
| 19,162
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
-- | Run sub-processes.
module System.Process.Run
(runCmd
,runCmd'
,callProcess
,callProcess'
,callProcessInheritStderrStdout
,createProcess'
,ProcessExitedUnsuccessfully
,Cmd(..)
)
where
import Control.Exception.Lifted
import Control.Monad (liftM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger (MonadLogger, logError)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Conduit.Process hiding (callProcess)
import Data.Foldable (forM_)
import Data.Text (Text)
import qualified Data.Text as T
import Path (Dir, Abs, Path)
import Path (toFilePath)
import Prelude -- Fix AMP warning
import System.Exit (exitWith, ExitCode (..))
import System.IO
import qualified System.Process
import System.Process.Log
import System.Process.Read
-- | Cmd holds common infos needed to running a process in most cases
data Cmd = Cmd
{ cmdDirectoryToRunIn :: Maybe (Path Abs Dir) -- ^ directory to run in
, cmdCommandToRun :: FilePath -- ^ command to run
, cmdEnvOverride :: EnvOverride
, cmdCommandLineArguments :: [String] -- ^ command line arguments
}
-- | Run the given command in the given directory, inheriting stdout and stderr.
--
-- If it exits with anything but success, prints an error
-- and then calls 'exitWith' to exit the program.
runCmd :: forall (m :: * -> *).
(MonadLogger m,MonadIO m,MonadBaseControl IO m)
=> Cmd
-> Maybe Text -- ^ optional additional error message
-> m ()
runCmd = runCmd' id
runCmd' :: forall (m :: * -> *).
(MonadLogger m,MonadIO m,MonadBaseControl IO m)
=> (CreateProcess -> CreateProcess)
-> Cmd
-> Maybe Text -- ^ optional additional error message
-> m ()
runCmd' modCP cmd@(Cmd{..}) mbErrMsg = do
result <- try (callProcess' modCP cmd)
case result of
Left (ProcessExitedUnsuccessfully _ ec) -> do
$logError $
T.pack $
concat $
[ "Exit code "
, show ec
, " while running "
, show (cmdCommandToRun : cmdCommandLineArguments)
] ++ (case cmdDirectoryToRunIn of
Nothing -> []
Just mbDir -> [" in ", toFilePath mbDir]
)
forM_ mbErrMsg $logError
liftIO (exitWith ec)
Right () -> return ()
-- | Like 'System.Process.callProcess', but takes an optional working directory and
-- environment override, and throws 'ProcessExitedUnsuccessfully' if the
-- process exits unsuccessfully.
--
-- Inherits stdout and stderr.
callProcess :: (MonadIO m, MonadLogger m) => Cmd -> m ()
callProcess = callProcess' id
-- | Like 'System.Process.callProcess', but takes an optional working directory and
-- environment override, and throws 'ProcessExitedUnsuccessfully' if the
-- process exits unsuccessfully.
--
-- Inherits stdout and stderr.
callProcess' :: (MonadIO m, MonadLogger m)
=> (CreateProcess -> CreateProcess) -> Cmd -> m ()
callProcess' modCP cmd = do
c <- liftM modCP (cmdToCreateProcess cmd)
$logCreateProcess c
liftIO $ do
(_, _, _, p) <- System.Process.createProcess c
exit_code <- waitForProcess p
case exit_code of
ExitSuccess -> return ()
ExitFailure _ -> throwIO (ProcessExitedUnsuccessfully c exit_code)
callProcessInheritStderrStdout :: (MonadIO m, MonadLogger m) => Cmd -> m ()
callProcessInheritStderrStdout cmd = do
let inheritOutput cp = cp { std_in = CreatePipe, std_out = Inherit, std_err = Inherit }
callProcess' inheritOutput cmd
-- | Like 'System.Process.Internal.createProcess_', but taking a 'Cmd'.
-- Note that the 'Handle's provided by 'UseHandle' are not closed
-- automatically.
createProcess' :: (MonadIO m, MonadLogger m)
=> String
-> (CreateProcess -> CreateProcess)
-> Cmd
-> m (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
createProcess' tag modCP cmd = do
c <- liftM modCP (cmdToCreateProcess cmd)
$logCreateProcess c
liftIO $ System.Process.createProcess_ tag c
cmdToCreateProcess :: MonadIO m => Cmd -> m CreateProcess
cmdToCreateProcess (Cmd wd cmd0 menv args) = do
cmd <- preProcess wd menv cmd0
return $ (proc cmd args) { delegate_ctlc = True
, cwd = fmap toFilePath wd
, env = envHelper menv }
|
Heather/stack
|
src/System/Process/Run.hs
|
Haskell
|
bsd-3-clause
| 4,928
|
{-# LANGUAGE Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Choose.ST
-- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu>
-- License : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability : experimental
--
-- Mutable combinations in the 'ST' monad.
module Data.Choose.ST (
-- * Combinations
STChoose,
runSTChoose,
-- * Overloaded mutable combination interface
module Data.Choose.MChoose
) where
import Control.Monad.ST
import Data.Choose.Base( Choose, STChoose, unsafeFreezeSTChoose )
import Data.Choose.MChoose
-- | A safe way to create and work with a mutable combination before returning
-- an immutable one for later perusal. This function avoids copying the
-- combination before returning it - it uses unsafeFreeze internally, but this
-- wrapper is a safe interface to that function.
runSTChoose :: (forall s. ST s (STChoose s)) -> Choose
runSTChoose c = runST (c >>= unsafeFreezeSTChoose)
{-# INLINE runSTChoose #-}
|
patperry/permutation
|
lib/Data/Choose/ST.hs
|
Haskell
|
bsd-3-clause
| 1,074
|
{-# LANGUAGE CPP #-}
module Main where
import Prelude hiding ( catch )
import Test.HUnit
import System.Exit
import System.Process ( system )
import System.IO ( stderr )
import qualified DependencyTest
import qualified MigrationsTest
import qualified FilesystemSerializeTest
import qualified FilesystemParseTest
import qualified FilesystemTest
import qualified CycleDetectionTest
import qualified StoreTest
import Control.Monad ( forM )
import Control.Exception ( finally, catch, SomeException )
import Database.HDBC ( IConnection(disconnect) )
#ifndef WithoutBackendDependencies
import qualified BackendTest
import Database.HDBC.Sqlite3 ( connectSqlite3 )
import qualified Database.HDBC.PostgreSQL as PostgreSQL
doBackendTests :: IO [Test]
doBackendTests = do
sqliteConn <- connectSqlite3 ":memory:"
pgConn <- setupPostgresDb
let backends = [ ("Sqlite", (BackendTest.tests sqliteConn) `finally`
(disconnect sqliteConn))
, ("PostgreSQL", (BackendTest.tests pgConn) `finally`
(disconnect pgConn >> teardownPostgresDb))
]
backendTests <- forM backends $ \(name, testAct) -> do
return $ (name ++ " backend tests") ~: test testAct
setupPostgresDb :: IO PostgreSQL.Connection
setupPostgresDb = do
teardownPostgresDb `catch` ignoreException
-- create database
status <- system $ "createdb " ++ tempPgDatabase
case status of
ExitSuccess -> return ()
ExitFailure _ -> error $ "Failed to create PostgreSQL database " ++ (show tempPgDatabase)
-- return test db connection
PostgreSQL.connectPostgreSQL $ "dbname=" ++ tempPgDatabase
teardownPostgresDb :: IO ()
teardownPostgresDb = do
-- create database
status <- system $ "dropdb " ++ tempPgDatabase ++ " 2>/dev/null"
case status of
ExitSuccess -> return ()
ExitFailure _ -> error $ "Failed to drop PostgreSQL database " ++ (show tempPgDatabase)
#else
doBackendTests :: IO [Test]
doBackendTests = return []
#endif
loadTests :: IO [Test]
loadTests = do
backendTests <- doBackendTests
ioTests <- sequence [ do fspTests <- FilesystemParseTest.tests
return $ "Filesystem Parsing" ~: test fspTests
, do fsTests <- FilesystemTest.tests
return $ "Filesystem general" ~: test fsTests
]
return $ concat [ backendTests
, ioTests
, DependencyTest.tests
, FilesystemSerializeTest.tests
, MigrationsTest.tests
, CycleDetectionTest.tests
, StoreTest.tests
]
tempPgDatabase :: String
tempPgDatabase = "dbmigrations_test"
ignoreException :: SomeException -> IO ()
ignoreException _ = return ()
main :: IO ()
main = do
tests <- loadTests
(testResults, _) <- runTestText (putTextToHandle stderr False) $ test tests
if errors testResults + failures testResults > 0
then exitFailure
else exitSuccess
|
nick0x01/dbmigrations
|
test/TestDriver.hs
|
Haskell
|
bsd-3-clause
| 3,047
|
module Graphics.UI.Gtk.Layout.EitherWidget where
import Control.Monad
import Data.IORef
import Graphics.UI.Gtk
import System.Glib.Types
data EitherWidget a b = EitherWidget Notebook (IORef EitherWidgetParams)
type EitherWidgetParams = Bool
instance WidgetClass (EitherWidget a b)
instance ObjectClass (EitherWidget a b)
instance GObjectClass (EitherWidget a b) where
toGObject (EitherWidget nb _) = toGObject nb
unsafeCastGObject o = EitherWidget (unsafeCastGObject o) undefined
eitherWidgetNew :: (WidgetClass a, WidgetClass b) => a -> b -> IO (EitherWidget a b)
eitherWidgetNew wL wR = do
nb <- notebookNew
_ <- notebookAppendPage nb wL ""
_ <- notebookAppendPage nb wR ""
notebookSetShowTabs nb False
params <- newIORef True
return $ EitherWidget nb params
eitherWidgetLeftActivated :: Attr (EitherWidget a b) Bool
eitherWidgetLeftActivated = newAttr getter setter
where getter (EitherWidget _ paramsR) = readIORef paramsR
setter (EitherWidget nb paramsR) v = do
params <- readIORef paramsR
when (v /= params) $ do let upd = if v then 0 else 1
notebookSetCurrentPage nb upd
writeIORef paramsR v
eitherWidgetRightActivated :: Attr (EitherWidget a b) Bool
eitherWidgetRightActivated = newAttr getter setter
where getter w = fmap not $ get w eitherWidgetLeftActivated
setter w v = set w [ eitherWidgetLeftActivated := not v ]
eitherWidgetToggle :: EitherWidget a b -> IO()
eitherWidgetToggle w = set w [ eitherWidgetLeftActivated :~ not ]
|
keera-studios/gtk-helpers
|
gtk3/src/Graphics/UI/Gtk/Layout/EitherWidget.hs
|
Haskell
|
bsd-3-clause
| 1,612
|
module E.Binary() where
import Data.Binary
import E.Type
import FrontEnd.HsSyn()
import Name.Binary()
import Support.MapBinaryInstance
import {-# SOURCE #-} Info.Binary(putInfo,getInfo)
instance Binary TVr where
put TVr { tvrIdent = eid, tvrType = e, tvrInfo = nf} = do
put eid
put e
putInfo nf
get = do
x <- get
e <- get
nf <- getInfo
return $ TVr x e nf
instance Data.Binary.Binary RuleType where
put RuleSpecialization = do
Data.Binary.putWord8 0
put RuleUser = do
Data.Binary.putWord8 1
put RuleCatalyst = do
Data.Binary.putWord8 2
get = do
h <- Data.Binary.getWord8
case h of
0 -> do
return RuleSpecialization
1 -> do
return RuleUser
2 -> do
return RuleCatalyst
_ -> fail "invalid binary data found"
instance Data.Binary.Binary Rule where
put (Rule aa ab ac ad ae af ag ah) = do
Data.Binary.put aa
putList ab
putList ac
putLEB128 $ fromIntegral ad
Data.Binary.put ae
Data.Binary.put af
Data.Binary.put ag
Data.Binary.put ah
get = do
aa <- get
ab <- getList
ac <- getList
ad <- fromIntegral `fmap` getLEB128
ae <- get
af <- get
ag <- get
ah <- get
return (Rule aa ab ac ad ae af ag ah)
instance Data.Binary.Binary ARules where
put (ARules aa ab) = do
Data.Binary.put aa
putList ab
get = do
aa <- get
ab <- getList
return (ARules aa ab)
instance (Data.Binary.Binary e,
Data.Binary.Binary t) => Data.Binary.Binary (Lit e t) where
put (LitInt aa ab) = do
Data.Binary.putWord8 0
Data.Binary.put aa
Data.Binary.put ab
put (LitCons ac ad ae af) = do
Data.Binary.putWord8 1
Data.Binary.put ac
putList ad
Data.Binary.put ae
Data.Binary.put af
get = do
h <- Data.Binary.getWord8
case h of
0 -> do
aa <- Data.Binary.get
ab <- Data.Binary.get
return (LitInt aa ab)
1 -> do
ac <- Data.Binary.get
ad <- getList
ae <- Data.Binary.get
af <- Data.Binary.get
return (LitCons ac ad ae af)
_ -> fail "invalid binary data found"
instance Data.Binary.Binary ESort where
put EStar = do
Data.Binary.putWord8 0
put EBang = do
Data.Binary.putWord8 1
put EHash = do
Data.Binary.putWord8 2
put ETuple = do
Data.Binary.putWord8 3
put EHashHash = do
Data.Binary.putWord8 4
put EStarStar = do
Data.Binary.putWord8 5
put (ESortNamed aa) = do
Data.Binary.putWord8 6
Data.Binary.put aa
get = do
h <- Data.Binary.getWord8
case h of
0 -> do
return EStar
1 -> do
return EBang
2 -> do
return EHash
3 -> do
return ETuple
4 -> do
return EHashHash
5 -> do
return EStarStar
6 -> do
aa <- Data.Binary.get
return (ESortNamed aa)
_ -> fail "invalid binary data found"
instance Data.Binary.Binary E where
put (EAp aa ab) = do
Data.Binary.putWord8 0
Data.Binary.put aa
Data.Binary.put ab
put (ELam ac ad) = do
Data.Binary.putWord8 1
Data.Binary.put ac
Data.Binary.put ad
put (EPi ae af) = do
Data.Binary.putWord8 2
Data.Binary.put ae
Data.Binary.put af
put (EVar ag) = do
Data.Binary.putWord8 3
Data.Binary.put ag
put Unknown = do
Data.Binary.putWord8 4
put (ESort ah) = do
Data.Binary.putWord8 5
Data.Binary.put ah
put (ELit ai) = do
Data.Binary.putWord8 6
Data.Binary.put ai
put (ELetRec aj ak) = do
Data.Binary.putWord8 7
putList aj
Data.Binary.put ak
put (EPrim al am an) = do
Data.Binary.putWord8 8
Data.Binary.put al
Data.Binary.put am
Data.Binary.put an
put (EError ao ap) = do
Data.Binary.putWord8 9
Data.Binary.put ao
Data.Binary.put ap
put (ECase aq ar as at au av) = do
Data.Binary.putWord8 10
Data.Binary.put aq
Data.Binary.put ar
Data.Binary.put as
putList at
Data.Binary.put au
Data.Binary.put av
get = do
h <- Data.Binary.getWord8
case h of
0 -> do
aa <- Data.Binary.get
ab <- Data.Binary.get
return (EAp aa ab)
1 -> do
ac <- Data.Binary.get
ad <- Data.Binary.get
return (ELam ac ad)
2 -> do
ae <- Data.Binary.get
af <- Data.Binary.get
return (EPi ae af)
3 -> do
ag <- Data.Binary.get
return (EVar ag)
4 -> do
return Unknown
5 -> do
ah <- Data.Binary.get
return (ESort ah)
6 -> do
ai <- Data.Binary.get
return (ELit ai)
7 -> do
aj <- getList
ak <- Data.Binary.get
return (ELetRec aj ak)
8 -> do
al <- Data.Binary.get
am <- Data.Binary.get
an <- Data.Binary.get
return (EPrim al am an)
9 -> do
ao <- Data.Binary.get
ap <- Data.Binary.get
return (EError ao ap)
10 -> do
aq <- Data.Binary.get
ar <- Data.Binary.get
as <- Data.Binary.get
at <- getList
au <- Data.Binary.get
av <- Data.Binary.get
return (ECase aq ar as at au av)
_ -> fail "invalid binary data found"
instance (Data.Binary.Binary e) => Data.Binary.Binary (Alt e) where
put (Alt aa ab) = do
Data.Binary.put aa
Data.Binary.put ab
get = do
aa <- get
ab <- get
return (Alt aa ab)
|
m-alvarez/jhc
|
src/E/Binary.hs
|
Haskell
|
mit
| 5,542
|
<?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="hu-HU">
<title>Directory List v2.3</title>
<maps>
<homeID>directorylistv2_3</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/directorylistv2_3/src/main/javahelp/help_hu_HU/helpset_hu_HU.hs
|
Haskell
|
apache-2.0
| 978
|
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.NoFrillsDecoration
-- Copyright : (c) Jan Vornberger 2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : jan.vornberger@informatik.uni-oldenburg.de
-- Stability : unstable
-- Portability : not portable
--
-- Most basic version of decoration for windows without any additional
-- modifications. In contrast to "XMonad.Layout.SimpleDecoration" this will
-- result in title bars that span the entire window instead of being only the
-- length of the window title.
--
-----------------------------------------------------------------------------
module XMonad.Layout.NoFrillsDecoration
( -- * Usage:
-- $usage
noFrillsDeco
, module XMonad.Layout.SimpleDecoration
, NoFrillsDecoration
) where
import XMonad.Layout.Decoration
import XMonad.Layout.SimpleDecoration
-- $usage
-- You can use this module with the following in your
-- @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.NoFrillsDecoration
--
-- Then edit your @layoutHook@ by adding the NoFrillsDecoration to
-- your layout:
--
-- > myL = noFrillsDeco shrinkText def (layoutHook def)
-- > main = xmonad def { layoutHook = myL }
--
-- | Add very simple decorations to windows of a layout.
noFrillsDeco :: (Eq a, Shrinker s) => s -> Theme
-> l a -> ModifiedLayout (Decoration NoFrillsDecoration s) l a
noFrillsDeco s c = decoration s c $ NFD True
data NoFrillsDecoration a = NFD Bool deriving (Show, Read)
instance Eq a => DecorationStyle NoFrillsDecoration a where
describeDeco _ = "NoFrillsDeco"
|
pjones/xmonad-test
|
vendor/xmonad-contrib/XMonad/Layout/NoFrillsDecoration.hs
|
Haskell
|
bsd-2-clause
| 1,703
|
{-# LANGUAGE TypeFamilies, TypeSynonymInstances, FlexibleContexts, FlexibleInstances, ScopedTypeVariables, Arrows, GeneralizedNewtypeDeriving, PatternSynonyms #-}
module Graphics.GPipe.Internal.PrimitiveStream where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Writer.Lazy
import Control.Monad.Trans.State.Lazy
import Prelude hiding (length, id, (.))
import Graphics.GPipe.Internal.Buffer
import Graphics.GPipe.Internal.Expr
import Graphics.GPipe.Internal.Shader
import Graphics.GPipe.Internal.Compiler
import Graphics.GPipe.Internal.PrimitiveArray
import Graphics.GPipe.Internal.Context
import Control.Category
import Control.Arrow
import Data.Monoid (Monoid(..))
import Data.IntMap.Lazy (insert)
import Data.Word
import Data.Int
import Graphics.GL.Core33
import Foreign.Marshal.Utils
import Foreign.Ptr (intPtrToPtr)
import Data.IORef
import Linear.V4
import Linear.V3
import Linear.V2
import Linear.V1
import Linear.V0
import Linear.Plucker (Plucker(..))
import Linear.Quaternion (Quaternion(..))
import Linear.Affine (Point(..))
import Data.Maybe (fromMaybe)
type DrawCallName = Int
data PrimitiveStreamData = PrimitiveStreamData DrawCallName
-- | A @'PrimitiveStream' t a @ is a stream of primitives of type @t@ where the vertices are values of type @a@. You
-- can operate a stream's vertex values using the 'Functor' instance (this will result in a shader running on the GPU).
-- You may also append 'PrimitiveStream's using the 'Monoid' instance, but if possible append the origin 'PrimitiveArray's instead, as this will create more optimized
-- draw calls.
newtype PrimitiveStream t a = PrimitiveStream [(a, (Maybe PointSize, PrimitiveStreamData))] deriving Monoid
instance Functor (PrimitiveStream t) where
fmap f (PrimitiveStream xs) = PrimitiveStream $ map (first f) xs
-- | This class constraints which buffer types can be turned into vertex values, and what type those values have.
class BufferFormat a => VertexInput a where
-- | The type the buffer value will be turned into once it becomes a vertex value.
type VertexFormat a
-- | An arrow action that turns a value from it's buffer representation to it's vertex representation. Use 'toVertex' from
-- the GPipe provided instances to operate in this arrow. Also note that this arrow needs to be able to return a value
-- lazily, so ensure you use
--
-- @proc ~pattern -> do ...@.
toVertex :: ToVertex a (VertexFormat a)
-- | The arrow type for 'toVertex'.
newtype ToVertex a b = ToVertex (Kleisli (StateT Int (Writer [Binding -> (IO VAOKey, IO ())])) a b) deriving (Category, Arrow)
-- | Create a primitive stream from a primitive array provided from the shader environment.
toPrimitiveStream :: forall os f s a p. VertexInput a => (s -> PrimitiveArray p a) -> Shader os f s (PrimitiveStream p (VertexFormat a))
toPrimitiveStream sf = Shader $ do n <- getName
uniAl <- askUniformAlignment
let sampleBuffer = makeBuffer undefined undefined uniAl :: Buffer os a
x = fst $ runWriter (evalStateT (mf $ bufBElement sampleBuffer $ BInput 0 0) 0)
doForInputArray n (map drawcall . getPrimitiveArray . sf)
return $ PrimitiveStream [(x, (Nothing, PrimitiveStreamData n))]
where
ToVertex (Kleisli mf) = toVertex :: ToVertex a (VertexFormat a)
drawcall (PrimitiveArraySimple p l a) binds = (attribs a binds, glDrawArrays (toGLtopology p) 0 (fromIntegral l))
drawcall (PrimitiveArrayIndexed p i a) binds = (attribs a binds, do
bindIndexBuffer i
glDrawElements (toGLtopology p) (fromIntegral $ indexArrayLength i) (indexType i) (intPtrToPtr $ fromIntegral $ offset i * glSizeOf (indexType i)))
drawcall (PrimitiveArrayInstanced p il l a) binds = (attribs a binds, glDrawArraysInstanced (toGLtopology p) 0 (fromIntegral l) (fromIntegral il))
drawcall (PrimitiveArrayIndexedInstanced p i il a) binds = (attribs a binds, do
bindIndexBuffer i
glDrawElementsInstanced (toGLtopology p) (fromIntegral $ indexArrayLength i) (indexType i) (intPtrToPtr $ fromIntegral $ offset i * glSizeOf (indexType i)) (fromIntegral il))
bindIndexBuffer i = do case restart i of Just x -> do glEnable GL_PRIMITIVE_RESTART
glPrimitiveRestartIndex (fromIntegral x)
Nothing -> glDisable GL_PRIMITIVE_RESTART
bname <- readIORef (iArrName i)
glBindBuffer GL_ELEMENT_ARRAY_BUFFER bname
glSizeOf GL_UNSIGNED_INT = 4
glSizeOf GL_UNSIGNED_SHORT = 2
glSizeOf GL_UNSIGNED_BYTE = 1
glSizeOf _ = error "toPrimitiveStream: Unknown indexArray type"
assignIxs :: Int -> Binding -> [Int] -> [Binding -> (IO VAOKey, IO ())] -> [(IO VAOKey, IO ())]
assignIxs n ix xxs@(x:xs) (f:fs) | x == n = f ix : assignIxs (n+1) (ix+1) xs fs
| otherwise = assignIxs (n+1) ix xxs fs
assignIxs _ _ [] _ = []
assignIxs _ _ _ _ = error "Too few attributes generated in toPrimitiveStream"
attribs a binds = first sequence $ second sequence_ $ unzip $ assignIxs 0 0 binds $ execWriter (runStateT (mf a) 0)
doForInputArray :: Int -> (s -> [[Binding] -> ((IO [VAOKey], IO ()), IO ())]) -> ShaderM s ()
doForInputArray n io = modifyRenderIO (\s -> s { inputArrayToRenderIOs = insert n io (inputArrayToRenderIOs s) } )
data InputIndices = InputIndices {
inputVertexID :: VInt,
inputInstanceID :: VInt
}
-- | Like 'fmap', but where the vertex and instance IDs are provided as arguments as well.
withInputIndices :: (a -> InputIndices -> b) -> PrimitiveStream p a -> PrimitiveStream p b
withInputIndices f = fmap (\a -> f a (InputIndices (scalarS' "gl_VertexID") (scalarS' "gl_InstanceID")))
type PointSize = VFloat
-- | Like 'fmap', but where each point's size is provided as arguments as well, and a new point size is set for each point in addition to the new vertex value.
--
-- When a 'PrimitiveStream' of 'Points' is created, all points will have the default size of 1.
withPointSize :: (a -> PointSize -> (b, PointSize)) -> PrimitiveStream Points a -> PrimitiveStream Points b
withPointSize f (PrimitiveStream xs) = PrimitiveStream $ map (\(a, (ps, d)) -> let (b, ps') = f a (fromMaybe (scalarS' "1") ps) in (b, (Just ps', d))) xs
makeVertexFx norm x f styp typ b = do
n <- get
put $ n + 1
let combOffset = bStride b * bSkipElems b + bOffset b
lift $ tell [\ix -> ( do bn <- readIORef $ bName b
return $ VAOKey bn combOffset x norm (bInstanceDiv b)
, do bn <- readIORef $ bName b
let ix' = fromIntegral ix
glEnableVertexAttribArray ix'
glBindBuffer GL_ARRAY_BUFFER bn
glVertexAttribDivisor ix' (fromIntegral $ bInstanceDiv b)
glVertexAttribPointer ix' x typ (fromBool norm) (fromIntegral $ bStride b) (intPtrToPtr $ fromIntegral combOffset))]
return (f styp $ useVInput styp n)
makeVertexFnorm = makeVertexFx True
makeVertexF = makeVertexFx False
makeVertexI x f styp typ b = do
n <- get
put $ n + 1
let combOffset = bStride b * bSkipElems b + bOffset b
lift $ tell [\ix -> ( do bn <- readIORef $ bName b
return $ VAOKey bn combOffset x False (bInstanceDiv b)
, do bn <- readIORef $ bName b
let ix' = fromIntegral ix
glEnableVertexAttribArray ix'
glBindBuffer GL_ARRAY_BUFFER bn
glVertexAttribDivisor ix' (fromIntegral $ bInstanceDiv b)
glVertexAttribIPointer ix' x typ (fromIntegral $ bStride b) (intPtrToPtr $ fromIntegral combOffset))]
return (f styp $ useVInput styp n)
-- scalars
unBnorm :: Normalized t -> t
unBnorm (Normalized a) = a
instance VertexInput (B Float) where
type VertexFormat (B Float) = VFloat
toVertex = ToVertex $ Kleisli $ makeVertexF 1 (const S) STypeFloat GL_FLOAT
instance VertexInput (Normalized (B Int32)) where
type VertexFormat (Normalized (B Int32)) = VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 1 (const S) STypeFloat GL_INT . unBnorm
instance VertexInput (Normalized (B Word32)) where
type VertexFormat (Normalized (B Word32)) = VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 1 (const S) STypeFloat GL_UNSIGNED_INT . unBnorm
instance VertexInput (B Int32) where
type VertexFormat (B Int32) = VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 1 (const S) STypeInt GL_INT
instance VertexInput (B Word32) where
type VertexFormat (B Word32) = VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 1 (const S) STypeUInt GL_UNSIGNED_INT
-- B2
instance VertexInput (B2 Float) where
type VertexFormat (B2 Float) = V2 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexF 2 vec2S (STypeVec 2) GL_FLOAT . unB2
instance VertexInput (Normalized (B2 Int32)) where
type VertexFormat (Normalized (B2 Int32)) = V2 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_INT . unB2 . unBnorm
instance VertexInput (Normalized (B2 Int16)) where
type VertexFormat (Normalized (B2 Int16)) = V2 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_SHORT . unB2 . unBnorm
instance VertexInput (Normalized (B2 Word32)) where
type VertexFormat (Normalized (B2 Word32)) = V2 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_UNSIGNED_INT . unB2 . unBnorm
instance VertexInput (Normalized (B2 Word16)) where
type VertexFormat (Normalized (B2 Word16)) = V2 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 2 vec2S (STypeVec 2) GL_UNSIGNED_SHORT . unB2 . unBnorm
instance VertexInput (B2 Int32) where
type VertexFormat (B2 Int32) = V2 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeIVec 2) GL_INT . unB2
instance VertexInput (B2 Int16) where
type VertexFormat (B2 Int16) = V2 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeIVec 2) GL_SHORT . unB2
instance VertexInput (B2 Word32) where
type VertexFormat (B2 Word32) = V2 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeUVec 2) GL_UNSIGNED_INT . unB2
instance VertexInput (B2 Word16) where
type VertexFormat (B2 Word16) = V2 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 2 vec2S (STypeUVec 2) GL_UNSIGNED_SHORT . unB2
-- B3
instance VertexInput (B3 Float) where
type VertexFormat (B3 Float) = V3 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexF 3 vec3S (STypeVec 3) GL_FLOAT . unB3
instance VertexInput (Normalized (B3 Int32)) where
type VertexFormat (Normalized (B3 Int32)) = V3 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_INT . unB3 . unBnorm
instance VertexInput (Normalized (B3 Int16)) where
type VertexFormat (Normalized (B3 Int16)) = V3 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_SHORT . unB3 . unBnorm
instance VertexInput (Normalized (B3 Int8)) where
type VertexFormat (Normalized (B3 Int8)) = V3 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_BYTE . unB3 . unBnorm
instance VertexInput (Normalized (B3 Word32)) where
type VertexFormat (Normalized (B3 Word32)) = V3 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_UNSIGNED_INT . unB3 . unBnorm
instance VertexInput (Normalized (B3 Word16)) where
type VertexFormat (Normalized (B3 Word16)) = V3 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_UNSIGNED_SHORT . unB3 . unBnorm
instance VertexInput (Normalized (B3 Word8)) where
type VertexFormat (Normalized (B3 Word8)) = V3 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 3 vec3S (STypeVec 3) GL_UNSIGNED_BYTE . unB3 . unBnorm
instance VertexInput (B3 Int32) where
type VertexFormat (B3 Int32) = V3 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeIVec 3) GL_INT . unB3
instance VertexInput (B3 Int16) where
type VertexFormat (B3 Int16) = V3 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeIVec 3) GL_SHORT . unB3
instance VertexInput (B3 Int8) where
type VertexFormat (B3 Int8) = V3 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeIVec 3) GL_BYTE . unB3
instance VertexInput (B3 Word32) where
type VertexFormat (B3 Word32) = V3 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeUVec 3) GL_UNSIGNED_INT . unB3
instance VertexInput (B3 Word16) where
type VertexFormat (B3 Word16) = V3 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeUVec 3) GL_UNSIGNED_SHORT . unB3
instance VertexInput (B3 Word8) where
type VertexFormat (B3 Word8) = V3 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 3 vec3S (STypeUVec 3) GL_UNSIGNED_BYTE . unB3
-- B4
instance VertexInput (B4 Float) where
type VertexFormat (B4 Float) = V4 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexF 4 vec4S (STypeVec 4) GL_FLOAT . unB4
instance VertexInput (Normalized (B4 Int32)) where
type VertexFormat (Normalized (B4 Int32)) = V4 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_INT . unB4 . unBnorm
instance VertexInput (Normalized (B4 Int16)) where
type VertexFormat (Normalized (B4 Int16)) = V4 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_SHORT . unB4 . unBnorm
instance VertexInput (Normalized (B4 Int8)) where
type VertexFormat (Normalized (B4 Int8)) = V4 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_BYTE . unB4 . unBnorm
instance VertexInput (Normalized (B4 Word32)) where
type VertexFormat (Normalized (B4 Word32)) = V4 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_UNSIGNED_INT . unB4 . unBnorm
instance VertexInput (Normalized (B4 Word16)) where
type VertexFormat (Normalized (B4 Word16)) = V4 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_UNSIGNED_SHORT . unB4 . unBnorm
instance VertexInput (Normalized (B4 Word8)) where
type VertexFormat (Normalized (B4 Word8)) = V4 VFloat
toVertex = ToVertex $ Kleisli $ makeVertexFnorm 4 vec4S (STypeVec 4) GL_UNSIGNED_BYTE . unB4 . unBnorm
instance VertexInput (B4 Int32) where
type VertexFormat (B4 Int32) = V4 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeIVec 4) GL_INT . unB4
instance VertexInput (B4 Int16) where
type VertexFormat (B4 Int16) = V4 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeIVec 4) GL_SHORT . unB4
instance VertexInput (B4 Int8) where
type VertexFormat (B4 Int8) = V4 VInt
toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeIVec 4) GL_BYTE . unB4
instance VertexInput (B4 Word32) where
type VertexFormat (B4 Word32) = V4 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeUVec 4) GL_UNSIGNED_INT . unB4
instance VertexInput (B4 Word16) where
type VertexFormat (B4 Word16) = V4 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeUVec 4) GL_UNSIGNED_SHORT . unB4
instance VertexInput (B4 Word8) where
type VertexFormat (B4 Word8) = V4 VWord
toVertex = ToVertex $ Kleisli $ makeVertexI 4 vec4S (STypeUVec 4) GL_UNSIGNED_BYTE . unB4
instance VertexInput () where
type VertexFormat () = ()
toVertex = arr (const ())
instance (VertexInput a, VertexInput b) => VertexInput (a,b) where
type VertexFormat (a,b) = (VertexFormat a, VertexFormat b)
toVertex = proc ~(a,b) -> do a' <- toVertex -< a
b' <- toVertex -< b
returnA -< (a', b')
instance (VertexInput a, VertexInput b, VertexInput c) => VertexInput (a,b,c) where
type VertexFormat (a,b,c) = (VertexFormat a, VertexFormat b, VertexFormat c)
toVertex = proc ~(a,b,c) -> do a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
returnA -< (a', b', c')
instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d) => VertexInput (a,b,c,d) where
type VertexFormat (a,b,c,d) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d)
toVertex = proc ~(a,b,c,d) -> do a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
d' <- toVertex -< d
returnA -< (a', b', c', d')
instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d, VertexInput e) => VertexInput (a,b,c,d,e) where
type VertexFormat (a,b,c,d,e) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d, VertexFormat e)
toVertex = proc ~(a,b,c,d,e) -> do a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
d' <- toVertex -< d
e' <- toVertex -< e
returnA -< (a', b', c', d', e')
instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d, VertexInput e, VertexInput f) => VertexInput (a,b,c,d,e,f) where
type VertexFormat (a,b,c,d,e,f) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d, VertexFormat e, VertexFormat f)
toVertex = proc ~(a,b,c,d,e,f) -> do a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
d' <- toVertex -< d
e' <- toVertex -< e
f' <- toVertex -< f
returnA -< (a', b', c', d', e', f')
instance (VertexInput a, VertexInput b, VertexInput c, VertexInput d, VertexInput e, VertexInput f, VertexInput g) => VertexInput (a,b,c,d,e,f,g) where
type VertexFormat (a,b,c,d,e,f,g) = (VertexFormat a, VertexFormat b, VertexFormat c, VertexFormat d, VertexFormat e, VertexFormat f, VertexFormat g)
toVertex = proc ~(a,b,c,d,e,f,g) -> do a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
d' <- toVertex -< d
e' <- toVertex -< e
f' <- toVertex -< f
g' <- toVertex -< g
returnA -< (a', b', c', d', e', f', g')
instance VertexInput a => VertexInput (V0 a) where
type VertexFormat (V0 a) = V0 (VertexFormat a)
toVertex = arr (const V0)
instance VertexInput a => VertexInput (V1 a) where
type VertexFormat (V1 a) = V1 (VertexFormat a)
toVertex = proc ~(V1 a) -> do a' <- toVertex -< a
returnA -< V1 a'
instance VertexInput a => VertexInput (V2 a) where
type VertexFormat (V2 a) = V2 (VertexFormat a)
toVertex = proc ~(V2 a b) -> do a' <- toVertex -< a
b' <- toVertex -< b
returnA -< V2 a' b'
instance VertexInput a => VertexInput (V3 a) where
type VertexFormat (V3 a) = V3 (VertexFormat a)
toVertex = proc ~(V3 a b c) -> do a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
returnA -< V3 a' b' c'
instance VertexInput a => VertexInput (V4 a) where
type VertexFormat (V4 a) = V4 (VertexFormat a)
toVertex = proc ~(V4 a b c d) -> do a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
d' <- toVertex -< d
returnA -< V4 a' b' c' d'
instance VertexInput a => VertexInput (Quaternion a) where
type VertexFormat (Quaternion a) = Quaternion (VertexFormat a)
toVertex = proc ~(Quaternion a v) -> do
a' <- toVertex -< a
v' <- toVertex -< v
returnA -< Quaternion a' v'
instance (VertexInput (f a), VertexInput a, HostFormat (f a) ~ f (HostFormat a), VertexFormat (f a) ~ f (VertexFormat a)) => VertexInput (Point f a) where
type VertexFormat (Point f a) = Point f (VertexFormat a)
toVertex = proc ~(P a) -> do
a' <- toVertex -< a
returnA -< P a'
instance VertexInput a => VertexInput (Plucker a) where
type VertexFormat (Plucker a) = Plucker (VertexFormat a)
toVertex = proc ~(Plucker a b c d e f) -> do
a' <- toVertex -< a
b' <- toVertex -< b
c' <- toVertex -< c
d' <- toVertex -< d
e' <- toVertex -< e
f' <- toVertex -< f
returnA -< Plucker a' b' c' d' e' f'
|
Teaspot-Studio/GPipe-Core
|
src/Graphics/GPipe/Internal/PrimitiveStream.hs
|
Haskell
|
mit
| 22,384
|
module ASPico.Handler.Root.Affiliate
( ApiAffiliate
, serverAffiliate
) where
import ASPico.Prelude hiding (product)
import Database.Persist.Sql (Entity(..), fromSqlKey)
import Servant ((:>), FormUrlEncoded, JSON, Post, ReqBody, ServerT)
import ASPico.Envelope (Envelope, returnSuccess)
import ASPico.Error (AppErr)
import ASPico.Form (AffiliateForm(..), AffiliateResp(..))
import ASPico.Monad (MonadASPicoDb, dbCreateAffiliate)
type ApiAffiliate = "affiliate" :> ReqBody '[JSON, FormUrlEncoded] AffiliateForm :> Post '[JSON, FormUrlEncoded] (Envelope AffiliateResp)
serverAffiliate
:: (MonadError AppErr m, MonadASPicoDb m)
=> ServerT ApiAffiliate m
serverAffiliate = affUrl
affUrl
:: (MonadError AppErr m, MonadASPicoDb m)
=> AffiliateForm -> m (Envelope AffiliateResp)
affUrl form = do
Entity k _ <- dbCreateAffiliate form
returnSuccess . AffiliateResp . tshow . fromSqlKey $ k
|
arowM/ASPico
|
src/ASPico/Handler/Root/Affiliate.hs
|
Haskell
|
mit
| 905
|
module StackLang where
import Prelude hiding (EQ,If)
-- Grammar for StackLang:
--
-- num ::= (any number)
-- bool ::= `true` | `false`
-- prog ::= cmd*
-- cmd ::= int push a number on the stack
-- | bool push a boolean on the stack
-- | `add` add the top two numbers the stack
-- | `eq` check whether the top two elements are equal
-- | `if` prog prog if the value on the top
-- 1. Encode the above grammar as a set of Haskell data types
type Num = Int
type Prog = [Cmd]
data Cmd = LitI Int
| LitB Bool
| Add
| EQ
| If Prog Prog
deriving (Eq,Show)
-- 2. Write a Haskell value that represents a StackLang program that:
-- * checks whether 3 and 4 are equal
-- * if so, returns the result of adding 5 and 6
-- * if not, returns the value false
myProg :: Prog
myProg = [LitI 3, LitI 4, EQ, If [LitI 5, LitI 6, Add] [LitB False]]
-- 3. Write a Haskell function that takes two arguments x and y
-- and generates a StackLang program that adds both x and y to
-- the number on the top of the stack
genAdd2 :: Int -> Int -> Prog
genAdd2 x y = [LitI x, LitI y, Add, Add]
-- 4. Write a Haskell function that takes a list of integers and
-- generates a StackLang program that sums them all up.
genSum :: [Int] -> Prog
genSum [] = [LitI 0]
genSum (x:xs) = genSum xs ++ [LitI x, Add]
|
siphayne/CS381
|
scratch/StackLang.hs
|
Haskell
|
mit
| 1,454
|
module Utils where
import Import hiding (group)
import Data.Char (isSpace)
import Data.Conduit.Binary (sinkLbs)
import qualified Data.ByteString.Lazy.Char8 as LB8
import qualified Data.HashMap.Strict as M
import qualified Data.List as L
-- import Data.Hashable
stringFields :: Int -> String -> Either String [String]
stringFields n s
| length xs == n = Right xs
| otherwise = Left err
where
xs = stringFields' s
err = s ++ " does not have " ++ show n ++ " fields!"
stringFields' :: String -> [String]
stringFields' s = snipSpaces <$> (splitOn ',' s)
splitOn :: (Eq a) => a -> [a] -> [[a]]
splitOn _ [] = [[]]
splitOn x (y:ys)
| x == y = [] : splitOn x ys
| otherwise = (y:zs) : zss where zs:zss = splitOn x ys
snipSpaces :: String -> String
snipSpaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace
fileLines :: FileInfo -> IO [String]
fileLines file = do
bytes <- runResourceT $ fileSource file $$ sinkLbs
return (lines . LB8.unpack $ bytes)
textString :: (IsString a) => Text -> a
textString = fromString . unpack
group :: (Eq k, Hashable k) => [(k, v)] -> M.HashMap k [v]
group = groupBase M.empty
groupBase :: (Eq k, Hashable k) => M.HashMap k [v] -> [(k, v)] -> M.HashMap k [v]
groupBase = L.foldl' (\m (k, v) -> inserts k v m)
groupList :: (Eq k, Hashable k) => [(k, v)] -> [(k, [v])]
groupList = M.toList . group
groupBy :: (Eq k, Hashable k) => (a -> k) -> [a] -> M.HashMap k [a]
groupBy f = L.foldl' (\m x -> inserts (f x) x m) M.empty
inserts :: (Eq k, Hashable k) => k -> v -> M.HashMap k [v] -> M.HashMap k [v]
inserts k v m = M.insert k (v : M.lookupDefault [] k m) m
|
ranjitjhala/gradr
|
Utils.hs
|
Haskell
|
mit
| 1,752
|
-- | Specification for the exercises of Chapter 6.
module Chapter06Spec where
import qualified Chapter06 as C6
import Data.List (sort)
import Data.Proxy
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.QuickCheck (Arbitrary (..), Property, property, (.&.),
(===), (==>))
checkEquivalence :: (Arbitrary a, Show a, Show b, Eq b)
=> Proxy a -> (a -> b) -> (a -> b) -> Property
checkEquivalence _ f g = property $ \x -> f x === g x
newtype IncreasingList a = IL { incList :: [a] } deriving (Eq, Show)
newtype NonEmptyList a = NEL { list :: [a] } deriving (Eq, Show)
instance (Ord a, Arbitrary a) => Arbitrary (IncreasingList a) where
arbitrary = IL . sort <$> arbitrary
instance (Arbitrary a) => Arbitrary (NonEmptyList a) where
arbitrary = do
x <- arbitrary
xs <- arbitrary
return $ NEL (x:xs)
checkIndex :: Int -> Property
checkIndex i = checkEquivalence (Proxy :: Proxy (NonEmptyList Double))
(apply (!!) i) (apply (C6.!!) i)
where apply f j (NEL xs) = f xs j'
where j' = (abs j) `min` (length xs - 1)
type TwoIncreasingLists = (IncreasingList Double, IncreasingList Double)
spec :: Spec
spec = do
describe "Exercise 1: define a function that" $ do
describe "returns true iff all logical values in a list are true" $ do
it "returns True for the empty list" $ do
C6.and ([]:: [Bool]) `shouldBe` True
it "returns True if only True is in the list" $ do
C6.and [True] `shouldBe` True
it "returns False if only False is in the list" $ do
C6.and [False] `shouldBe` False
it "returns False if any value is False" $ do
C6.and [True, False, False] `shouldBe` False
C6.and [False, True, True] `shouldBe` False
it "returns True if all values are True" $ do
C6.and [True, True, True ] `shouldBe` True
it "behaves equivalent to and" $
checkEquivalence (Proxy :: Proxy [Bool]) and C6.and
describe "concatenates a list of lists" $ do
it "returns empty list for the empty list" $ do
C6.concat ([] :: [[Int]]) `shouldBe` []
it "returns the list for a list of only one list" $ do
C6.concat ([[1,2,3]] :: [[Int]]) `shouldBe` [1,2,3]
it "returns the concatenation of the list in the list" $ do
C6.concat ([[1,2,3], [4,5,6], [7,8,9]] :: [[Int]]) `shouldBe` [1,2,3,4,5,6,7,8,9]
it "behaves equivalent to concat" $
checkEquivalence (Proxy :: Proxy [String]) concat C6.concat
describe "produces a list with n identical elements" $ do
it "returns empty list for n < 0" $ do
C6.replicate 0 True `shouldBe` []
C6.replicate 0 'a' `shouldBe` []
C6.replicate (-10::Int) True `shouldBe` []
it "returns a list with 1 element for n = 1" $ do
C6.replicate 1 13 `shouldBe` [13]
it "returns a list with n times the same element" $ do
C6.replicate 3 'a' `shouldBe` "aaa"
C6.replicate 2 (13::Int) `shouldBe` [13,13]
it "behaves equivalent to replicate" $ property $ \i ->
checkEquivalence (Proxy :: Proxy Char) (replicate i) (C6.replicate i)
describe "selects the nth element of a list" $ do
it "returns the element if n=0 and there is only one element" $ do
['a'] C6.!! 0 `shouldBe` 'a'
it "returns the element if nth element" $ do
"abcd" C6.!! 2 `shouldBe` 'c'
it "behaves equivalent to !!" $ property $ checkIndex
describe "decides if an element is in a list" $ do
it "returns False if the list is empty" $ do
C6.elem 'a' [] `shouldBe` False
it "returns True if the element is in the list" $ do
C6.elem 'a' "dcba" `shouldBe` True
it "returns False if the element is not in the list" $ do
C6.elem 'e' "dcba" `shouldBe` False
it "behaves equivalent to elem" $ property $ \str ->
checkEquivalence (Proxy :: Proxy [String]) (str `elem`) (str `C6.elem`)
describe "Exercise 2: define a recursive function that" $ do
describe "merges two sorted lists of values to give a single sorted list" $ do
it "returns the empty list if both lists are empty" $ do
C6.merge ([]::[Int]) ([]::[Int]) `shouldBe` []
it "returns the other list if one of both lists is empty" $ do
C6.merge "foo" "" `shouldBe` "foo"
C6.merge "" "foo" `shouldBe` "foo"
it "merges the two lists" $ do
C6.merge "foo" "abr" `shouldBe` "abfoor"
it "behaves equivalent to sort" $
checkEquivalence (Proxy :: Proxy TwoIncreasingLists)
(\(xs, ys) -> C6.merge (incList xs) (incList ys))
(\(xs, ys) -> sort (incList xs ++ incList ys))
describe "Exercise 3" $ do
it "returns the empty list if the list is empty" $ do
C6.msort ([]::[Int]) `shouldBe` []
it "returns the list if the has length 1" $ do
C6.msort "a" `shouldBe` "a"
it "returns the sorted list" $ do
C6.msort "the quick brown fox jumps over the lazy dog" `shouldBe` " abcdeeefghhijklmnoooopqrrsttuuvwxyz"
it "behaves equivalent to sort" $ do
checkEquivalence (Proxy :: Proxy [[Int]]) sort C6.msort
|
EindhovenHaskellMeetup/meetup
|
courses/programming-in-haskell/pih-exercises/test/Chapter06Spec.hs
|
Haskell
|
mit
| 5,372
|
module ProjectEuler.Problem004 (solve) where
isPalindrome :: Integer -> Bool
isPalindrome n = reverse xs == xs
where
xs = show n
nDigitIntegers :: Integer -> [Integer]
nDigitIntegers n = [10^(n-1)..(10^n)-1]
solve :: Integer -> Integer
solve n = maximum $ filter isPalindrome xs
where
xs = [a * b | a <- ys, b <- ys]
ys = nDigitIntegers n
|
hachibu/project-euler
|
src/ProjectEuler/Problem004.hs
|
Haskell
|
mit
| 358
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | This module introduces functions that allow to run action in parallel with logging.
module System.Wlog.Concurrent
( WaitingDelta (..)
, CanLogInParallel
, logWarningLongAction
, logWarningWaitOnce
, logWarningWaitLinear
, logWarningWaitInf
) where
import Universum
import Control.Concurrent.Async.Lifted (withAsyncWithUnmask)
import Control.Monad.Trans.Control (MonadBaseControl)
import Fmt ((+|), (+||), (|+), (||+))
import GHC.Real ((%))
import Time (RatioNat, Second, Time, sec, threadDelay, timeMul, (+:+))
import System.Wlog.CanLog (WithLoggerIO, logWarning)
-- | Data type to represent waiting strategy for printing warnings
-- if action take too much time.
data WaitingDelta
-- | wait s seconds and stop execution
= WaitOnce (Time Second)
-- | wait s, s * 2, s * 3 , s * 4 , ... seconds
| WaitLinear (Time Second)
-- | wait m, m * q, m * q^2, m * q^3, ... microseconds
| WaitGeometric (Time Second) RatioNat
deriving (Show)
-- | Constraint for something that can be logged in parallel with other action.
type CanLogInParallel m = (MonadBaseControl IO m, WithLoggerIO m)
-- | Run action and print warning if it takes more time than expected.
logWarningLongAction :: forall m a . CanLogInParallel m
=> (Text -> m ()) -> WaitingDelta -> Text -> m a -> m a
logWarningLongAction logFunc delta actionTag action =
-- Previous implementation was
--
-- bracket (fork $ waitAndWarn delta) killThread (const action)
--
-- but this has a subtle problem: 'killThread' can be interrupted even
-- when exceptions are masked, so it's possible that the forked thread is
-- left running, polluting the logs with misinformation.
--
-- 'withAsync' is assumed to take care of this, and indeed it does for
-- 'Production's implementation, which uses the definition from the async
-- package: 'uninterruptibleCancel' is used to kill the thread.
--
-- thinking even more about it, unmasking auxilary thread is crucial if
-- this function is going to be called under 'mask'.
withAsyncWithUnmask (\unmask -> unmask $ waitAndWarn delta) (const action)
where
printWarning :: Time Second -> m ()
printWarning t = logFunc $ "Action `"+|actionTag|+"` took more than "+||t||+""
waitAndWarn :: WaitingDelta -> m ()
waitAndWarn (WaitOnce s) = delayAndPrint s s
waitAndWarn (WaitLinear s) =
let waitLoop :: Time Second -> m ()
waitLoop acc = do
delayAndPrint s acc
waitLoop (acc +:+ s)
in waitLoop s
waitAndWarn (WaitGeometric ms k) =
let waitLoop :: Time Second -> Time Second -> m ()
waitLoop acc delayT = do
let newAcc = acc +:+ delayT
let newDelayT = k `timeMul` delayT
delayAndPrint delayT newAcc
waitLoop newAcc newDelayT
in waitLoop (sec 0) ms
delayAndPrint :: Time Second -> Time Second -> m ()
delayAndPrint delayT printT = do
threadDelay delayT
printWarning printT
{- Helper functions to avoid dealing with data type -}
-- | Specialization of 'logWarningLongAction' with 'WaitOnce'.
logWarningWaitOnce :: CanLogInParallel m => Time Second -> Text -> m a -> m a
logWarningWaitOnce = logWarningLongAction logWarning . WaitOnce
-- | Specialization of 'logWarningLongAction' with 'WaiLinear'.
logWarningWaitLinear :: CanLogInParallel m => Time Second -> Text -> m a -> m a
logWarningWaitLinear = logWarningLongAction logWarning . WaitLinear
-- | Specialization of 'logWarningLongAction' with 'WaitGeometric'
-- with parameter @1.3@. Accepts 'Second'.
logWarningWaitInf :: CanLogInParallel m => Time Second -> Text -> m a -> m a
logWarningWaitInf = logWarningLongAction logWarning
. (`WaitGeometric` (13 % 10))
|
serokell/log-warper
|
src/System/Wlog/Concurrent.hs
|
Haskell
|
mit
| 4,062
|
{-# htermination negate :: Float -> Float #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_negate_3.hs
|
Haskell
|
mit
| 46
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module SchoolOfHaskell.Scheduler.API where
import Control.Applicative ((<$>), (<*>))
import Control.Lens (makeLenses)
import Data.Aeson (ToJSON(..), FromJSON(..))
import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier)
import Data.Data (Data)
import Data.Text (Text)
import Data.Typeable (Typeable)
import Data.UUID.Types (UUID)
import qualified Data.UUID.Types as UUID
newtype ContainerSpec =
ContainerSpec {_csImageName :: Text}
deriving (Eq, Show, Data, Typeable)
newtype ContainerReceipt =
ContainerReceipt {_crID :: UUID}
deriving (Eq, Data, Typeable)
instance Show ContainerReceipt where
show = show . _crID
newtype ContainerId =
ContainerId {_ciID :: Text}
deriving (Eq, Show, Ord, Data, Typeable)
data ContainerDetail =
ContainerDetail {_cdID :: Text
,_cdAddress :: Maybe (Text, PortMappings)
,_cdStatus :: Maybe Text}
deriving (Eq, Show, Data, Typeable)
instance ToJSON UUID where
toJSON = toJSON . UUID.toString
instance FromJSON UUID where
parseJSON val = do
str <- parseJSON val
case UUID.fromString str of
Nothing -> fail "Failed to parse UUID from JSON"
Just x -> return x
newtype PortMappings = PortMappings [(Int,Int)]
deriving (Eq, Show, Data, Typeable, ToJSON, FromJSON)
------------------------------------------------------------------------------
-- Constants
-- | Receipt used for local development.
devReceipt :: ContainerReceipt
devReceipt = ContainerReceipt (UUID.fromWords 0 0 0 0)
------------------------------------------------------------------------------
-- Lenses and aeson instances
$(let opts n = defaultOptions { fieldLabelModifier = drop n } in
concat <$> mapM (\(n, x) -> (++) <$> makeLenses x <*> deriveJSON (opts n) x)
[ (3, ''ContainerSpec)
, (3, ''ContainerReceipt)
, (3, ''ContainerId)
, (3, ''ContainerDetail)
])
|
fpco/schoolofhaskell
|
soh-scheduler-api/src/SchoolOfHaskell/Scheduler/API.hs
|
Haskell
|
mit
| 2,070
|
length' [] = 0
length' (x:xs) = 1 + (length' xs)
append' [] = id
append' (x:xs) = (x:).append' xs
-- A trivial way
reverse' [] = []
reverse' (x:xs) = (reverse' xs) ++ [x]
reverse2 = rev [] where
rev a [] = a
rev a (x:xs) = rev (x:a) xs
fix f = f (fix f)
reverse3 = fix (\ f a x -> case x of
[] -> a
(x:xs) -> f (x:a)xs) []
concat' [] = []
concat' (x:xs) = x : concat' xs
intersperse _ ys | length ys < 2 = ys
intersperse x (y:ys) = y : x : intersperse x ys
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x, y) : zip' xs ys
unzip' [] = ([], [])
unzip' ((x,y):l) = (x:l1, y:l2) where
(l1, l2) = unzip l
zipwith f [] _ = []
zipwith f _ [] = []
zipwith f (x:xs) (y:ys) = f x y : zipwith f xs ys
|
MaKToff/SPbSU_Homeworks
|
Semester 3/Classwork/cw01.hs
|
Haskell
|
mit
| 760
|
szachy is xD
mialo byc warcaby xD
w erlangu zrobic strange sort itp.. wszysstko to co w haskelu
|
RAFIRAF/HASKELL
|
CHESS2016.hs
|
Haskell
|
mit
| 97
|
{-
******************************************************************************
* JSHOP *
* *
* Module: ParseMonad *
* Purpose: Monad for scanning and parsing *
* Authors: Nick Brunt, Henrik Nilsson *
* *
* Based on the HMTC equivalent *
* Copyright (c) Henrik Nilsson, 2006 - 2011 *
* http://www.cs.nott.ac.uk/~nhn/ *
* *
* Revisions for JavaScript *
* Copyright (c) Nick Brunt, 2011 - 2012 *
* *
******************************************************************************
-}
module ParseMonad where
-- Standard library imports
import Control.Monad.Identity
import Control.Monad.Error
import Control.Monad.State
-- JSHOP module imports
import Token
--import Lexer
data LexerMode
= Normal
| InComment
| InRegex
deriving Show
data LexerState
= LS {rest :: String,
lineno :: Int,
mode :: LexerMode,
tr :: [String],
nl :: Bool,
rest2 :: String,
expectRegex :: Bool,
lastToken :: (Maybe Token)}
deriving Show
startState str
= LS {rest = str,
lineno = 1,
mode = Normal,
tr = [],
nl = False,
rest2 = "",
expectRegex = False,
lastToken = Nothing}
type P = StateT LexerState (ErrorT String Identity)
getLineNo :: P Int
getLineNo = do
s <- get
return (lineno s)
{-
-- | Monad for scanning and parsing.
-- The scanner and parser are both monadic, following the design outlined
-- in the Happy documentation on monadic parsers. The parse monad P
-- is built on top of the diagnostics monad D, additionally keeping track
-- of the input and current source code position, and exploiting that
-- the source code position is readily available to avoid having to pass
-- the position as an explicit argument.
module ParseMonad (
-- The parse monad
P (..), -- Not abstract. Instances: Monad.
unP, -- :: P a -> (Int -> Int -> String -> D a)
emitInfoP, -- :: String -> P ()
emitWngP, -- :: String -> P ()
emitErrP, -- :: String -> P ()
failP, -- :: String -> P a
getSrcPosP, -- :: P SrcPos
runP -- :: String -> P a -> D a
) where
-- JSHOP module imports
import SrcPos
import Diagnostics
newtype P a = P (Int -> Int -> String -> D a)
unP :: P a -> (Int -> Int -> String -> D a)
unP (P x) = x
instance Monad P where
return a = P (\_ _ _ -> return a)
p >>= f = P (\l c s -> unP p l c s >>= \a -> unP (f a) l c s)
-- Liftings of useful computations from the underlying D monad, taking
-- advantage of the fact that source code positions are available.
-- | Emits an information message.
emitInfoP :: String -> P ()
emitInfoP msg = P (\l c _ -> emitInfoD (SrcPos l c) msg)
-- | Emits a warning message.
emitWngP :: String -> P ()
emitWngP msg = P (\l c _ -> emitWngD (SrcPos l c) msg)
-- | Emits an error message.
emitErrP :: String -> P ()
emitErrP msg = P (\l c _ -> emitErrD (SrcPos l c) msg)
-- | Emits an error message and fails.
failP :: String -> P a
failP msg = P (\l c _ -> failD (SrcPos l c) msg)
-- | Gets the current source code position.
getSrcPosP :: P SrcPos
getSrcPosP = P (\l c _ -> return (SrcPos l c))
-- | Runs parser (and scanner), yielding a result in the diagnostics monad D.
runP :: P a -> String -> D a
runP p s = unP p 1 1 s
-}
|
nbrunt/JSHOP
|
src/old/ver2/ParseMonad.hs
|
Haskell
|
mit
| 4,096
|
-----------------------------------------------------------------------------
--
-- Module : Topology
-- Copyright :
-- License : AllRightsReserved
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module Topology (
cycles
) where
import Prelude hiding (cycle, elem)
import Data.Bits (bit, xor)
import Data.List ((\\))
import Data.Collections (fromList, elem)
import Data.Cycle (Cycle)
import Util (headMaybe, cshiftL, log2)
type GenFunc = Int -> Int
generate :: Eq a => (a -> a) -> [a] -> [a]
generate f ls@(l:_) =
if new `elem` ls then ls else generate f (new : ls)
where new = f l
generate _ [] = error "Must provide init value for generate"
cycle :: Int -> GenFunc -> [Cycle Int]
cycle n f = map fromList $ step [] 0
where allNums = [0 .. 2 ^ n - 1]
step res init = case findInit of
Nothing -> res'
Just init' -> step res' init'
where new = generate f [init]
res' = new : res
findInit = headMaybe $ allNums \\ concat res'
genFuncs :: Int -> [GenFunc]
genFuncs pow = map (genFunc pow) [1 .. n]
where n = log2 pow
genFunc :: Int -> Int -> GenFunc
genFunc pow i = cshiftL pow i . xor (if odd i then f else l)
where f = 1
l = bit (pow - 1)
cycles :: Int -> [Cycle Int]
cycles pow = concatMap (cycle pow) $ genFuncs pow
|
uvNikita/TopologyRouting
|
src/Topology.hs
|
Haskell
|
mit
| 1,494
|
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-
Copyright 2020 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Internal.Exports
( -- * Entry points
Program,
drawingOf,
animationOf,
activityOf,
debugActivityOf,
groupActivityOf,
-- * Pictures
Picture,
codeWorldLogo,
circle,
solidCircle,
thickCircle,
rectangle,
solidRectangle,
thickRectangle,
pictures,
(&),
coordinatePlane,
blank,
colored,
coloured,
translated,
scaled,
dilated,
rotated,
reflected,
clipped,
polyline,
thickPolyline,
polygon,
thickPolygon,
solidPolygon,
curve,
thickCurve,
closedCurve,
thickClosedCurve,
solidClosedCurve,
arc,
sector,
thickArc,
lettering,
styledLettering,
Font (..),
TextStyle (..),
-- * Colors
Color,
Colour,
pattern RGBA,
pattern RGB,
pattern HSL,
black,
white,
red,
green,
blue,
yellow,
orange,
brown,
pink,
purple,
gray,
grey,
mixed,
light,
dark,
bright,
dull,
translucent,
assortedColors,
lighter,
darker,
brighter,
duller,
-- * Points and vectors
Point,
translatedPoint,
rotatedPoint,
reflectedPoint,
scaledPoint,
dilatedPoint,
Vector,
vectorLength,
vectorDirection,
vectorSum,
vectorDifference,
scaledVector,
rotatedVector,
dotProduct,
-- * Events
Event (..),
-- * Debugging
traced,
)
where
import Internal.CodeWorld
import Internal.Color
import Internal.Event
import Internal.Num
import Internal.Picture
import Internal.Prelude
import Internal.Text
import "base" Prelude (IO)
|
google/codeworld
|
codeworld-base/src/Internal/Exports.hs
|
Haskell
|
apache-2.0
| 2,352
|
{- Primitive.hs
- Primitive shapes.
-
- Timothy A. Chagnon
- CS 636 - Spring 2009
-}
module Primitive where
import Math
import Ray
import Material
data Primitive = Sphere RealT Vec3f -- Sphere defined by radius, center
| Plane Vec3f Vec3f Vec3f -- Plane defined by 3 points
deriving (Show, Eq)
-- Sphere centered at the origin
sphere :: RealT -> Primitive
sphere r = Sphere r zeroVec3f
-- Intersect a ray with primitives
intersectP :: Ray -> Material -> Primitive -> [Intersection]
intersectP (Ray o d) mat (Sphere r ctr) =
let b = 2 * (d `dot` (o-ctr)) in
let c = (magSq (o-ctr)) - r*r in
let discrim = b*b - 4*c in
let normal t = (1/r) `svMul` ((o-ctr) + (t `svMul` d)) in
if discrim < 0
then []
else
let t0 = (-b - (sqrt discrim))/2 in
let t1 = (-b + (sqrt discrim))/2 in
if t0 < 0
then if t1 < 0
then []
else [(Inx t1 (normal t1) mat)]
else [(Inx t0 (normal t0) mat), (Inx t1 (normal t1) mat)]
intersectP (Ray r d) mat (Plane a b c) =
let amb = a-b in
let amc = a-c in
let amr = a-r in
let mtxA = colMat3f amb amc d in
let detA = detMat3f mtxA in
let beta = (detMat3f (colMat3f amr amc d)) / detA in
let gamma = (detMat3f (colMat3f amb amr d)) / detA in
let alpha = 1 - beta - gamma in
let t = (detMat3f (colMat3f amb amc amr)) / detA in
let normal = norm (amb `cross` amc) in
if t > 0
then [Inx t normal mat]
else []
-- Transform Primitives
transformP :: Mat4f -> Primitive -> Primitive
transformP t (Sphere r c) =
let r' = r * (t!|0!.0) in
let c' = transformPt t c in
Sphere r' c'
transformP t (Plane a b c) =
let a' = transformPt t a in
let b' = transformPt t b in
let c' = transformPt t c in
Plane a' b' c'
|
tchagnon/cs636-raytracer
|
a5/Primitive.hs
|
Haskell
|
apache-2.0
| 2,060
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
#include "settings.h"
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings
( hamletFile
, cassiusFile
, juliusFile
, widgetFile
, connStr
, ConnectionPool
, withConnectionPool
, runConnectionPool
, approot
, staticroot
, staticdir
, previewImage
, bugImage
, spinnerImage
) where
import qualified Text.Hamlet as H
import qualified Text.Cassius as H
import qualified Text.Julius as H
import Language.Haskell.TH.Syntax
import Database.Persist.Sqlite
import Yesod (MonadInvertIO, addWidget, addCassius, addJulius)
import Data.Monoid (mempty)
import System.Directory (doesFileExist)
-- | The base URL for your application. This will usually be different for
-- development and production. Yesod automatically constructs URLs for you,
-- so this value must be accurate to create valid links.
approot :: String
#ifdef PRODUCTION
approot = "http://funkyfotoapp.com"
#else
approot = "http://localhost:3000"
#endif
-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticdir :: FilePath
staticdir = "static"
-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Foundation.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Foundation.hs
staticroot :: String
staticroot = approot ++ "/static"
-- Location of image files to use for effect preivews.
--
previewImage :: FilePath
previewImage = "original.jpg"
bugImage :: FilePath
bugImage = "bug.jpg"
spinnerImage :: FilePath
spinnerImage = "spinner.gif"
-- | The database connection string. The meaning of this string is backend-
-- specific.
connStr :: String
#ifdef PRODUCTION
connStr = "production.db3"
#else
connStr = "debug.db3"
#endif
-- | Your application will keep a connection pool and take connections from
-- there as necessary instead of continually creating new connections. This
-- value gives the maximum number of connections to be open at a given time.
-- If your application requests a connection when all connections are in
-- use, that request will fail. Try to choose a number that will work well
-- with the system resources available to you while providing enough
-- connections for your expected load.
--
-- Also, connections are returned to the pool as quickly as possible by
-- Yesod to avoid resource exhaustion. A connection is only considered in
-- use while within a call to runDB.
connectionCount :: Int
connectionCount = 10
-- The rest of this file contains settings which rarely need changing by a
-- user.
-- The following three functions are used for calling HTML, CSS and
-- Javascript templates from your Haskell code. During development,
-- the "Debug" versions of these functions are used so that changes to
-- the templates are immediately reflected in an already running
-- application. When making a production compile, the non-debug version
-- is used for increased performance.
--
-- You can see an example of how to call these functions in Handler/Root.hs
--
-- Note: due to polymorphic Hamlet templates, hamletFileDebug is no longer
-- used; to get the same auto-loading effect, it is recommended that you
-- use the devel server.
toHamletFile, toCassiusFile, toJuliusFile :: String -> FilePath
toHamletFile x = "hamlet/" ++ x ++ ".hamlet"
toCassiusFile x = "cassius/" ++ x ++ ".cassius"
toJuliusFile x = "julius/" ++ x ++ ".julius"
hamletFile :: FilePath -> Q Exp
hamletFile = H.hamletFile . toHamletFile
cassiusFile :: FilePath -> Q Exp
#ifdef PRODUCTION
cassiusFile = H.cassiusFile . toCassiusFile
#else
cassiusFile = H.cassiusFileDebug . toCassiusFile
#endif
juliusFile :: FilePath -> Q Exp
#ifdef PRODUCTION
juliusFile = H.juliusFile . toJuliusFile
#else
juliusFile = H.juliusFileDebug . toJuliusFile
#endif
widgetFile :: FilePath -> Q Exp
widgetFile x = do
let h = unlessExists toHamletFile hamletFile
let c = unlessExists toCassiusFile cassiusFile
let j = unlessExists toJuliusFile juliusFile
[|addWidget $h >> addCassius $c >> addJulius $j|]
where
unlessExists tofn f = do
e <- qRunIO $ doesFileExist $ tofn x
if e then f x else [|mempty|]
-- The next two functions are for allocating a connection pool and running
-- database actions using a pool, respectively. It is used internally
-- by the scaffolded application, and therefore you will rarely need to use
-- them yourself.
withConnectionPool :: MonadInvertIO m => (ConnectionPool -> m a) -> m a
withConnectionPool = withSqlitePool connStr connectionCount
runConnectionPool :: MonadInvertIO m => SqlPersist m a -> ConnectionPool -> m a
runConnectionPool = runSqlPool
|
sseefried/funky-foto
|
Settings.hs
|
Haskell
|
bsd-2-clause
| 5,570
|
-- | Provides functionality of rendering the application model.
module Renderer
( Descriptor
, initialize
, terminate
, render
) where
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.Storable
import Graphics.Rendering.OpenGL
import System.IO
import qualified LoadShaders as LS
-- | Checks OpenGL errors, and Writes to stderr when errors occur.
checkError
:: String -- ^ a function name that called this
-> IO ()
checkError functionName = get errors >>= mapM_ reportError
where
reportError (Error category message) = do
hPutStrLn stderr $ (show category) ++ " in " ++ functionName ++ ": " ++ message
-- | Converts an offset value to the Ptr value.
bufferOffset :: Integral a
=> a -- ^ an offset value
-> Ptr b -- ^ the Ptr value
bufferOffset = plusPtr nullPtr . fromIntegral
-- | The byte size of a memory area that is converted from a list.
arrayByteSize :: (Storable a)
=> [a] -- ^ a list
-> Int
arrayByteSize ls = (sizeOf (head ls)) * (length ls)
-- | Represents a set of OpenGL objects for rendering information.
data Descriptor = Descriptor
BufferObject
VertexArrayObject
BufferObject
Program
ArrayIndex
NumArrayIndices
-- | Initializes a buffer object.
initializeBuffer :: (Storable a) => BufferTarget -> [a] -> IO BufferObject
initializeBuffer t array = do
buffer <- genObjectName
bindBuffer t $= Just buffer
withArray array $ \ptr -> do
bufferData t $= (fromIntegral $ arrayByteSize array, ptr, StaticDraw)
bindBuffer ElementArrayBuffer $= Nothing
return buffer
-- | Initializes OpenGL objects.
initialize :: IO Descriptor
initialize = do
-- meshes
let vertices =
-- vertex attribute format : x, y, z, r, g, b, a
[
(-0.90), (-0.90), 0.0, 1.0, 0.0, 0.0, 1.0
, 0.90, (-0.90), 0.0, 0.0, 1.0, 0.0, 1.0
, 0.90, 0.90, 0.0, 1.0, 1.0, 1.0, 1.0
, (-0.90), 0.90, 0.0, 0.0, 0.0, 1.0, 1.0
] :: [GLfloat]
numPositionElements = 3
numColorElements = 4
offsetPosition = 0
offsetColor = offsetPosition + numPositionElements
sizeElement = sizeOf (head vertices)
sizeVertex = fromIntegral (sizeElement * (numPositionElements + numColorElements))
let indices =
[
0, 1, 2
, 2, 3, 0
] :: [GLushort]
vertexBuffer <- initializeBuffer ArrayBuffer vertices
attributes <- genObjectName
bindVertexArrayObject $= Just attributes
bindBuffer ArrayBuffer $= Just vertexBuffer
let vPosition = AttribLocation 0
vColor = AttribLocation 1
vertexAttribPointer vPosition $=
(ToFloat, VertexArrayDescriptor (fromIntegral numPositionElements) Float sizeVertex (bufferOffset (offsetPosition * sizeElement)))
vertexAttribPointer vColor $=
(ToFloat, VertexArrayDescriptor (fromIntegral numColorElements) Float sizeVertex (bufferOffset (offsetColor * sizeElement)))
vertexAttribArray vPosition $= Enabled
vertexAttribArray vColor $= Enabled
bindBuffer ArrayBuffer $= Nothing
bindVertexArrayObject $= Nothing
indexBuffer <- initializeBuffer ElementArrayBuffer indices
program <- LS.loadShaders
[ LS.ShaderInfo VertexShader (LS.FileSource "rectangle.vert")
, LS.ShaderInfo FragmentShader (LS.FileSource "rectangle.frag")
]
currentProgram $= Just program
checkError "initialize"
return $ Descriptor vertexBuffer attributes indexBuffer program 0 (fromIntegral $ length indices)
-- | Terminates OpenGL objects.
terminate :: Descriptor -> IO ()
terminate (Descriptor vertexBuffer attributes indexBuffer program _ _) = do
currentProgram $= Nothing
shaders <- get $ attachedShaders program
mapM_ releaseShader shaders
deleteObjectName program
deleteObjectName indexBuffer
deleteObjectName attributes
deleteObjectName vertexBuffer
checkError "terminate"
where
releaseShader shader = do
detachShader program shader
deleteObjectName shader
-- | Renders the application model with a descriptor.
render :: Descriptor -- ^ a descriptor
-> IO ()
render (Descriptor _ attributes indexBuffer _ rectangleOffset rectangleNumIndices) = do
clear [ ColorBuffer ]
bindVertexArrayObject $= Just attributes
bindBuffer ElementArrayBuffer $= Just indexBuffer
drawElements Triangles rectangleNumIndices UnsignedShort (bufferOffset rectangleOffset)
bindBuffer ElementArrayBuffer $= Nothing
bindVertexArrayObject $= Nothing
flush
checkError "render"
|
fujiyan/toriaezuzakki
|
haskell/opengl/rectangle/Renderer.hs
|
Haskell
|
bsd-2-clause
| 4,665
|
{-# LANGUAGE OverloadedStrings #-}
-- | This module contains convertions from LDAP types to ASN.1.
--
-- Various hacks are employed because "asn1-encoding" only encodes to DER, but
-- LDAP demands BER-encoding. So, when a definition looks suspiciously different
-- from the spec in the comment, that's why. I hope all that will be fixed
-- eventually.
module Ldap.Asn1.ToAsn1
( ToAsn1(toAsn1)
) where
import Data.ASN1.Types (ASN1, ASN1Class, ASN1Tag, ASN1ConstructionType)
import qualified Data.ASN1.Types as Asn1
import Data.ByteString (ByteString)
import Data.Foldable (fold, foldMap)
import Data.List.NonEmpty (NonEmpty)
import Data.Maybe (maybe)
import Data.Monoid (Endo(Endo), (<>), mempty)
import qualified Data.Text.Encoding as Text
import Prelude (Integer, (.), fromIntegral)
import Ldap.Asn1.Type
-- | Convert a LDAP type to ASN.1.
--
-- When it's relevant, instances include the part of RFC describing the encoding.
class ToAsn1 a where
toAsn1 :: a -> Endo [ASN1]
{- |
@
LDAPMessage ::= SEQUENCE {
messageID MessageID,
protocolOp CHOICE {
bindRequest BindRequest,
bindResponse BindResponse,
unbindRequest UnbindRequest,
searchRequest SearchRequest,
searchResEntry SearchResultEntry,
searchResDone SearchResultDone,
searchResRef SearchResultReference,
addRequest AddRequest,
addResponse AddResponse,
... },
controls [0] Controls OPTIONAL }
@
-}
instance ToAsn1 op => ToAsn1 (LdapMessage op) where
toAsn1 (LdapMessage i op mc) =
sequence (toAsn1 i <> toAsn1 op <> maybe mempty (context 0 . toAsn1) mc)
{- |
@
MessageID ::= INTEGER (0 .. maxInt)
@
-}
instance ToAsn1 Id where
toAsn1 (Id i) = single (Asn1.IntVal (fromIntegral i))
{- |
@
LDAPString ::= OCTET STRING -- UTF-8 encoded
@
-}
instance ToAsn1 LdapString where
toAsn1 (LdapString s) = single (Asn1.OctetString (Text.encodeUtf8 s))
{- |
@
LDAPOID ::= OCTET STRING -- Constrained to \<numericoid\>
@
-}
instance ToAsn1 LdapOid where
toAsn1 (LdapOid s) = single (Asn1.OctetString (Text.encodeUtf8 s))
{- |
@
LDAPDN ::= LDAPString -- Constrained to \<distinguishedName\>
@
-}
instance ToAsn1 LdapDn where
toAsn1 (LdapDn s) = toAsn1 s
{- |
@
RelativeLDAPDN ::= LDAPString -- Constrained to \<name-component\>
@
-}
instance ToAsn1 RelativeLdapDn where
toAsn1 (RelativeLdapDn s) = toAsn1 s
{- |
@
AttributeDescription ::= LDAPString
@
-}
instance ToAsn1 AttributeDescription where
toAsn1 (AttributeDescription s) = toAsn1 s
{- |
@
AttributeValue ::= OCTET STRING
@
-}
instance ToAsn1 AttributeValue where
toAsn1 (AttributeValue s) = single (Asn1.OctetString s)
{- |
@
AttributeValueAssertion ::= SEQUENCE {
attributeDesc AttributeDescription,
assertionValue AssertionValue }
@
-}
instance ToAsn1 AttributeValueAssertion where
toAsn1 (AttributeValueAssertion d v) = toAsn1 d <> toAsn1 v
{- |
@
AssertionValue ::= OCTET STRING
@
-}
instance ToAsn1 AssertionValue where
toAsn1 (AssertionValue s) = single (Asn1.OctetString s)
{- |
@
PartialAttribute ::= SEQUENCE {
type AttributeDescription,
vals SET OF value AttributeValue }
@
-}
instance ToAsn1 PartialAttribute where
toAsn1 (PartialAttribute d xs) = sequence (toAsn1 d <> set (toAsn1 xs))
{- |
@
Attribute ::= PartialAttribute(WITH COMPONENTS {
...,
vals (SIZE(1..MAX))})
@
-}
instance ToAsn1 Attribute where
toAsn1 (Attribute d xs) = sequence (toAsn1 d <> set (toAsn1 xs))
{- |
@
MatchingRuleId ::= LDAPString
@
-}
instance ToAsn1 MatchingRuleId where
toAsn1 (MatchingRuleId s) = toAsn1 s
{- |
@
Controls ::= SEQUENCE OF control Control
@
-}
instance ToAsn1 Controls where
toAsn1 (Controls cs) = sequence (toAsn1 cs)
{- |
@
Control ::= SEQUENCE {
controlType LDAPOID,
criticality BOOLEAN DEFAULT FALSE,
controlValue OCTET STRING OPTIONAL }
@
-}
instance ToAsn1 Control where
toAsn1 (Control t c v) =
sequence (fold
[ toAsn1 t
, single (Asn1.Boolean c)
, maybe mempty (single . Asn1.OctetString) v
])
{- |
@
BindRequest ::= [APPLICATION 0] SEQUENCE {
version INTEGER (1 .. 127),
name LDAPDN,
authentication AuthenticationChoice }
@
@
UnbindRequest ::= [APPLICATION 2] NULL
@
@
SearchRequest ::= [APPLICATION 3] SEQUENCE {
baseObject LDAPDN,
scope ENUMERATED {
baseObject (0),
singleLevel (1),
wholeSubtree (2),
... },
derefAliases ENUMERATED {
neverDerefAliases (0),
derefInSearching (1),
derefFindingBaseObj (2),
derefAlways (3) },
sizeLimit INTEGER (0 .. maxInt),
timeLimit INTEGER (0 .. maxInt),
typesOnly BOOLEAN,
filter Filter,
attributes AttributeSelection }
@
@
ModifyRequest ::= [APPLICATION 6] SEQUENCE {
object LDAPDN,
changes SEQUENCE OF change SEQUENCE {
operation ENUMERATED {
add (0),
delete (1),
replace (2),
... },
modification PartialAttribute } }
@
@
AddRequest ::= [APPLICATION 8] SEQUENCE {
entry LDAPDN,
attributes AttributeList }
@
@
DelRequest ::= [APPLICATION 10] LDAPDN
@
@
ModifyDNRequest ::= [APPLICATION 12] SEQUENCE {
entry LDAPDN,
newrdn RelativeLDAPDN,
deleteoldrdn BOOLEAN,
newSuperior [0] LDAPDN OPTIONAL }
@
@
CompareRequest ::= [APPLICATION 14] SEQUENCE {
entry LDAPDN,
ava AttributeValueAssertion }
@
@
ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
requestName [0] LDAPOID,
requestValue [1] OCTET STRING OPTIONAL }
@
-}
instance ToAsn1 ProtocolClientOp where
toAsn1 (BindRequest v n a) =
application 0 (single (Asn1.IntVal (fromIntegral v)) <> toAsn1 n <> toAsn1 a)
toAsn1 UnbindRequest =
other Asn1.Application 2 mempty
toAsn1 (SearchRequest bo s da sl tl to f a) =
application 3 (fold
[ toAsn1 bo
, enum s'
, enum da'
, single (Asn1.IntVal (fromIntegral sl))
, single (Asn1.IntVal (fromIntegral tl))
, single (Asn1.Boolean to)
, toAsn1 f
, toAsn1 a
])
where
s' = case s of
BaseObject -> 0
SingleLevel -> 1
WholeSubtree -> 2
da' = case da of
NeverDerefAliases -> 0
DerefInSearching -> 1
DerefFindingBaseObject -> 2
DerefAlways -> 3
toAsn1 (ModifyRequest dn xs) =
application 6 (fold
[ toAsn1 dn
, sequence (foldMap (\(op, pa) -> sequence (enum (case op of
Add -> 0
Delete -> 1
Replace -> 2) <> toAsn1 pa)) xs)
])
toAsn1 (AddRequest dn as) =
application 8 (toAsn1 dn <> toAsn1 as)
toAsn1 (DeleteRequest (LdapDn (LdapString dn))) =
other Asn1.Application 10 (Text.encodeUtf8 dn)
toAsn1 (ModifyDnRequest dn rdn del new) =
application 12 (fold
[ toAsn1 dn
, toAsn1 rdn
, single (Asn1.Boolean del)
, maybe mempty
(\(LdapDn (LdapString dn')) -> other Asn1.Context 0 (Text.encodeUtf8 dn'))
new
])
toAsn1 (CompareRequest dn av) =
application 14 (toAsn1 dn <> sequence (toAsn1 av))
toAsn1 (ExtendedRequest (LdapOid oid) mv) =
application 23 (fold
[ other Asn1.Context 0 (Text.encodeUtf8 oid)
, maybe mempty (other Asn1.Context 1) mv
])
{- |
@
AuthenticationChoice ::= CHOICE {
simple [0] OCTET STRING,
sasl [3] SaslCredentials,
... }
SaslCredentials ::= SEQUENCE {
mechanism LDAPString,
credentials OCTET STRING OPTIONAL }
@
-}
instance ToAsn1 AuthenticationChoice where
toAsn1 (Simple s) = other Asn1.Context 0 s
toAsn1 (Sasl External c) =
context 3 (fold
[ toAsn1 (LdapString "EXTERNAL")
, maybe mempty (toAsn1 . LdapString) c
])
{- |
@
AttributeSelection ::= SEQUENCE OF selector LDAPString
@
-}
instance ToAsn1 AttributeSelection where
toAsn1 (AttributeSelection as) = sequence (toAsn1 as)
{- |
@
Filter ::= CHOICE {
and [0] SET SIZE (1..MAX) OF filter Filter,
or [1] SET SIZE (1..MAX) OF filter Filter,
not [2] Filter,
equalityMatch [3] AttributeValueAssertion,
substrings [4] SubstringFilter,
greaterOrEqual [5] AttributeValueAssertion,
lessOrEqual [6] AttributeValueAssertion,
present [7] AttributeDescription,
approxMatch [8] AttributeValueAssertion,
extensibleMatch [9] MatchingRuleAssertion,
... }
@
-}
instance ToAsn1 Filter where
toAsn1 f = case f of
And xs -> context 0 (toAsn1 xs)
Or xs -> context 1 (toAsn1 xs)
Not x -> context 2 (toAsn1 x)
EqualityMatch x -> context 3 (toAsn1 x)
Substrings x -> context 4 (toAsn1 x)
GreaterOrEqual x -> context 5 (toAsn1 x)
LessOrEqual x -> context 6 (toAsn1 x)
Present (AttributeDescription (LdapString x))
-> other Asn1.Context 7 (Text.encodeUtf8 x)
ApproxMatch x -> context 8 (toAsn1 x)
ExtensibleMatch x -> context 9 (toAsn1 x)
{- |
@
SubstringFilter ::= SEQUENCE {
type AttributeDescription,
substrings SEQUENCE SIZE (1..MAX) OF substring CHOICE {
initial [0] AssertionValue, -- can occur at most once
any [1] AssertionValue,
final [2] AssertionValue } -- can occur at most once
}
@
-}
instance ToAsn1 SubstringFilter where
toAsn1 (SubstringFilter ad ss) =
toAsn1 ad <> sequence (foldMap (\s -> case s of
Initial (AssertionValue v) -> other Asn1.Context 0 v
Any (AssertionValue v) -> other Asn1.Context 1 v
Final (AssertionValue v) -> other Asn1.Context 2 v) ss)
{- |
@
MatchingRuleAssertion ::= SEQUENCE {
matchingRule [1] MatchingRuleId OPTIONAL,
type [2] AttributeDescription OPTIONAL,
matchValue [3] AssertionValue,
dnAttributes [4] BOOLEAN DEFAULT FALSE }
@
-}
instance ToAsn1 MatchingRuleAssertion where
toAsn1 (MatchingRuleAssertion mmr mad (AssertionValue av) _) = fold
[ maybe mempty f mmr
, maybe mempty g mad
, other Asn1.Context 3 av
]
where
f (MatchingRuleId (LdapString x)) = other Asn1.Context 1 (Text.encodeUtf8 x)
g (AttributeDescription (LdapString x)) = other Asn1.Context 2 (Text.encodeUtf8 x)
{- |
@
AttributeList ::= SEQUENCE OF attribute Attribute
@
-}
instance ToAsn1 AttributeList where
toAsn1 (AttributeList xs) = sequence (toAsn1 xs)
instance ToAsn1 a => ToAsn1 [a] where
toAsn1 = foldMap toAsn1
instance ToAsn1 a => ToAsn1 (NonEmpty a) where
toAsn1 = foldMap toAsn1
sequence :: Endo [ASN1] -> Endo [ASN1]
sequence = construction Asn1.Sequence
set :: Endo [ASN1] -> Endo [ASN1]
set = construction Asn1.Set
application :: ASN1Tag -> Endo [ASN1] -> Endo [ASN1]
application = construction . Asn1.Container Asn1.Application
context :: ASN1Tag -> Endo [ASN1] -> Endo [ASN1]
context = construction . Asn1.Container Asn1.Context
construction :: ASN1ConstructionType -> Endo [ASN1] -> Endo [ASN1]
construction t x = single (Asn1.Start t) <> x <> single (Asn1.End t)
other :: ASN1Class -> ASN1Tag -> ByteString -> Endo [ASN1]
other c t = single . Asn1.Other c t
enum :: Integer -> Endo [ASN1]
enum = single . Asn1.Enumerated
single :: a -> Endo [a]
single x = Endo (x :)
|
supki/ldap-client
|
src/Ldap/Asn1/ToAsn1.hs
|
Haskell
|
bsd-2-clause
| 11,863
|
module HSNTP.Util.Daemon (daemonize, childLives) where
import System.Posix
daemonize :: IO () -> IO () -> IO ProcessID
daemonize hup comp = forkProcess cont
where cont = do createSession
installHandler lostConnection (Catch hup) Nothing
comp
childLives :: ProcessID -> IO Bool
childLives pid = do sleep 1
ms <- getProcessStatus False False pid
return $ maybe True (const False) ms
|
creswick/hsntp
|
HSNTP/Util/Daemon.hs
|
Haskell
|
bsd-3-clause
| 413
|
-- -fno-warn-deprecations for use of Map.foldWithKey
{-# OPTIONS_GHC -fno-warn-deprecations #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.PackageDescription.Configuration
-- Copyright : Thomas Schilling, 2007
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is about the cabal configurations feature. It exports
-- 'finalizePackageDescription' and 'flattenPackageDescription' which are
-- functions for converting 'GenericPackageDescription's down to
-- 'PackageDescription's. It has code for working with the tree of conditions
-- and resolving or flattening conditions.
module Distribution.PackageDescription.Configuration (
finalizePackageDescription,
flattenPackageDescription,
-- Utils
parseCondition,
freeVars,
mapCondTree,
mapTreeData,
mapTreeConds,
mapTreeConstrs,
) where
import Distribution.Package
import Distribution.PackageDescription
import Distribution.PackageDescription.Utils
import Distribution.Version
import Distribution.Compiler
import Distribution.System
import Distribution.Simple.Utils
import Distribution.Text
import Distribution.Compat.ReadP as ReadP hiding ( char )
import qualified Distribution.Compat.ReadP as ReadP ( char )
import Distribution.Compat.Semigroup as Semi
import Control.Arrow (first)
import Data.Char ( isAlphaNum )
import Data.Maybe ( mapMaybe, maybeToList )
import Data.Map ( Map, fromListWith, toList )
import qualified Data.Map as Map
------------------------------------------------------------------------------
-- | Simplify the condition and return its free variables.
simplifyCondition :: Condition c
-> (c -> Either d Bool) -- ^ (partial) variable assignment
-> (Condition d, [d])
simplifyCondition cond i = fv . walk $ cond
where
walk cnd = case cnd of
Var v -> either Var Lit (i v)
Lit b -> Lit b
CNot c -> case walk c of
Lit True -> Lit False
Lit False -> Lit True
c' -> CNot c'
COr c d -> case (walk c, walk d) of
(Lit False, d') -> d'
(Lit True, _) -> Lit True
(c', Lit False) -> c'
(_, Lit True) -> Lit True
(c',d') -> COr c' d'
CAnd c d -> case (walk c, walk d) of
(Lit False, _) -> Lit False
(Lit True, d') -> d'
(_, Lit False) -> Lit False
(c', Lit True) -> c'
(c',d') -> CAnd c' d'
-- gather free vars
fv c = (c, fv' c)
fv' c = case c of
Var v -> [v]
Lit _ -> []
CNot c' -> fv' c'
COr c1 c2 -> fv' c1 ++ fv' c2
CAnd c1 c2 -> fv' c1 ++ fv' c2
-- | Simplify a configuration condition using the OS and arch names. Returns
-- the names of all the flags occurring in the condition.
simplifyWithSysParams :: OS -> Arch -> CompilerInfo -> Condition ConfVar
-> (Condition FlagName, [FlagName])
simplifyWithSysParams os arch cinfo cond = (cond', flags)
where
(cond', flags) = simplifyCondition cond interp
interp (OS os') = Right $ os' == os
interp (Arch arch') = Right $ arch' == arch
interp (Impl comp vr)
| matchImpl (compilerInfoId cinfo) = Right True
| otherwise = case compilerInfoCompat cinfo of
-- fixme: treat Nothing as unknown, rather than empty list once we
-- support partial resolution of system parameters
Nothing -> Right False
Just compat -> Right (any matchImpl compat)
where
matchImpl (CompilerId c v) = comp == c && v `withinRange` vr
interp (Flag f) = Left f
-- TODO: Add instances and check
--
-- prop_sC_idempotent cond a o = cond' == cond''
-- where
-- cond' = simplifyCondition cond a o
-- cond'' = simplifyCondition cond' a o
--
-- prop_sC_noLits cond a o = isLit res || not (hasLits res)
-- where
-- res = simplifyCondition cond a o
-- hasLits (Lit _) = True
-- hasLits (CNot c) = hasLits c
-- hasLits (COr l r) = hasLits l || hasLits r
-- hasLits (CAnd l r) = hasLits l || hasLits r
-- hasLits _ = False
--
-- | Parse a configuration condition from a string.
parseCondition :: ReadP r (Condition ConfVar)
parseCondition = condOr
where
condOr = sepBy1 condAnd (oper "||") >>= return . foldl1 COr
condAnd = sepBy1 cond (oper "&&")>>= return . foldl1 CAnd
cond = sp >> (boolLiteral +++ inparens condOr +++ notCond +++ osCond
+++ archCond +++ flagCond +++ implCond )
inparens = between (ReadP.char '(' >> sp) (sp >> ReadP.char ')' >> sp)
notCond = ReadP.char '!' >> sp >> cond >>= return . CNot
osCond = string "os" >> sp >> inparens osIdent >>= return . Var
archCond = string "arch" >> sp >> inparens archIdent >>= return . Var
flagCond = string "flag" >> sp >> inparens flagIdent >>= return . Var
implCond = string "impl" >> sp >> inparens implIdent >>= return . Var
boolLiteral = fmap Lit parse
archIdent = fmap Arch parse
osIdent = fmap OS parse
flagIdent = fmap (Flag . FlagName . lowercase) (munch1 isIdentChar)
isIdentChar c = isAlphaNum c || c == '_' || c == '-'
oper s = sp >> string s >> sp
sp = skipSpaces
implIdent = do i <- parse
vr <- sp >> option anyVersion parse
return $ Impl i vr
------------------------------------------------------------------------------
mapCondTree :: (a -> b) -> (c -> d) -> (Condition v -> Condition w)
-> CondTree v c a -> CondTree w d b
mapCondTree fa fc fcnd (CondNode a c ifs) =
CondNode (fa a) (fc c) (map g ifs)
where
g (cnd, t, me) = (fcnd cnd, mapCondTree fa fc fcnd t,
fmap (mapCondTree fa fc fcnd) me)
mapTreeConstrs :: (c -> d) -> CondTree v c a -> CondTree v d a
mapTreeConstrs f = mapCondTree id f id
mapTreeConds :: (Condition v -> Condition w) -> CondTree v c a -> CondTree w c a
mapTreeConds f = mapCondTree id id f
mapTreeData :: (a -> b) -> CondTree v c a -> CondTree v c b
mapTreeData f = mapCondTree f id id
-- | Result of dependency test. Isomorphic to @Maybe d@ but renamed for
-- clarity.
data DepTestRslt d = DepOk | MissingDeps d
instance Semigroup d => Monoid (DepTestRslt d) where
mempty = DepOk
mappend = (Semi.<>)
instance Semigroup d => Semigroup (DepTestRslt d) where
DepOk <> x = x
x <> DepOk = x
(MissingDeps d) <> (MissingDeps d') = MissingDeps (d <> d')
-- | Try to find a flag assignment that satisfies the constraints of all trees.
--
-- Returns either the missing dependencies, or a tuple containing the
-- resulting data, the associated dependencies, and the chosen flag
-- assignments.
--
-- In case of failure, the _smallest_ number of of missing dependencies is
-- returned. [TODO: Could also be specified with a function argument.]
--
-- TODO: The current algorithm is rather naive. A better approach would be to:
--
-- * Rule out possible paths, by taking a look at the associated dependencies.
--
-- * Infer the required values for the conditions of these paths, and
-- calculate the required domains for the variables used in these
-- conditions. Then picking a flag assignment would be linear (I guess).
--
-- This would require some sort of SAT solving, though, thus it's not
-- implemented unless we really need it.
--
resolveWithFlags ::
[(FlagName,[Bool])]
-- ^ Domain for each flag name, will be tested in order.
-> OS -- ^ OS as returned by Distribution.System.buildOS
-> Arch -- ^ Arch as returned by Distribution.System.buildArch
-> CompilerInfo -- ^ Compiler information
-> [Dependency] -- ^ Additional constraints
-> [CondTree ConfVar [Dependency] PDTagged]
-> ([Dependency] -> DepTestRslt [Dependency]) -- ^ Dependency test function.
-> Either [Dependency] (TargetSet PDTagged, FlagAssignment)
-- ^ Either the missing dependencies (error case), or a pair of
-- (set of build targets with dependencies, chosen flag assignments)
resolveWithFlags dom os arch impl constrs trees checkDeps = try dom []
where
extraConstrs = toDepMap constrs
-- simplify trees by (partially) evaluating all conditions and converting
-- dependencies to dependency maps.
simplifiedTrees :: [CondTree FlagName DependencyMap PDTagged]
simplifiedTrees = map ( mapTreeConstrs toDepMap -- convert to maps
. mapTreeConds (fst . simplifyWithSysParams os arch impl))
trees
-- @try@ recursively tries all possible flag assignments in the domain and
-- either succeeds or returns the shortest list of missing dependencies.
try :: [(FlagName, [Bool])]
-> [(FlagName, Bool)]
-> Either [Dependency] (TargetSet PDTagged, FlagAssignment)
try [] flags =
let targetSet = TargetSet $ flip map simplifiedTrees $
-- apply additional constraints to all dependencies
first (`constrainBy` extraConstrs) .
simplifyCondTree (env flags)
deps = overallDependencies targetSet
in case checkDeps (fromDepMap deps) of
DepOk -> Right (targetSet, flags)
MissingDeps mds -> Left mds
try ((n, vals):rest) flags =
tryAll $ map (\v -> try rest ((n, v):flags)) vals
tryAll :: [Either [a] b] -> Either [a] b
tryAll = foldr mp mz
-- special version of `mplus' for our local purposes
mp :: Either [a] b -> Either [a] b -> Either [a] b
mp (Left xs) (Left ys) = xs `seq` ys `seq` Left (findShortest xs ys)
mp (Left _) m@(Right _) = m
mp m@(Right _) _ = m
-- `mzero'
mz :: Either [a] b
mz = Left []
env :: FlagAssignment -> FlagName -> Either FlagName Bool
env flags flag = (maybe (Left flag) Right . lookup flag) flags
-- we pick the shortest list of missing dependencies
findShortest :: [a] -> [a] -> [a]
findShortest [] xs = xs -- [] is too short
findShortest xs [] = xs
findShortest [x] _ = [x] -- single elem is optimum
findShortest _ [x] = [x]
findShortest xs ys = if lazyLengthCmp xs ys
then xs else ys
-- lazy variant of @\xs ys -> length xs <= length ys@
lazyLengthCmp :: [a] -> [a] -> Bool
lazyLengthCmp [] _ = True
lazyLengthCmp _ [] = False
lazyLengthCmp (_:xs) (_:ys) = lazyLengthCmp xs ys
-- | A map of dependencies. Newtyped since the default monoid instance is not
-- appropriate. The monoid instance uses 'intersectVersionRanges'.
newtype DependencyMap = DependencyMap { unDependencyMap :: Map PackageName VersionRange }
deriving (Show, Read)
instance Monoid DependencyMap where
mempty = DependencyMap Map.empty
mappend = (Semi.<>)
instance Semigroup DependencyMap where
(DependencyMap a) <> (DependencyMap b) =
DependencyMap (Map.unionWith intersectVersionRanges a b)
toDepMap :: [Dependency] -> DependencyMap
toDepMap ds =
DependencyMap $ fromListWith intersectVersionRanges [ (p,vr) | Dependency p vr <- ds ]
fromDepMap :: DependencyMap -> [Dependency]
fromDepMap m = [ Dependency p vr | (p,vr) <- toList (unDependencyMap m) ]
simplifyCondTree :: (Monoid a, Monoid d) =>
(v -> Either v Bool)
-> CondTree v d a
-> (d, a)
simplifyCondTree env (CondNode a d ifs) =
mconcat $ (d, a) : mapMaybe simplifyIf ifs
where
simplifyIf (cnd, t, me) =
case simplifyCondition cnd env of
(Lit True, _) -> Just $ simplifyCondTree env t
(Lit False, _) -> fmap (simplifyCondTree env) me
_ -> error $ "Environment not defined for all free vars"
-- | Flatten a CondTree. This will resolve the CondTree by taking all
-- possible paths into account. Note that since branches represent exclusive
-- choices this may not result in a \"sane\" result.
ignoreConditions :: (Monoid a, Monoid c) => CondTree v c a -> (a, c)
ignoreConditions (CondNode a c ifs) = (a, c) `mappend` mconcat (concatMap f ifs)
where f (_, t, me) = ignoreConditions t
: maybeToList (fmap ignoreConditions me)
freeVars :: CondTree ConfVar c a -> [FlagName]
freeVars t = [ f | Flag f <- freeVars' t ]
where
freeVars' (CondNode _ _ ifs) = concatMap compfv ifs
compfv (c, ct, mct) = condfv c ++ freeVars' ct ++ maybe [] freeVars' mct
condfv c = case c of
Var v -> [v]
Lit _ -> []
CNot c' -> condfv c'
COr c1 c2 -> condfv c1 ++ condfv c2
CAnd c1 c2 -> condfv c1 ++ condfv c2
------------------------------------------------------------------------------
-- | A set of targets with their package dependencies
newtype TargetSet a = TargetSet [(DependencyMap, a)]
-- | Combine the target-specific dependencies in a TargetSet to give the
-- dependencies for the package as a whole.
overallDependencies :: TargetSet PDTagged -> DependencyMap
overallDependencies (TargetSet targets) = mconcat depss
where
(depss, _) = unzip $ filter (removeDisabledSections . snd) targets
removeDisabledSections :: PDTagged -> Bool
removeDisabledSections (Lib l) = buildable (libBuildInfo l)
removeDisabledSections (Exe _ e) = buildable (buildInfo e)
removeDisabledSections (Test _ t) = testEnabled t && buildable (testBuildInfo t)
removeDisabledSections (Bench _ b) = benchmarkEnabled b && buildable (benchmarkBuildInfo b)
removeDisabledSections PDNull = True
-- Apply extra constraints to a dependency map.
-- Combines dependencies where the result will only contain keys from the left
-- (first) map. If a key also exists in the right map, both constraints will
-- be intersected.
constrainBy :: DependencyMap -- ^ Input map
-> DependencyMap -- ^ Extra constraints
-> DependencyMap
constrainBy left extra =
DependencyMap $
Map.foldWithKey tightenConstraint (unDependencyMap left)
(unDependencyMap extra)
where tightenConstraint n c l =
case Map.lookup n l of
Nothing -> l
Just vr -> Map.insert n (intersectVersionRanges vr c) l
-- | Collect up the targets in a TargetSet of tagged targets, storing the
-- dependencies as we go.
flattenTaggedTargets :: TargetSet PDTagged ->
(Maybe Library, [(String, Executable)], [(String, TestSuite)]
, [(String, Benchmark)])
flattenTaggedTargets (TargetSet targets) = foldr untag (Nothing, [], [], []) targets
where
untag (_, Lib _) (Just _, _, _, _) = userBug "Only one library expected"
untag (deps, Lib l) (Nothing, exes, tests, bms) =
(Just l', exes, tests, bms)
where
l' = l {
libBuildInfo = (libBuildInfo l) { targetBuildDepends = fromDepMap deps }
}
untag (deps, Exe n e) (mlib, exes, tests, bms)
| any ((== n) . fst) exes =
userBug $ "There exist several exes with the same name: '" ++ n ++ "'"
| any ((== n) . fst) tests =
userBug $ "There exists a test with the same name as an exe: '" ++ n ++ "'"
| any ((== n) . fst) bms =
userBug $ "There exists a benchmark with the same name as an exe: '" ++ n ++ "'"
| otherwise = (mlib, (n, e'):exes, tests, bms)
where
e' = e {
buildInfo = (buildInfo e) { targetBuildDepends = fromDepMap deps }
}
untag (deps, Test n t) (mlib, exes, tests, bms)
| any ((== n) . fst) tests =
userBug $ "There exist several tests with the same name: '" ++ n ++ "'"
| any ((== n) . fst) exes =
userBug $ "There exists an exe with the same name as the test: '" ++ n ++ "'"
| any ((== n) . fst) bms =
userBug $ "There exists a benchmark with the same name as the test: '" ++ n ++ "'"
| otherwise = (mlib, exes, (n, t'):tests, bms)
where
t' = t {
testBuildInfo = (testBuildInfo t)
{ targetBuildDepends = fromDepMap deps }
}
untag (deps, Bench n b) (mlib, exes, tests, bms)
| any ((== n) . fst) bms =
userBug $ "There exist several benchmarks with the same name: '" ++ n ++ "'"
| any ((== n) . fst) exes =
userBug $ "There exists an exe with the same name as the benchmark: '" ++ n ++ "'"
| any ((== n) . fst) tests =
userBug $ "There exists a test with the same name as the benchmark: '" ++ n ++ "'"
| otherwise = (mlib, exes, tests, (n, b'):bms)
where
b' = b {
benchmarkBuildInfo = (benchmarkBuildInfo b)
{ targetBuildDepends = fromDepMap deps }
}
untag (_, PDNull) x = x -- actually this should not happen, but let's be liberal
------------------------------------------------------------------------------
-- Convert GenericPackageDescription to PackageDescription
--
data PDTagged = Lib Library
| Exe String Executable
| Test String TestSuite
| Bench String Benchmark
| PDNull
deriving Show
instance Monoid PDTagged where
mempty = PDNull
mappend = (Semi.<>)
instance Semigroup PDTagged where
PDNull <> x = x
x <> PDNull = x
Lib l <> Lib l' = Lib (l <> l')
Exe n e <> Exe n' e' | n == n' = Exe n (e <> e')
Test n t <> Test n' t' | n == n' = Test n (t <> t')
Bench n b <> Bench n' b' | n == n' = Bench n (b <> b')
_ <> _ = cabalBug "Cannot combine incompatible tags"
-- | Create a package description with all configurations resolved.
--
-- This function takes a `GenericPackageDescription` and several environment
-- parameters and tries to generate `PackageDescription` by finding a flag
-- assignment that result in satisfiable dependencies.
--
-- It takes as inputs a not necessarily complete specifications of flags
-- assignments, an optional package index as well as platform parameters. If
-- some flags are not assigned explicitly, this function will try to pick an
-- assignment that causes this function to succeed. The package index is
-- optional since on some platforms we cannot determine which packages have
-- been installed before. When no package index is supplied, every dependency
-- is assumed to be satisfiable, therefore all not explicitly assigned flags
-- will get their default values.
--
-- This function will fail if it cannot find a flag assignment that leads to
-- satisfiable dependencies. (It will not try alternative assignments for
-- explicitly specified flags.) In case of failure it will return a /minimum/
-- number of dependencies that could not be satisfied. On success, it will
-- return the package description and the full flag assignment chosen.
--
finalizePackageDescription ::
FlagAssignment -- ^ Explicitly specified flag assignments
-> (Dependency -> Bool) -- ^ Is a given dependency satisfiable from the set of
-- available packages? If this is unknown then use
-- True.
-> Platform -- ^ The 'Arch' and 'OS'
-> CompilerInfo -- ^ Compiler information
-> [Dependency] -- ^ Additional constraints
-> GenericPackageDescription
-> Either [Dependency]
(PackageDescription, FlagAssignment)
-- ^ Either missing dependencies or the resolved package
-- description along with the flag assignments chosen.
finalizePackageDescription userflags satisfyDep
(Platform arch os) impl constraints
(GenericPackageDescription pkg flags mlib0 exes0 tests0 bms0) =
case resolveFlags of
Right ((mlib, exes', tests', bms'), targetSet, flagVals) ->
Right ( pkg { library = mlib
, executables = exes'
, testSuites = tests'
, benchmarks = bms'
, buildDepends = fromDepMap (overallDependencies targetSet)
}
, flagVals )
Left missing -> Left missing
where
-- Combine lib, exes, and tests into one list of @CondTree@s with tagged data
condTrees = maybeToList (fmap (mapTreeData Lib) mlib0 )
++ map (\(name,tree) -> mapTreeData (Exe name) tree) exes0
++ map (\(name,tree) -> mapTreeData (Test name) tree) tests0
++ map (\(name,tree) -> mapTreeData (Bench name) tree) bms0
resolveFlags =
case resolveWithFlags flagChoices os arch impl constraints condTrees check of
Right (targetSet, fs) ->
let (mlib, exes, tests, bms) = flattenTaggedTargets targetSet in
Right ( (fmap libFillInDefaults mlib,
map (\(n,e) -> (exeFillInDefaults e) { exeName = n }) exes,
map (\(n,t) -> (testFillInDefaults t) { testName = n }) tests,
map (\(n,b) -> (benchFillInDefaults b) { benchmarkName = n }) bms),
targetSet, fs)
Left missing -> Left missing
flagChoices = map (\(MkFlag n _ d manual) -> (n, d2c manual n d)) flags
d2c manual n b = case lookup n userflags of
Just val -> [val]
Nothing
| manual -> [b]
| otherwise -> [b, not b]
--flagDefaults = map (\(n,x:_) -> (n,x)) flagChoices
check ds = let missingDeps = filter (not . satisfyDep) ds
in if null missingDeps
then DepOk
else MissingDeps missingDeps
{-
let tst_p = (CondNode [1::Int] [Distribution.Package.Dependency "a" AnyVersion] [])
let tst_p2 = (CondNode [1::Int] [Distribution.Package.Dependency "a" (EarlierVersion (Version [1,0] [])), Distribution.Package.Dependency "a" (LaterVersion (Version [2,0] []))] [])
let p_index = Distribution.Simple.PackageIndex.fromList [Distribution.Package.PackageIdentifier "a" (Version [0,5] []), Distribution.Package.PackageIdentifier "a" (Version [2,5] [])]
let look = not . null . Distribution.Simple.PackageIndex.lookupDependency p_index
let looks ds = mconcat $ map (\d -> if look d then DepOk else MissingDeps [d]) ds
resolveWithFlags [] Distribution.System.Linux Distribution.System.I386 (Distribution.Compiler.GHC,Version [6,8,2] []) [tst_p] looks ===> Right ...
resolveWithFlags [] Distribution.System.Linux Distribution.System.I386 (Distribution.Compiler.GHC,Version [6,8,2] []) [tst_p2] looks ===> Left ...
-}
-- | Flatten a generic package description by ignoring all conditions and just
-- join the field descriptors into on package description. Note, however,
-- that this may lead to inconsistent field values, since all values are
-- joined into one field, which may not be possible in the original package
-- description, due to the use of exclusive choices (if ... else ...).
--
-- TODO: One particularly tricky case is defaulting. In the original package
-- description, e.g., the source directory might either be the default or a
-- certain, explicitly set path. Since defaults are filled in only after the
-- package has been resolved and when no explicit value has been set, the
-- default path will be missing from the package description returned by this
-- function.
flattenPackageDescription :: GenericPackageDescription -> PackageDescription
flattenPackageDescription (GenericPackageDescription pkg _ mlib0 exes0 tests0 bms0) =
pkg { library = mlib
, executables = reverse exes
, testSuites = reverse tests
, benchmarks = reverse bms
, buildDepends = ldeps ++ reverse edeps ++ reverse tdeps ++ reverse bdeps
}
where
(mlib, ldeps) = case mlib0 of
Just lib -> let (l,ds) = ignoreConditions lib in
(Just (libFillInDefaults l), ds)
Nothing -> (Nothing, [])
(exes, edeps) = foldr flattenExe ([],[]) exes0
(tests, tdeps) = foldr flattenTst ([],[]) tests0
(bms, bdeps) = foldr flattenBm ([],[]) bms0
flattenExe (n, t) (es, ds) =
let (e, ds') = ignoreConditions t in
( (exeFillInDefaults $ e { exeName = n }) : es, ds' ++ ds )
flattenTst (n, t) (es, ds) =
let (e, ds') = ignoreConditions t in
( (testFillInDefaults $ e { testName = n }) : es, ds' ++ ds )
flattenBm (n, t) (es, ds) =
let (e, ds') = ignoreConditions t in
( (benchFillInDefaults $ e { benchmarkName = n }) : es, ds' ++ ds )
-- This is in fact rather a hack. The original version just overrode the
-- default values, however, when adding conditions we had to switch to a
-- modifier-based approach. There, nothing is ever overwritten, but only
-- joined together.
--
-- This is the cleanest way i could think of, that doesn't require
-- changing all field parsing functions to return modifiers instead.
libFillInDefaults :: Library -> Library
libFillInDefaults lib@(Library { libBuildInfo = bi }) =
lib { libBuildInfo = biFillInDefaults bi }
exeFillInDefaults :: Executable -> Executable
exeFillInDefaults exe@(Executable { buildInfo = bi }) =
exe { buildInfo = biFillInDefaults bi }
testFillInDefaults :: TestSuite -> TestSuite
testFillInDefaults tst@(TestSuite { testBuildInfo = bi }) =
tst { testBuildInfo = biFillInDefaults bi }
benchFillInDefaults :: Benchmark -> Benchmark
benchFillInDefaults bm@(Benchmark { benchmarkBuildInfo = bi }) =
bm { benchmarkBuildInfo = biFillInDefaults bi }
biFillInDefaults :: BuildInfo -> BuildInfo
biFillInDefaults bi =
if null (hsSourceDirs bi)
then bi { hsSourceDirs = [currentDir] }
else bi
|
edsko/cabal
|
Cabal/src/Distribution/PackageDescription/Configuration.hs
|
Haskell
|
bsd-3-clause
| 25,834
|
{-# LANGUAGE BangPatterns, MultiParamTypeClasses, FunctionalDependencies,
FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Permute.MPermute
-- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu>
-- License : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability : experimental
--
-- An overloaded interface to mutable permutations. For permutation types which
-- can be used with this interface, see "Data.Permute.IO" and "Data.Permute.ST".
--
module Data.Permute.MPermute (
-- * Class of mutable permutation types
MPermute,
-- * Constructing mutable permutations
newPermute,
newPermute_,
newListPermute,
newSwapsPermute,
newCyclesPermute,
newCopyPermute,
copyPermute,
setIdentity,
-- * Accessing permutation elements
getElem,
setElem,
getIndexOf,
swapElems,
-- * Permutation properties
getSize,
getElems,
setElems,
isValid,
getIsEven,
getPeriod,
-- * Permutation functions
getInverse,
copyInverse,
setNext,
setPrev,
-- * Applying permutations
getSwaps,
getInvSwaps,
getCycleFrom,
getCycles,
-- * Sorting
getSort,
getSortBy,
getOrder,
getOrderBy,
getRank,
getRankBy,
-- * Converstions between mutable and immutable permutations
freeze,
unsafeFreeze,
thaw,
unsafeThaw,
-- * Unsafe operations
unsafeNewListPermute,
unsafeNewSwapsPermute,
unsafeNewCyclesPermute,
unsafeGetElem,
unsafeSetElem,
unsafeSwapElems,
) where
import Control.Monad
import Control.Monad.ST
import Data.Function( on )
import qualified Data.List as List
import System.IO.Unsafe( unsafeInterleaveIO )
import Data.Permute.Base
import Data.Permute.IOBase
--------------------------------- MPermute --------------------------------
-- | Class for representing a mutable permutation. The type is parameterized
-- over the type of the monad, @m@, in which the mutable permutation will be
-- manipulated.
class (Monad m) => MPermute p m | p -> m, m -> p where
-- | Get the size of a permutation.
getSize :: p -> m Int
-- | Create a new permutation initialized to be the identity.
newPermute :: Int -> m p
-- | Allocate a new permutation but do not initialize it.
newPermute_ :: Int -> m p
unsafeGetElem :: p -> Int -> m Int
unsafeSetElem :: p -> Int -> Int -> m ()
unsafeSwapElems :: p -> Int -> Int -> m ()
-- | Get a lazy list of the permutation elements. The laziness makes this
-- function slightly dangerous if you are modifying the permutation.
getElems :: p -> m [Int]
-- | Set all the values of a permutation from a list of elements.
setElems :: p -> [Int] -> m ()
unsafeFreeze :: p -> m Permute
unsafeThaw :: Permute -> m p
unsafeInterleaveM :: m a -> m a
-- | Construct a permutation from a list of elements.
-- @newListPermute n is@ creates a permutation of size @n@ with
-- the @i@th element equal to @is !! i@. For the permutation to be valid,
-- the list @is@ must have length @n@ and contain the indices @0..(n-1)@
-- exactly once each.
newListPermute :: (MPermute p m) => Int -> [Int] -> m p
newListPermute n is = do
p <- unsafeNewListPermute n is
valid <- isValid p
when (not valid) $ fail "invalid permutation"
return p
{-# INLINE newListPermute #-}
unsafeNewListPermute :: (MPermute p m) => Int -> [Int] -> m p
unsafeNewListPermute n is = do
p <- newPermute_ n
setElems p is
return p
{-# INLINE unsafeNewListPermute #-}
-- | Construct a permutation from a list of swaps.
-- @newSwapsPermute n ss@ creates a permutation of size @n@ given a
-- sequence of swaps.
-- If @ss@ is @[(i0,j0), (i1,j1), ..., (ik,jk)]@, the
-- sequence of swaps is
-- @i0 \<-> j0@, then
-- @i1 \<-> j1@, and so on until
-- @ik \<-> jk@.
newSwapsPermute :: (MPermute p m) => Int -> [(Int,Int)] -> m p
newSwapsPermute = newSwapsPermuteHelp swapElems
{-# INLINE newSwapsPermute #-}
unsafeNewSwapsPermute :: (MPermute p m) => Int -> [(Int,Int)] -> m p
unsafeNewSwapsPermute = newSwapsPermuteHelp unsafeSwapElems
{-# INLINE unsafeNewSwapsPermute #-}
newSwapsPermuteHelp :: (MPermute p m) => (p -> Int -> Int -> m ())
-> Int -> [(Int,Int)] -> m p
newSwapsPermuteHelp swap n ss = do
p <- newPermute n
mapM_ (uncurry $ swap p) ss
return p
{-# INLINE newSwapsPermuteHelp #-}
-- | Construct a permutation from a list of disjoint cycles.
-- @newCyclesPermute n cs@ creates a permutation of size @n@ which is the
-- composition of the cycles @cs@.
newCyclesPermute :: (MPermute p m) => Int -> [[Int]] -> m p
newCyclesPermute n cs =
newSwapsPermute n $ concatMap cycleToSwaps cs
{-# INLINE newCyclesPermute #-}
unsafeNewCyclesPermute :: (MPermute p m) => Int -> [[Int]] -> m p
unsafeNewCyclesPermute n cs =
unsafeNewSwapsPermute n $ concatMap cycleToSwaps cs
{-# INLINE unsafeNewCyclesPermute #-}
cycleToSwaps :: [Int] -> [(Int, Int)]
cycleToSwaps [] = error "Empty cycle"
cycleToSwaps (i:is) = [(i,j) | j <- reverse is]
{-# INLINE cycleToSwaps #-}
-- | Construct a new permutation by copying another.
newCopyPermute :: (MPermute p m) => p -> m p
newCopyPermute p = do
n <- getSize p
p' <- newPermute_ n
copyPermute p' p
return p'
{-# INLINE newCopyPermute #-}
-- | @copyPermute dst src@ copies the elements of the permutation @src@
-- into the permutation @dst@. The two permutations must have the same
-- size.
copyPermute :: (MPermute p m) => p -> p -> m ()
copyPermute dst src =
getElems src >>= setElems dst
{-# INLINE copyPermute #-}
-- | Set a permutation to the identity.
setIdentity :: (MPermute p m) => p -> m ()
setIdentity p = do
n <- getSize p
setElems p [0 .. n-1]
{-# INLINE setIdentity #-}
-- | @getElem p i@ gets the value of the @i@th element of the permutation
-- @p@. The index @i@ must be in the range @0..(n-1)@, where @n@ is the
-- size of the permutation.
getElem :: (MPermute p m) => p -> Int -> m Int
getElem p i = do
n <- getSize p
when (i < 0 || i >= n) $ fail "getElem: invalid index"
unsafeGetElem p i
{-# INLINE getElem #-}
-- | @getIndexOf p x@ returns @i@ sutch that @getElem p i@ equals @x@. This
-- is a linear-time operation.
getIndexOf :: (MPermute p m) => p -> Int -> m Int
getIndexOf p x =
let go !i (y:ys) | y == x = i
| otherwise = go (i+1) ys
go _ _ = error "getIndexOf: invalid element"
in
liftM (go 0) $ getElems p
{-# INLINE getIndexOf #-}
-- | @setElem p i x@ sets the value of the @i@th element of the permutation
-- @p@. The index @i@ must be in the range @0..(n-1)@, where @n@ is the
-- size of the permutation.
setElem :: (MPermute p m) => p -> Int -> Int -> m ()
setElem p i x = do
n <- getSize p
when (i < 0 || i >= n) $ fail "getElem: invalid index"
unsafeSetElem p i x
{-# INLINE setElem #-}
-- | @swapElems p i j@ exchanges the @i@th and @j@th elements of the
-- permutation @p@.
swapElems :: (MPermute p m) => p -> Int -> Int -> m ()
swapElems p i j = do
n <- getSize p
when (i < 0 || i >= n || j < 0 || j >= n) $ fail "swapElems: invalid index"
unsafeSwapElems p i j
{-# INLINE swapElems #-}
-- | Returns whether or not the permutation is valid. For it to be valid,
-- the numbers @0,...,(n-1)@ must all appear exactly once in the stored
-- values @p[0],...,p[n-1]@.
isValid :: (MPermute p m) => p -> m Bool
isValid p = do
n <- getSize p
valid <- liftM and $ validIndices n
return $! valid
where
j `existsIn` i = do
seen <- liftM (take i) $ getElems p
return $ (any (==j)) seen
isValidIndex n i = do
i' <- unsafeGetElem p i
valid <- return $ i' >= 0 && i' < n
unique <- liftM not (i' `existsIn` i)
return $ valid && unique
validIndices n = validIndicesHelp n 0
validIndicesHelp n i
| i == n = return []
| otherwise = unsafeInterleaveM $ do
a <- isValidIndex n i
as <- validIndicesHelp n (i+1)
return (a:as)
{-# INLINE isValid #-}
-- | Compute the inverse of a permutation.
getInverse :: (MPermute p m) => p -> m p
getInverse p = do
n <- getSize p
q <- newPermute_ n
copyInverse q p
return $! q
{-# INLINE getInverse #-}
-- | Set one permutation to be the inverse of another.
-- @copyInverse inv p@ computes the inverse of @p@ and stores it in @inv@.
-- The two permutations must have the same size.
copyInverse :: (MPermute p m) => p -> p -> m ()
copyInverse dst src = do
n <- getSize src
n' <- getSize dst
when (n /= n') $ fail "permutation size mismatch"
forM_ [0 .. n-1] $ \i -> do
i' <- unsafeGetElem src i
unsafeSetElem dst i' i
{-# INLINE copyInverse #-}
-- | Advance a permutation to the next permutation in lexicogrphic order and
-- return @True@. If no further permutaitons are available, return @False@ and
-- leave the permutation unmodified. Starting with the idendity permutation
-- and repeatedly calling @setNext@ will iterate through all permutations of a
-- given size.
setNext :: (MPermute p m) => p -> m Bool
setNext = setNextBy compare
{-# INLINE setNext #-}
-- | Step backwards to the previous permutation in lexicographic order and
-- return @True@. If there is no previous permutation, return @False@ and
-- leave the permutation unmodified.
setPrev :: (MPermute p m) => p -> m Bool
setPrev = setNextBy (flip compare)
{-# INLINE setPrev #-}
setNextBy :: (MPermute p m) => (Int -> Int -> Ordering) -> p -> m Bool
setNextBy cmp p = do
n <- getSize p
if n > 1
then do
findLastAscent (n-2) >>=
maybe (return False) (\i -> do
i' <- unsafeGetElem p i
i1' <- unsafeGetElem p (i+1)
(k,k') <- findSmallestLargerThan n i' (i+2) (i+1) i1'
-- swap i and k
unsafeSetElem p i k'
unsafeSetElem p k i'
reverseElems (i+1) (n-1)
return True
)
else
return False
where
i `lt` j = cmp i j == LT
i `gt` j = cmp i j == GT
findLastAscent i = do
ascent <- isAscent i
if ascent then return (Just i) else recurse
where
recurse = if i /= 0 then findLastAscent (i-1) else return Nothing
findSmallestLargerThan n i' j k k'
| j < n = do
j' <- unsafeGetElem p j
if j' `gt` i' && j' `lt` k'
then findSmallestLargerThan n i' (j+1) j j'
else findSmallestLargerThan n i' (j+1) k k'
| otherwise =
return (k,k')
isAscent i = liftM2 lt (unsafeGetElem p i) (unsafeGetElem p (i+1))
reverseElems i j
| i >= j = return ()
| otherwise = do
unsafeSwapElems p i j
reverseElems (i+1) (j-1)
{-# INLINE setNextBy #-}
-- | Get a lazy list of swaps equivalent to the permutation. A result of
-- @[ (i0,j0), (i1,j1), ..., (ik,jk) ]@ means swap @i0 \<-> j0@,
-- then @i1 \<-> j1@, and so on until @ik \<-> jk@. The laziness makes this
-- function slightly dangerous if you are modifying the permutation.
getSwaps :: (MPermute p m) => p -> m [(Int,Int)]
getSwaps = getSwapsHelp overlapping_pairs
where
overlapping_pairs [] = []
overlapping_pairs [_] = []
overlapping_pairs (x:xs@(y:_)) = (x,y) : overlapping_pairs xs
{-# INLINE getSwaps #-}
-- | Get a lazy list of swaps equivalent to the inverse of a permutation.
getInvSwaps :: (MPermute p m) => p -> m [(Int,Int)]
getInvSwaps = getSwapsHelp pairs_withstart
where
pairs_withstart [] = error "Empty cycle"
pairs_withstart (x:xs) = [(x,y) | y <- xs]
{-# INLINE getInvSwaps #-}
getSwapsHelp :: (MPermute p m) => ([Int] -> [(Int, Int)]) -> p -> m [(Int,Int)]
getSwapsHelp swapgen p = do
liftM (concatMap swapgen) $ getCycles p
{-# INLINE getSwapsHelp #-}
-- | @getCycleFrom p i@ gets the list of elements reachable from @i@
-- by repeated application of @p@.
getCycleFrom :: (MPermute p m) => p -> Int -> m [Int]
getCycleFrom p i =
liftM (i:) $ go i
where
go j = unsafeInterleaveM $ do
next <- unsafeGetElem p j
if next == i
then return []
else liftM (next:) $ go next
{-# INLINE getCycleFrom #-}
-- | @getCycles p@ returns the list of disjoin cycles in @p@.
getCycles :: (MPermute p m) => p -> m [[Int]]
getCycles p = do
n <- getSize p
go n 0
where
go n i | i == n = return []
| otherwise = unsafeInterleaveM $ do
least <- isLeast i i
if least
then do
c <- getCycleFrom p i
liftM (c:) $ go n (i+1)
else go n (i+1)
isLeast i j = do
k <- unsafeGetElem p j
case compare i k of
LT -> isLeast i k
EQ -> return True
GT -> return False
{-# INLINE getCycles #-}
-- | Whether or not the permutation is made from an even number of swaps
getIsEven :: (MPermute p m) => p -> m Bool
getIsEven p = do
liftM (even . length) $ getSwaps p
-- | @getPeriod p@ - The first power of @p@ that is the identity permutation
getPeriod :: (MPermute p m) => p -> m Integer
getPeriod p = do
cycles <- getCycles p
let lengths = map List.genericLength cycles
return $ List.foldl' lcm 1 lengths
-- | Convert a mutable permutation to an immutable one.
freeze :: (MPermute p m) => p -> m Permute
freeze p = unsafeFreeze =<< newCopyPermute p
{-# INLINE freeze #-}
-- | Convert an immutable permutation to a mutable one.
thaw :: (MPermute p m) => Permute -> m p
thaw p = newCopyPermute =<< unsafeThaw p
{-# INLINE thaw #-}
-- | @getSort n xs@ sorts the first @n@ elements of @xs@ and returns a
-- permutation which transforms @xs@ into sorted order. The results are
-- undefined if @n@ is greater than the length of @xs@. This is a special
-- case of 'getSortBy'.
getSort :: (Ord a, MPermute p m) => Int -> [a] -> m ([a], p)
getSort = getSortBy compare
{-# INLINE getSort #-}
getSortBy :: (MPermute p m) => (a -> a -> Ordering) -> Int -> [a] -> m ([a], p)
getSortBy cmp n xs =
let ys = take n xs
(is,ys') = (unzip . List.sortBy (cmp `on` snd) . zip [0..]) ys
in liftM ((,) ys') $ unsafeNewListPermute n is
{-# INLINE getSortBy #-}
-- | @getOrder n xs@ returns a permutation which rearranges the first @n@
-- elements of @xs@ into ascending order. The results are undefined if @n@ is
-- greater than the length of @xs@. This is a special case of 'getOrderBy'.
getOrder :: (Ord a, MPermute p m) => Int -> [a] -> m p
getOrder = getOrderBy compare
{-# INLINE getOrder #-}
getOrderBy :: (MPermute p m) => (a -> a -> Ordering) -> Int -> [a] -> m p
getOrderBy cmp n xs =
liftM snd $ getSortBy cmp n xs
{-# INLINE getOrderBy #-}
-- | @getRank n xs@ eturns a permutation, the inverse of which rearranges the
-- first @n@ elements of @xs@ into ascending order. The returned permutation,
-- @p@, has the property that @p[i]@ is the rank of the @i@th element of @xs@.
-- The results are undefined if @n@ is greater than the length of @xs@.
-- This is a special case of 'getRankBy'.
getRank :: (Ord a, MPermute p m) => Int -> [a] -> m p
getRank = getRankBy compare
{-# INLINE getRank #-}
getRankBy :: (MPermute p m) => (a -> a -> Ordering) -> Int -> [a] -> m p
getRankBy cmp n xs = do
p <- getOrderBy cmp n xs
getInverse p
{-# INLINE getRankBy #-}
--------------------------------- Instances ---------------------------------
instance MPermute (STPermute s) (ST s) where
getSize = getSizeSTPermute
{-# INLINE getSize #-}
newPermute = newSTPermute
{-# INLINE newPermute #-}
newPermute_ = newSTPermute_
{-# INLINE newPermute_ #-}
unsafeGetElem = unsafeGetElemSTPermute
{-# INLINE unsafeGetElem #-}
unsafeSetElem = unsafeSetElemSTPermute
{-# INLINE unsafeSetElem #-}
unsafeSwapElems = unsafeSwapElemsSTPermute
{-# INLINE unsafeSwapElems #-}
getElems = getElemsSTPermute
{-# INLINE getElems #-}
setElems = setElemsSTPermute
{-# INLINE setElems #-}
unsafeFreeze = unsafeFreezeSTPermute
{-# INLINE unsafeFreeze #-}
unsafeThaw = unsafeThawSTPermute
{-# INLINE unsafeThaw #-}
unsafeInterleaveM = unsafeInterleaveST
{-# INLINE unsafeInterleaveM #-}
instance MPermute IOPermute IO where
getSize = getSizeIOPermute
{-# INLINE getSize #-}
newPermute = newIOPermute
{-# INLINE newPermute #-}
newPermute_ = newIOPermute_
{-# INLINE newPermute_ #-}
unsafeGetElem = unsafeGetElemIOPermute
{-# INLINE unsafeGetElem #-}
unsafeSetElem = unsafeSetElemIOPermute
{-# INLINE unsafeSetElem #-}
unsafeSwapElems = unsafeSwapElemsIOPermute
{-# INLINE unsafeSwapElems #-}
getElems = getElemsIOPermute
{-# INLINE getElems #-}
setElems = setElemsIOPermute
{-# INLINE setElems #-}
unsafeFreeze = unsafeFreezeIOPermute
{-# INLINE unsafeFreeze #-}
unsafeThaw = unsafeThawIOPermute
{-# INLINE unsafeThaw #-}
unsafeInterleaveM = unsafeInterleaveIO
{-# INLINE unsafeInterleaveM #-}
|
patperry/permutation
|
lib/Data/Permute/MPermute.hs
|
Haskell
|
bsd-3-clause
| 17,466
|
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- | Interface for GraphQL API.
--
-- __Note__: This module is highly subject to change. We're still figuring
-- where to draw the lines and what to expose.
module GraphQL
(
-- * Running queries
interpretQuery
, interpretAnonymousQuery
, Response(..)
-- * Preparing queries then running them
, makeSchema
, compileQuery
, executeQuery
, QueryError
, Schema
, VariableValues
, Value
) where
import Protolude
import Data.Attoparsec.Text (parseOnly, endOfInput)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import GraphQL.API (HasObjectDefinition(..), Object, SchemaError(..))
import GraphQL.Internal.Execution
( VariableValues
, ExecutionError
, substituteVariables
)
import qualified GraphQL.Internal.Execution as Execution
import qualified GraphQL.Internal.Syntax.AST as AST
import qualified GraphQL.Internal.Syntax.Parser as Parser
import GraphQL.Internal.Validation
( QueryDocument
, SelectionSetByType
, ValidationErrors
, validate
, getSelectionSet
, VariableValue
)
import GraphQL.Internal.Output
( GraphQLError(..)
, Response(..)
, singleError
)
import GraphQL.Internal.Schema (Schema)
import qualified GraphQL.Internal.Schema as Schema
import GraphQL.Resolver
( HasResolver(..)
, OperationResolverConstraint
, Result(..)
, resolveOperation
)
import GraphQL.Value (Name, Value)
-- | Errors that can happen while processing a query document.
data QueryError
-- | Failed to parse.
= ParseError Text
-- | Parsed, but failed validation.
--
-- See <https://facebook.github.io/graphql/#sec-Validation> for more
-- details.
| ValidationError ValidationErrors
-- | Validated, but failed during execution.
| ExecutionError ExecutionError
-- | Error in the schema.
| SchemaError SchemaError
-- | Got a value that wasn't an object.
| NonObjectResult Value
deriving (Eq, Show)
instance GraphQLError QueryError where
formatError (ParseError e) =
"Couldn't parse query document: " <> e
formatError (ValidationError es) =
"Validation errors:\n" <> mconcat [" " <> formatError e <> "\n" | e <- NonEmpty.toList es]
formatError (ExecutionError e) =
"Execution error: " <> show e
formatError (SchemaError e) =
"Schema error: " <> formatError e
formatError (NonObjectResult v) =
"Query returned a value that is not an object: " <> show v
-- | Execute a GraphQL query.
executeQuery
:: forall api m fields typeName interfaces.
( Object typeName interfaces fields ~ api
, OperationResolverConstraint m fields typeName interfaces
)
=> Handler m api -- ^ Handler for the query. This links the query to the code you've written to handle it.
-> QueryDocument VariableValue -- ^ A validated query document. Build one with 'compileQuery'.
-> Maybe Name -- ^ An optional name. If 'Nothing', then executes the only operation in the query. If @Just "something"@, executes the query named @"something".
-> VariableValues -- ^ Values for variables defined in the query document. A map of 'Variable' to 'Value'.
-> m Response -- ^ The outcome of running the query.
executeQuery handler document name variables =
case getOperation document name variables of
Left e -> pure (ExecutionFailure (singleError e))
Right operation ->
toResult
<$> resolveOperation @m @fields @typeName @interfaces handler operation
where
toResult (Result errors object) =
case NonEmpty.nonEmpty errors of
Nothing -> Success object
Just errs -> PartialSuccess object (map toError errs)
-- | Create a GraphQL schema.
makeSchema :: forall api. HasObjectDefinition api => Either QueryError Schema
makeSchema = first SchemaError (Schema.makeSchema <$> getDefinition @api)
-- | Interpet a GraphQL query.
--
-- Compiles then executes a GraphQL query.
interpretQuery
:: forall api m fields typeName interfaces.
( Object typeName interfaces fields ~ api
, OperationResolverConstraint m fields typeName interfaces
)
=> Handler m api -- ^ Handler for the query. This links the query to the code you've written to handle it.
-> Text -- ^ The text of a query document. Will be parsed and then executed.
-> Maybe Name -- ^ An optional name for the operation within document to run. If 'Nothing', execute the only operation in the document. If @Just "something"@, execute the query or mutation named @"something"@.
-> VariableValues -- ^ Values for variables defined in the query document. A map of 'Variable' to 'Value'.
-> m Response -- ^ The outcome of running the query.
interpretQuery handler query name variables =
case makeSchema @api >>= flip compileQuery query of
Left err -> pure (PreExecutionFailure (toError err :| []))
Right document -> executeQuery @api @m handler document name variables
-- | Interpret an anonymous GraphQL query.
--
-- Anonymous queries have no name and take no variables.
interpretAnonymousQuery
:: forall api m fields typeName interfaces.
( Object typeName interfaces fields ~ api
, OperationResolverConstraint m fields typeName interfaces
)
=> Handler m api -- ^ Handler for the anonymous query.
-> Text -- ^ The text of the anonymous query. Should defined only a single, unnamed query operation.
-> m Response -- ^ The result of running the query.
interpretAnonymousQuery handler query = interpretQuery @api @m handler query Nothing mempty
-- | Turn some text into a valid query document.
compileQuery :: Schema -> Text -> Either QueryError (QueryDocument VariableValue)
compileQuery schema query = do
parsed <- first ParseError (parseQuery query)
first ValidationError (validate schema parsed)
-- | Parse a query document.
parseQuery :: Text -> Either Text AST.QueryDocument
parseQuery query = first toS (parseOnly (Parser.queryDocument <* endOfInput) query)
-- | Get an operation from a query document ready to be processed.
getOperation :: QueryDocument VariableValue -> Maybe Name -> VariableValues -> Either QueryError (SelectionSetByType Value)
getOperation document name vars = first ExecutionError $ do
op <- Execution.getOperation document name
resolved <- substituteVariables op vars
pure (getSelectionSet resolved)
|
jml/graphql-api
|
src/GraphQL.hs
|
Haskell
|
bsd-3-clause
| 6,404
|
module QueryArrow.BuiltIn where
import System.IO (FilePath, readFile)
import Text.Read (readMaybe)
import QueryArrow.Syntax.Term
import QueryArrow.Syntax.Type
standardBuiltInPreds = [
Pred (UQPredName "le") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type]),
Pred (UQPredName "lt") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type]),
Pred (UQPredName "eq") (PredType ObjectPred [ParamType True True False False (TypeVar "a"), ParamType False True True False (TypeVar "a")]),
Pred (UQPredName "ge") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type]),
Pred (UQPredName "gt") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type]),
Pred (UQPredName "ne") (PredType ObjectPred [ParamType True True False False (TypeVar "a"), ParamType True True False False (TypeVar "a")]),
Pred (UQPredName "like") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False TextType]),
Pred (UQPredName "not_like") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False TextType]),
Pred (UQPredName "like_regex") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False TextType]),
Pred (UQPredName "not_like_regex") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False TextType]),
Pred (UQPredName "in") (PredType ObjectPred [ParamType True True False False (TypeVar "a"), ParamType True True False False (ListType (TypeVar "a"))]),
Pred (UQPredName "add") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type, ParamType False False True False Int64Type]),
Pred (UQPredName "sub") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type, ParamType False False True False Int64Type]),
Pred (UQPredName "mul") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type, ParamType False False True False Int64Type]),
Pred (UQPredName "div") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type, ParamType False False True False Int64Type]),
Pred (UQPredName "mod") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type, ParamType False False True False Int64Type]),
Pred (UQPredName "exp") (PredType ObjectPred [ParamType True True False False Int64Type, ParamType True True False False Int64Type, ParamType False False True False Int64Type]),
Pred (UQPredName "concat") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False TextType, ParamType False False True False TextType]),
Pred (UQPredName "substr") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False Int64Type, ParamType True True False False Int64Type, ParamType False False True False TextType]),
Pred (UQPredName "regex_replace") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False TextType, ParamType True True False False TextType, ParamType False False True False TextType]),
Pred (UQPredName "replace") (PredType ObjectPred [ParamType True True False False TextType, ParamType True True False False TextType, ParamType True True False False TextType, ParamType False False True False TextType]),
Pred (UQPredName "strlen") (PredType ObjectPred [ParamType True True False False TextType, ParamType False False True False Int64Type])
]
standardBuiltInPredsMap = constructPredMap standardBuiltInPreds
qStandardBuiltInPreds :: String -> [Pred]
qStandardBuiltInPreds ns = map (setPredNamespace ns) standardBuiltInPreds
qStandardBuiltInPredsMap ns = constructPredMap (qStandardBuiltInPreds ns)
|
xu-hao/QueryArrow
|
QueryArrow-common/src/QueryArrow/BuiltIn.hs
|
Haskell
|
bsd-3-clause
| 4,200
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module EFA.Utility.List where
vhead :: String -> [a] -> a
vhead _ (x:_) = x
vhead caller _ = error $ "vhead, " ++ caller ++ ": empty list"
vlast :: String -> [a] -> a
vlast _ xs@(_:_) = last xs
vlast caller _ = error $ "vlast, " ++ caller ++ ": empty list"
-- | Example
--
-- >>> takeUntil (>5) [1..10]
-- [1,2,3,4,5,6]
takeUntil :: (a -> Bool) -> [a] -> [a]
takeUntil p = go
where go (x:xs) = x : if not (p x) then go xs else []
go [] = []
|
energyflowanalysis/efa-2.1
|
src/EFA/Utility/List.hs
|
Haskell
|
bsd-3-clause
| 531
|
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PolyKinds #-}
module Rules.Kind.Infer.Offline (
UnifyT
, IKOffline
) where
import Control.Monad (unless)
import Data.Foldable (toList)
import Data.List (tails)
import Data.Proxy (Proxy(..))
import Bound (Bound)
import Control.Monad.Error.Lens (throwing)
import Control.Monad.Except (MonadError)
import Control.Monad.Writer (MonadWriter(..), WriterT, execWriterT, runWriterT)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as N
import qualified Data.Map as M
import Data.Bitransversable
import Data.Functor.Rec
import Ast.Kind
import Ast.Type
import Ast.Error.Common
import Context.Type.Error
import Rules.Unification
import Rules.Kind.Infer.Common
type UnifyT ki a = WriterT [UConstraint (Kind ki) a]
mkInferKind' :: (UnificationContext e m (Kind ki) a, MonadError e m)
=> (Type ki ty a -> UnifyT ki a m (Kind ki a))
-> ([UConstraint (Kind ki) a] -> m (M.Map a (Kind ki a)))
-> Type ki ty a
-> m (Kind ki a)
mkInferKind' go unifyFn x = do
(ty, cs) <- runWriterT $ go x
s <- unifyFn cs
return $ mapSubst _KiVar s ty
data IKOffline
mkCheck' :: MkInferKindConstraint e w s r m ki ty a IKOffline
=> Proxy (MonadProxy e w s r m)
-> (Type ki ty a -> UnifyT ki a m (Kind ki a))
-> ([UConstraint (Kind ki) a] -> m (M.Map a (Kind ki a)))
-> Type ki ty a
-> Kind ki a
-> m ()
mkCheck' m inferFn unifyFn x y = do
cs <- execWriterT $ (mkCheckKind m (Proxy :: Proxy ki) (Proxy :: Proxy ty) (Proxy :: Proxy a) (Proxy :: Proxy IKOffline) inferFn) x y
_ <- unifyFn cs
return ()
instance MkInferKind IKOffline where
type MkInferKindConstraint e w s r m ki ty a IKOffline =
( MonadError e m
, AsUnknownKindError e
, AsOccursError e (Kind ki) a
, AsUnificationMismatch e (Kind ki) a
, AsUnificationExpectedEq e (Kind ki) a
, AsUnboundTypeVariable e a
, Ord a
, OrdRec ki
, OrdRec (ty ki)
, Bound ki
, Bitransversable ki
, Bound (ty ki)
, Bitransversable (ty ki)
)
type InferKindMonad m ki a IKOffline =
UnifyT ki a m
type MkInferKindErrorList ki ty a IKOffline =
'[ ErrOccursError (Kind ki) a
, ErrUnificationMismatch (Kind ki) a
, ErrUnificationExpectedEq (Kind ki) a
, ErrUnificationExpectedEq (Type ki ty) a
, ErrUnboundTypeVariable a
]
type MkInferKindWarningList ki ty a IKOffline =
'[]
mkCheckKind m ki ty a i =
mkCheckKind' i (expectKind m ki ty a i)
expectKind _ _ _ _ _ (ExpectedKind ki1) (ActualKind ki2) =
unless (ki1 == ki2) $
tell [UCEq ki1 ki2]
expectKindEq _ _ _ _ _ ki1 ki2 =
unless (ki1 == ki2) $
tell [UCEq ki1 ki2]
expectKindAllEq _ _ _ _ _ n@(ki :| kis) = do
unless (all (== ki) kis) $
let
xss = tails . N.toList $ n
f [] = []
f (x : xs) = fmap (UCEq x) xs
ws = xss >>= f
in
tell ws
return ki
prepareInferKind pm pki pty pa pi kri =
let
u = mkUnify _KiVar id . kriUnifyRules $ kri
i = mkInferKind . kriInferRules $ kri
convertKind k =
case toList k of
[] -> return k
(x : _) -> throwing _UnboundTypeVariable x
i' = (>>= convertKind) . mkInferKind' i u
c = mkCheck' pm i u
in
InferKindOutput i' c
|
dalaing/type-systems
|
src/Rules/Kind/Infer/Offline.hs
|
Haskell
|
bsd-3-clause
| 3,672
|
{-# LANGUAGE ExistentialQuantification #-}
module Data.IORef.ReadWrite
( ReadWriteIORef
, toReadWriteIORef
) where
import Data.Bifunctor (first)
import Data.IORef (IORef)
import Data.IORef.Class
data ReadWriteIORef a = forall b. ReadWriteIORef (IORef b) (a -> b) (b -> a)
toReadWriteIORef :: IORef a -> ReadWriteIORef a
toReadWriteIORef ref = ReadWriteIORef ref id id
instance IORefRead ReadWriteIORef where
readIORef (ReadWriteIORef ref _ g) = g <$> readIORef ref
{-# INLINE readIORef #-}
instance IORefWrite ReadWriteIORef where
writeIORef (ReadWriteIORef ref f _) a = writeIORef ref (f a)
{-# INLINE writeIORef #-}
atomicWriteIORef (ReadWriteIORef ref f _) a = atomicWriteIORef ref (f a)
{-# INLINE atomicWriteIORef #-}
instance IORefReadWrite ReadWriteIORef where
modifyIORef (ReadWriteIORef ref f g) h = modifyIORef ref (f . h . g)
{-# INLINE modifyIORef #-}
modifyIORef' (ReadWriteIORef ref f g) h = modifyIORef' ref (f . h . g)
{-# INLINE modifyIORef' #-}
atomicModifyIORef (ReadWriteIORef ref f g) h = atomicModifyIORef ref $ first f . h . g
{-# INLINE atomicModifyIORef #-}
atomicModifyIORef' (ReadWriteIORef ref f g) h = atomicModifyIORef' ref $ first f . h . g
{-# INLINE atomicModifyIORef' #-}
|
osa1/privileged-concurrency
|
Data/IORef/ReadWrite.hs
|
Haskell
|
bsd-3-clause
| 1,251
|
module Main where
main :: IO ()
main = print $ length ('a', 'b')
|
stepcut/safe-length
|
example/BrokenTuple.hs
|
Haskell
|
bsd-3-clause
| 66
|
module Main where
import Control.Lens
import Numeric.Lens (binary, negated, adding)
import Test.Tasty (TestTree, defaultMain, testGroup)
import Test.Tasty.ExpectedFailure (allowFail)
import Test.DumbCheck -- (TestTree, defaultMain, testGroup)
import qualified Test.Tasty.Lens.Iso as Iso
import qualified Test.Tasty.Lens.Lens as Lens
import qualified Test.Tasty.Lens.Prism as Prism
main :: IO ()
main = defaultMain $ testGroup "Lens tests"
[ tupleTests
, maybeTests
, numTests
]
tupleTests :: TestTree
tupleTests = testGroup "Tuples"
[ testGroup "_1"
[ testGroup "Lens' (Char,Char) Char"
[ Lens.test (_1 :: Lens' (Char,Char) Char) ]
, testGroup "Lens' (Int,Char) Int"
[ Lens.test (_1 :: Lens' (Int,Char) Int) ]
]
, testGroup "_2"
[ testGroup "Lens' (Char,Char,Char) Char"
[ Lens.test (_2 :: Lens' (Char,Char,Char) Char) ]
]
]
maybeTests :: TestTree
maybeTests = testGroup "Maybe"
[ testGroup "_Nothing"
[ testGroup "Prism' (Maybe Char) ()"
[ Prism.test (_Nothing :: Prism' (Maybe Char) ()) ]
, testGroup "Prism' (Maybe Int) ()"
[ Prism.test (_Nothing :: Prism' (Maybe Int) ()) ]
]
, testGroup "_Just"
[ testGroup "Prism' (Maybe Char) Char"
[ Prism.test (_Just :: Prism' (Maybe Char) Char) ]
, testGroup "Prism' (Maybe Int) Int"
[ Prism.test (_Just :: Prism' (Maybe Int) Int) ]
]
]
type AlphaNumString = [AlphaNum]
numTests :: TestTree
numTests = testGroup "Numeric"
[ testGroup "negated"
[ testGroup "Iso' Int Int"
[ Iso.test (negated :: Iso' Int Int) ]
, testGroup "Iso' Float Float"
[ Iso.test (negated :: Iso' Float Float) ]
]
, testGroup "binary"
[ testGroup "Prism'' String Int"
[ allowFail $ Prism.test
(_AlphaNumString . (binary :: Prism' String Int)) ]
, testGroup "Prism'' String Integer"
[ Prism.test (binary :: Prism' String Integer) ]
]
, testGroup "adding"
[ testGroup "Iso' Int Int"
[ Iso.test (adding 2 :: Iso' Int Int) ]
, testGroup "Iso' Integer Integer"
[ Iso.test (adding 3 :: Iso' Integer Integer) ]
]
]
where
_AlphaNumString :: Iso' AlphaNumString String
_AlphaNumString = iso (fmap unAlphaNum) (fmap AlphaNum)
|
jdnavarro/tasty-lens
|
tests/tasty.hs
|
Haskell
|
bsd-3-clause
| 2,255
|
{-# LANGUAGE BangPatterns #-}
-- need a fast way to represent a sudo puzzle
-- use vector reference: https://wiki.haskell.org/Numeric_Haskell:_A_Vector_Tutorial
-- * End users should use Data.Vector.Unboxed for most cases
-- * If you need to store more complex structures, use Data.Vector
-- * If you need to pass to C, use Data.Vector.Storable
import qualified Data.Vector as V
import System.Environment
-- import Data.ByteString.Lazy.Char8 as BL
import Data.List (partition, intersect, nub)
data Cell = Unique Int | Choice [Int] deriving (Eq)
newtype Puzzle = Puzzle (V.Vector (V.Vector Cell))
-- for this simple solution, I should just use Array. and make Cell = Int is enough
instance Show Cell where
show (Unique n) = show n
show (Choice _) = "0"
instance Show Puzzle where
show puz = unlines . map (concatMap show) . puzzleToList $ puz
listToPuzzle :: [[Int]] -> Puzzle
listToPuzzle xs = Puzzle . V.fromList . map change $ xs
where change = V.fromList . map parse
parse 0 = Choice [1..9]
parse n = Unique n
puzzleToList :: Puzzle -> [[Cell]]
puzzleToList (Puzzle puz) = V.toList . (V.map V.toList) $ puz
index :: Int -> Int -> Puzzle -> Cell
index i j (Puzzle puz) = (puz V.! i) V.! j
indexCol i puz = [index i j puz | j <- [0..8]]
indexRow j puz = [index i j puz | i <- [0..8]]
indexTri i puz = [index x y puz | x <- sets !! i' , y <- sets !! j']
where (i', j') = divMod i 3
sets = [[0,1,2],[3,4,5],[6,7,8]]
isLegal :: Puzzle -> Bool
isLegal puz = all legal [indexCol i puz | i <- [0..8]]
&& all legal [indexRow i puz | i <- [0..8]]
&& all legal [indexTri i puz | i <- [0..8]]
where legal :: [Cell] -> Bool
legal xs =
let (uni, choices) = partition par xs
par (Unique _) = True
par _ = False
uni' = map (\(Unique x) -> x) uni
choices' = concatMap (\(Choice ys) -> ys) choices
in length uni == length (nub uni) -- rest check not used for solution 1 && null (intersect uni' choices')
isFinish :: Puzzle -> Bool
isFinish (Puzzle puz) = V.all id . V.map (V.all par) $ puz
where par (Unique _) = True
par _ = False
update :: Puzzle -> ((Int, Int), Cell) -> Puzzle
update (Puzzle puz) ((m, n), x) = Puzzle (puz V.// [(m, inner)])
where inner = puz V.! m
inner' = inner V.// [(n, x)]
solution :: Puzzle -> Maybe Puzzle
solution puz = walk puz 0
where
walk puz 81 = if isFinish puz then Just puz else Nothing
walk puz num =
let
(m, n) = divMod num 9
cell = index m n puz
isUnique = case cell of
Unique _ -> True
_ -> False
in if isUnique
then walk puz (num+1)
else go puz m n 1
go _ _ _ 10 = Nothing
go puz m n x =
let out = update puz ((m, n), Unique x)
in if isLegal out
then case walk out (m*9+n+1) of
Just puz' -> Just puz'
Nothing -> go puz m n (x+1)
else go puz m n (x+1)
parseString :: String -> [[Int]]
parseString = map (map (read . (:[]))) . lines
-- main :: IO ()
main = do
content <- readFile "data"
let puz = listToPuzzle $ parseString content
print $ solution puz
-- Why these function alawys give answer to sudoku problem?
-- because it is actually traverse all possible combination for the problem.
-- a brute algorithm, which take a lot of time
|
niexshao/Exercises
|
src/Euler96-Sudoku/sudoku1.hs
|
Haskell
|
bsd-3-clause
| 3,446
|
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Xmobar.Plugins.Monitors
-- Copyright : (c) 2010, 2011, 2012, 2013 Jose Antonio Ortega Ruiz
-- (c) 2007-10 Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability : unstable
-- Portability : unportable
--
-- The system monitor plugin for Xmobar.
--
-----------------------------------------------------------------------------
module Plugins.Monitors where
import Plugins
import Plugins.Monitors.Common (runM, runMD)
import Plugins.Monitors.Weather
import Plugins.Monitors.Net
import Plugins.Monitors.Mem
import Plugins.Monitors.Swap
import Plugins.Monitors.Cpu
import Plugins.Monitors.MultiCpu
import Plugins.Monitors.Batt
import Plugins.Monitors.Bright
import Plugins.Monitors.Thermal
import Plugins.Monitors.ThermalZone
import Plugins.Monitors.CpuFreq
import Plugins.Monitors.CoreTemp
import Plugins.Monitors.Disk
import Plugins.Monitors.Top
import Plugins.Monitors.Uptime
#ifdef IWLIB
import Plugins.Monitors.Wireless
#endif
#ifdef LIBMPD
import Plugins.Monitors.MPD
import Plugins.Monitors.Common (runMBD)
#endif
#ifdef ALSA
import Plugins.Monitors.Volume
#endif
#ifdef MPRIS
import Plugins.Monitors.Mpris
#endif
data Monitors = Weather Station Args Rate
| Network Interface Args Rate
| DynNetwork Args Rate
| BatteryP Args Args Rate
| BatteryN Args Args Rate Alias
| Battery Args Rate
| DiskU DiskSpec Args Rate
| DiskIO DiskSpec Args Rate
| Thermal Zone Args Rate
| ThermalZone ZoneNo Args Rate
| Memory Args Rate
| Swap Args Rate
| Cpu Args Rate
| MultiCpu Args Rate
| Brightness Args Rate
| CpuFreq Args Rate
| CoreTemp Args Rate
| TopProc Args Rate
| TopMem Args Rate
| Uptime Args Rate
#ifdef IWLIB
| Wireless Interface Args Rate
#endif
#ifdef LIBMPD
| MPD Args Rate
| AutoMPD Args
#endif
#ifdef ALSA
| Volume String String Args Rate
#endif
#ifdef MPRIS
| Mpris1 String Args Rate
| Mpris2 String Args Rate
#endif
deriving (Show,Read,Eq)
type Args = [String]
type Program = String
type Alias = String
type Station = String
type Zone = String
type ZoneNo = Int
type Interface = String
type Rate = Int
type DiskSpec = [(String, String)]
instance Exec Monitors where
alias (Weather s _ _) = s
alias (Network i _ _) = i
alias (DynNetwork _ _) = "dynnetwork"
alias (Thermal z _ _) = z
alias (ThermalZone z _ _) = "thermal" ++ show z
alias (Memory _ _) = "memory"
alias (Swap _ _) = "swap"
alias (Cpu _ _) = "cpu"
alias (MultiCpu _ _) = "multicpu"
alias (Battery _ _) = "battery"
alias (BatteryP _ _ _)= "battery"
alias (BatteryN _ _ _ a)= a
alias (Brightness _ _) = "bright"
alias (CpuFreq _ _) = "cpufreq"
alias (TopProc _ _) = "top"
alias (TopMem _ _) = "topmem"
alias (CoreTemp _ _) = "coretemp"
alias (DiskU _ _ _) = "disku"
alias (DiskIO _ _ _) = "diskio"
alias (Uptime _ _) = "uptime"
#ifdef IWLIB
alias (Wireless i _ _) = i ++ "wi"
#endif
#ifdef LIBMPD
alias (MPD _ _) = "mpd"
alias (AutoMPD _) = "autompd"
#endif
#ifdef ALSA
alias (Volume m c _ _) = m ++ ":" ++ c
#endif
#ifdef MPRIS
alias (Mpris1 _ _ _) = "mpris1"
alias (Mpris2 _ _ _) = "mpris2"
#endif
start (Network i a r) = startNet i a r
start (DynNetwork a r) = startDynNet a r
start (Cpu a r) = startCpu a r
start (MultiCpu a r) = startMultiCpu a r
start (TopProc a r) = startTop a r
start (TopMem a r) = runM a topMemConfig runTopMem r
start (Weather s a r) = runMD (a ++ [s]) weatherConfig runWeather r weatherReady
start (Thermal z a r) = runM (a ++ [z]) thermalConfig runThermal r
start (ThermalZone z a r) =
runM (a ++ [show z]) thermalZoneConfig runThermalZone r
start (Memory a r) = runM a memConfig runMem r
start (Swap a r) = runM a swapConfig runSwap r
start (Battery a r) = runM a battConfig runBatt r
start (BatteryP s a r) = runM a battConfig (runBatt' s) r
start (BatteryN s a r _) = runM a battConfig (runBatt' s) r
start (Brightness a r) = runM a brightConfig runBright r
start (CpuFreq a r) = runM a cpuFreqConfig runCpuFreq r
start (CoreTemp a r) = runM a coreTempConfig runCoreTemp r
start (DiskU s a r) = runM a diskUConfig (runDiskU s) r
start (DiskIO s a r) = startDiskIO s a r
start (Uptime a r) = runM a uptimeConfig runUptime r
#ifdef IWLIB
start (Wireless i a r) = runM (a ++ [i]) wirelessConfig runWireless r
#endif
#ifdef LIBMPD
start (MPD a r) = runMD a mpdConfig runMPD r mpdReady
start (AutoMPD a) = runMBD a mpdConfig runMPD mpdWait mpdReady
#endif
#ifdef ALSA
start (Volume m c a r) = runM a volumeConfig (runVolume m c) r
#endif
#ifdef MPRIS
start (Mpris1 s a r) = runM a mprisConfig (runMPRIS1 s) r
start (Mpris2 s a r) = runM a mprisConfig (runMPRIS2 s) r
#endif
|
apoikos/pkg-xmobar
|
src/Plugins/Monitors.hs
|
Haskell
|
bsd-3-clause
| 5,554
|
{-# LANGUAGE RecordWildCards #-}
module Helper
( emptyEnv
, newUserAct
, midnight
, stubRunner
, stubCommand
, addUser
, createEnv
, createUser
, createPost
, stubUsers
, secAfterMidnight
, usersEnv
, newSysAct
) where
import Types
import qualified Data.Map.Lazy as Map (insert, empty, fromList)
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock
import Env
emptyEnv :: Env
emptyEnv = createEnv (Map.empty, Map.empty, midnight)
usersEnv :: Env
usersEnv = createEnv (Map.empty, stubUsers, secAfterMidnight 250)
newSysAct :: String -> UTCTime -> Action
newSysAct xs t = SystemAct { sysAct = xs, sysTime = t }
newUserAct :: String -> String -> String -> UTCTime -> Action
newUserAct n act args t = UserAct { userName = n
, action = act
, args = args
, time = t }
createEnv :: (Commands, Users, UTCTime) -> Env
createEnv (c, u, t) = Env
{ cmds = c
, users = u
, eTime = t }
midnight :: UTCTime
midnight = UTCTime (fromGregorian 2017 1 1) 0
stubRunner :: ActionRunner
stubRunner a = return ""
stubCommand :: Command
stubCommand = Cmd { cmd = "stub", runner = stubRunner, desc = "a stub command"}
addUser :: User -> Env -> Env
addUser u@User{..} e@Env{..} = e { users = Map.insert name u users}
createUser :: (String, [Post], [String]) -> User
createUser (n, ps, fs) = User
{ name = n
, posts = ps
, followings = fs }
createPost :: (String, String, UTCTime) -> Post
createPost (u, m, d) = Post
{ user = u
, msg = m
, date = d }
stubUsers :: Users
stubUsers = Map.fromList $ zip ["foo", "bob", "alice"] users
where users = map createUser [ ("foo", fooPosts, ["bob", "alice"])
, ("bob", bobPosts, ["alice"])
, ("alice", alicePosts, ["foo"]) ]
fooPosts :: [Post]
fooPosts = map createPost [ ("foo", "ruuun", secAfterMidnight 200)
, ("foo", "goooo", secAfterMidnight 210)
, ("foo", "get to the choppaaa!", secAfterMidnight 220) ]
bobPosts :: [Post]
bobPosts = map createPost [ ("bob", "hello!", secAfterMidnight 10)
, ("bob", "I'm batman", secAfterMidnight 20)
, ("bob", "you ok bro?", secAfterMidnight 215) ]
alicePosts :: [Post]
alicePosts = map createPost [ ("alice", "I like dogs", midnight) ]
secAfterMidnight :: Integer -> UTCTime
secAfterMidnight = UTCTime (fromGregorian 2017 1 1) . secondsToDiffTime
|
lpalma/hamerkop
|
test/Helper.hs
|
Haskell
|
bsd-3-clause
| 2,747
|
-- | Collection of types (@Proc_*@ types and others), and
-- some functions on these types as well.
module Graphics.Web.Processing.Core.Types (
-- * Processing Script
ProcScript (..)
, emptyScript
-- ** Script rendering
, renderScript
, renderFile
-- ** Processing Code
, ProcCode
-- * Contexts
, Preamble (..)
, Setup (..)
, Draw (..)
, MouseClicked (..)
, MouseReleased (..)
, KeyPressed (..)
-- * @Proc_*@ types
, ProcType
-- ** Bool
, Proc_Bool, true, false
, fromBool
, pnot, (#||), (#&&)
-- ** Int
, Proc_Int
, fromInt
, intToFloat
-- ** Float
, Proc_Float
, fromFloat
, pfloor
, pround
-- ** Char
, Proc_Char
, fromChar
-- ** Text
, Proc_Text
, fromStText
, (+.+)
, Proc_Show (..)
-- ** Image
, Proc_Image
-- * Processing classes
, Proc_Eq (..)
, Proc_Ord (..)
-- * Conditional values
, if_
) where
import Graphics.Web.Processing.Core.Primal
import Text.PrettyPrint.Mainland
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy.IO as T
charsPerLine :: Int
charsPerLine = 80
-- | Render a script as a lazy 'Text'.
renderScript :: ProcScript -> Text
renderScript = prettyLazyText charsPerLine . ppr
-- | Render a script using 'renderScript' and
-- write it directly in a file.
renderFile :: FilePath -> ProcScript -> IO ()
renderFile fp = T.writeFile fp . renderScript
-- | Conditional value. For example:
--
-- > if_ (x #> 3) "X is greater than 3."
-- > "X is less than or equal to 3."
--
if_ :: ProcType a => Proc_Bool -> a -> a -> a
if_ = proc_cond
|
Daniel-Diaz/processing
|
Graphics/Web/Processing/Core/Types.hs
|
Haskell
|
bsd-3-clause
| 1,582
|
module MakeTerm where
import BruijnTerm
import Value
import Name
val :: Value -> LamTerm () () n
val = Val ()
var :: String -> LamTerm () () Name
var = Var () . fromString
double :: Double -> LamTerm () () n
double = Val () . Prim . MyDouble
true :: LamTerm () () n
true = Val () $ Prim $ MyBool True
false :: LamTerm () () n
false = Val () $ Prim $ MyBool False
bvar :: Int -> BruijnTerm () ()
bvar = Var () . Bound
lambda :: String -> LamTerm () () n -> LamTerm () () n
lambda = Lambda () . fromString
appl :: LamTerm ()() n -> LamTerm () () n -> LamTerm () () n
appl = Appl
mkLet :: [(String, LamTerm () () n)] -> LamTerm () () n -> LamTerm () () n
mkLet tupleDef = Let () (map (uncurry (Def (). Name )) tupleDef)
def :: String -> t -> Def () t
def = Def () . Name
|
kwibus/myLang
|
tests/MakeTerm.hs
|
Haskell
|
bsd-3-clause
| 779
|
module Main where
import GHC.IO.Handle
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO
import Data.Aeson
import Sampler
import Control.Monad ( replicateM )
import qualified Data.ByteString.Lazy.Char8 as B
data Flag = OutputFile String -- ^ output file location
| LowerBound String -- ^ structure size lower bound
| UpperBound String -- ^ structure size upper bound
| Samples String -- ^ number of samples
| Help -- ^ whether to print usage help text
deriving (Show,Eq)
options :: [OptDescr Flag]
options =
[ Option "o"
["output"]
(ReqArg OutputFile "FILE")
"Output file. If not given, STDOUT is used instead."
, Option "l"
["lower-bound"]
(ReqArg LowerBound "N")
"Lower bound for the structure size. Default: 10."
, Option "u"
["upper-bound"]
(ReqArg UpperBound "N")
"Upper bound for the structure size. Default: 50."
, Option "s"
["samples"]
(ReqArg Samples "N")
"Number of structures to sample. Default: 1."
, Option "h" ["help"] (NoArg Help) "Prints this help message."
]
outputF :: [Flag] -> Maybe String
outputF (OutputFile f : _ ) = Just f
outputF (_ : fs) = outputF fs
outputF [] = Nothing
lowerBound :: [Flag] -> Int
lowerBound (LowerBound n : _ ) = (read n)
lowerBound (_ : opts) = lowerBound opts
lowerBound [] = 10
upperBound :: [Flag] -> Int
upperBound (UpperBound n : _ ) = read n
upperBound (_ : opts) = upperBound opts
upperBound [] = 50
samples :: [Flag] -> Int
samples (Samples n : _ ) = read n
samples (_ : opts) = samples opts
samples [] = 1
fail' s = do
hPutStrLn stderr s
exitWith (ExitFailure 1)
align :: String -> String -> String
align s t = s ++ t ++ replicate (80 - length s - length t) ' '
version :: String
version = "v2.0"
signature :: String
signature = "Boltzmann Brain " ++ version
versionHeader :: String
versionHeader = signature ++ " (c) 2017-2021."
logoHeader :: String
logoHeader = align s versionHeader
where s = " `/:/::- ` ././:.` "
buildTimeHeader :: String
buildTimeHeader = align s "Sampler"
where s = " .- `..- "
artLogo :: String
artLogo = unlines
[ " .-- "
, " .-` ./:`` ` "
, " .:.-` `.-` ..--:/ .+- ``....:::. "
, " ``.:`-:-::` --..:--//:+/-````:-`.```.-` `//::///---`"
, " ``::-:` //+:. `. `...`-::.++//++/:----:-:.-:/-`/oo+::/-"
, " /o. .:::/-.-:` ` -://:::/:// .::`.-..::/:- "
, " `` ``````.-:` `.`...-/`. `- ``.` `.:/:` -:. "
, " ...+-/-:--::-:` -::/-/:-`.-.`..:::/+:. `+` "
, " `:-.-::::--::.```:/+:-:` ./+/:-+:. :-`.` --. "
, " `` .`.:-``.////-``../++:/::-:/--::::-+/:. -+- "
, "..`..-...:```````-:::`.`.///:-.` ``-.-``.:. ` `/.:/:` `-` "
, "`:////::/+-/+/.`:/o++/:::++-:-.-- . ` `.+/. ` "
, " ` :/:``--.:- .--/+++-::-:-: ` .:. "
, " -::+:./:://+:--.-:://-``/+-` .` "
, " -/`.- -/o+/o+/+//+++//o+. "
, " ` `:/+/s+-...```.://-- "
, logoHeader
, buildTimeHeader
]
usage = do
putStrLn artLogo
putStr (usageInfo "Usage:" options)
exitWith (ExitFailure 1)
-- | Parses the CLI arguments into the command string
-- and some additional (optional) flags.
parse :: [String] -> IO [Flag]
parse argv = case getOpt Permute options argv of
(opts, _, []) | Help `elem` opts -> usage
| otherwise -> return opts
(_, _, errs) -> fail' $ concat errs
-- | Sets up stdout and stdin IO handles.
handleIO :: [Flag] -> IO ()
handleIO opts = do
case outputF opts of
Just file -> do
h <- openFile file WriteMode
hDuplicateTo h stdout -- h becomes the new stdout
Nothing -> return ()
main :: IO ()
main = do
opts <- getArgs >>= parse
handleIO opts -- set up IO handles.
let lb = lowerBound opts
let ub = upperBound opts
let n = samples opts
xs <- replicateM n (SAMPLE_COMMAND lb ub)
B.putStrLn $ encode xs
|
maciej-bendkowski/boltzmann-brain
|
scripts/sampler-template/app/Main.hs
|
Haskell
|
bsd-3-clause
| 4,877
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Simple program to proxy a SFTP session. I.e. a SFTP client will spawn us
-- through SSH instead of a real sftp executable. It won't see any difference
-- as we are fully transparent, but we can se what the protocol looks like.
module Main (main) where
import Control.Applicative ((<$>), (<*), (<*>))
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar, MVar)
import Control.Exception (finally)
import Control.Monad (when)
import Control.Monad.Trans.Class
import Control.Monad.Trans.Writer
import qualified Data.Attoparsec.ByteString as AB (take)
import Data.Attoparsec.ByteString hiding (parse, take)
import Data.Bits (unsafeShiftL, (.&.), Bits)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Base16 as Base16
import qualified Data.ByteString.Char8 as BC
import Data.List (partition)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T (decodeUtf8)
import Data.Word (Word8, Word32, Word64)
import System.Environment (getArgs)
import System.IO (hClose, hFlush, hPutStrLn, hSetBuffering, stdin, stderr, stdout, BufferMode(..))
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as S
import qualified System.IO.Streams.Attoparsec as S
import qualified System.Process as P
import Network.SFTP.Messages
debug :: String -> IO ()
debug s = hPutStrLn stderr ("### " ++ s) >> hFlush stderr
----------------------------------------------------------------------
-- Main loop:
-- We connect our stdin, stdout, and stderr to the real sftp process
-- and feed at the same time our parser.
----------------------------------------------------------------------
main :: IO ()
main = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering
args <- getArgs
(sftpInp, sftpOut, sftpErr, _) <-
runInteractiveProcess "/usr/lib/openssh/sftp-server-original"
args Nothing Nothing
(is, is') <- splitIS S.stdin
(is2, is2') <- splitIS sftpOut
inThread <- forkIO $ S.connect is' sftpInp
errThread <- forkIO $ S.connect sftpErr S.stderr
_ <- forkIO $ S.connect is2' S.stdout
-- S.withFileAsOutput "/home/sftp/debug.txt" $ \observe -> do
mvar <- newEmptyMVar
_ <- forkIO $ do
ps <- execWriterT (protocol is)
putMVar mvar ps
ps <- execWriterT (protocol is2)
ps' <- takeMVar mvar
S.withFileAsOutput "/home/sftp/debug.txt" $ \os -> do
S.write (Just . BC.pack $ "Arguments: " ++ show args ++ "\n") os
mapM_ (\(s, p) -> S.write (Just . BC.pack $ s ++ display p ++ "\n") os) $ merge ps' ps
return ()
-- takeMVar inThread
-- takeMVar errThread
merge [] ys = map ("<<< ",) ys
merge (x:xs) ys = (">>> ", x) : ("<<< ", y') : merge xs ys'
where (y', ys') = case partition ((== packetId x) . packetId) ys of
(y:ys1, ys2) -> (y, ys1 ++ ys2)
(_, ys2) -> (Unknown (RequestId 0) "Missing response.", ys2)
waitableForkIO :: IO () -> IO (MVar ())
waitableForkIO io = do
mvar <- newEmptyMVar
_ <- forkIO (io `finally` putMVar mvar ())
return mvar
-- | Similar to S.runInteractiveProcess but set the different (wrapped)
-- Handles to NoBuffering.
runInteractiveProcess :: FilePath
-> [String]
-> Maybe FilePath
-> Maybe [(String, String)]
-> IO (OutputStream ByteString, InputStream ByteString,
InputStream ByteString, P.ProcessHandle)
runInteractiveProcess cmd args wd env = do
(hin, hout, herr, ph) <- P.runInteractiveProcess cmd args wd env
hSetBuffering hin NoBuffering
hSetBuffering hout NoBuffering
hSetBuffering herr NoBuffering
sIn <- S.handleToOutputStream hin >>=
S.atEndOfOutput (hClose hin) >>=
S.lockingOutputStream
sOut <- S.handleToInputStream hout >>=
S.atEndOfInput (hClose hout) >>=
S.lockingInputStream
sErr <- S.handleToInputStream herr >>=
S.atEndOfInput (hClose herr) >>=
S.lockingInputStream
return (sIn, sOut, sErr, ph)
splitIS :: InputStream a -> IO (InputStream a, InputStream a)
splitIS is = do
mvar <- newEmptyMVar
is0 <- S.makeInputStream (S.read is >>= \m -> putMVar mvar m >> return m)
is1 <- S.makeInputStream (takeMVar mvar)
return (is0, is1)
display :: Packet -> String
display p = short p ++ (let d = description p in if null d then "" else " " ++ d)
|
noteed/sftp-streams
|
bin/sftp-mitm.hs
|
Haskell
|
bsd-3-clause
| 4,471
|
{-# LANGUAGE MonadComprehensions #-}
-- | A big-endian binary PATRICIA trie with fixed-size ints as keys.
module BinaryTrie where
import Prelude hiding (lookup)
import Data.Bits
import Data.Monoid
import Text.Printf
-- | A PATRICIA trie that inspects an @Int@ key bit by bit.
data Trie a = Empty
| Leaf !Int a
-- ^ Each leaf stores the whole key along with the value
-- for that key.
| Branch !Int !Int (Trie a) (Trie a) deriving (Eq, Ord)
-- ^ Each branch stores a prefix and a control bit for
-- the bit it branched on—an @Int@ with just that bit
-- set.
instance Show a => Show (Trie a) where
show Empty = "Empty"
show (Leaf k v) = printf "Leaf %d %s" k (show v)
show (Branch prefix control l r) = printf "(Branch %b %b %s %s)" prefix control (show l) (show r)
width :: Int
width = finiteBitSize (0 :: Int)
-- | Returns the key masked to every bit before (ie more significant)
-- than the control bit.
getPrefix :: Int -> Int -> Int
getPrefix key control = key .&. complement ((control `shiftL` 1) - 1)
-- | A smart consructor for branches of the tree tha avoids creating
-- unnecessary nodes and puts children in the correct order.
branch :: Int -> Int -> Trie a -> Trie a -> Trie a
branch _ _ Empty Empty = Empty
branch _ _ Empty (Leaf k v) = Leaf k v
branch _ _ (Leaf k v) Empty = Leaf k v
branch prefix control l r = Branch prefix control l r
-- TODO: Replace with efficient version with 7.10
countLeadingZeros :: Int -> Int
countLeadingZeros n = (width - 1) - go (width - 1)
where go i | i < 0 = i
| testBit n i = i
| otherwise = go (i - 1)
highestBitSet :: Int -> Int
highestBitSet n = bit $ width - countLeadingZeros n - 1
-- | Branches on whether the bit of the key at the given control bit
-- is 0 (left) or 1 (right).
checkBit :: Int -> Int -> a -> a -> a
checkBit k control left right = if k .&. control == 0 then left else right
-- | We look a value up by branching based on bits. If we ever hit a
-- leaf node, we check whether our whole key matches. If we ever hit
-- an empty node, we know the key is not in the trie.
lookup :: Int -> Trie a -> Maybe a
lookup _ Empty = Nothing
lookup k (Leaf k' v) = [v | k == k']
lookup k (Branch prefix control l r)
| getPrefix k control /= prefix = Nothing
| otherwise = lookup k (checkBit k control l r)
-- | Combines two trees with two different prefixes.
combine :: Int -> Trie a -> Int -> Trie a -> Trie a
combine pl l pr r = checkBit pl control
(branch prefix control l r)
(branch prefix control r l)
where control = highestBitSet (pl `xor` pr)
prefix = getPrefix pl control
insert :: Monoid a => Int -> a -> Trie a -> Trie a
insert k v Empty = Leaf k v
insert k v (Leaf k' v')
| k == k' = Leaf k (v <> v')
| otherwise = combine k (Leaf k v) k' (Leaf k' v')
insert k v trie@(Branch prefix control l r)
| getPrefix k control == prefix = checkBit k control
(branch prefix control (insert k v l) r)
(branch prefix control l (insert k v r))
| otherwise = combine k (Leaf k v) prefix trie
fromList :: Monoid a => [(Int, a)] -> Trie a
fromList = foldr (\ (k, v) t -> insert k v t) Empty
keys :: Trie a -> [Int]
keys Empty = []
keys (Leaf k _) = [k]
keys (Branch _ _ l r) = keys l ++ keys r
merge :: Monoid a => Trie a -> Trie a -> Trie a
merge Empty t = t
merge t Empty = t
merge (Leaf k v) t = insert k v t
merge t (Leaf k v) = insert k v t
merge t₁@(Branch p₁ c₁ l₁ r₁) t₂@(Branch p₂ c₂ l₂ r₂)
| p₁ == p₂ && c₁ == c₂ = branch p₁ c₁ (merge l₁ l₂) (merge r₁ r₂)
| c₁ > c₂ && getPrefix p₂ c₁ == p₁ = checkBit p₂ c₁
(branch p₁ c₁ (merge l₁ t₂) r₁)
(branch p₁ c₁ l₁ (merge r₁ t₂))
| c₂ > c₁ && getPrefix p₁ c₂ == p₂ = checkBit p₁ c₂
(branch p₂ c₂ (merge t₁ l₂) r₂)
(branch p₂ c₂ l₂ (merge t₁ r₂))
| otherwise = combine p₁ t₁ p₂ t₂
delete :: Int -> Trie a -> Trie a
delete k Empty = Empty
delete k (Leaf k' v)
| k == k' = Empty
| otherwise = Leaf k' v
delete k trie@(Branch prefix control l r)
| getPrefix k control == prefix = checkBit k control
(branch prefix control (delete k l) r)
(branch prefix control l (delete k r))
| otherwise = trie
intersect :: Monoid a => Trie a -> Trie a -> Trie a
intersect Empty _ = Empty
intersect _ Empty = Empty
intersect (Leaf k v) (Leaf k' v')
| k == k' = Leaf k (v <> v')
| otherwise = Empty
intersect leaf@(Leaf k v) (Branch prefix control l r)
| getPrefix k control == prefix = checkBit k control (intersect leaf l) (intersect leaf r)
| otherwise = Empty
intersect (Branch prefix control l r) leaf@(Leaf k v)
| getPrefix k control == prefix = checkBit k control (intersect l leaf) (intersect r leaf)
| otherwise = Empty
intersect left@(Branch p₁ c₁ l₁ r₁) right@(Branch p₂ c₂ l₂ r₂)
| c₁ == c₂ && p₁ == p₂ = branch p₁ c₁ (intersect l₁ l₂) (intersect r₁ r₂)
| c₁ > c₂ && getPrefix p₂ c₁ == p₁ = checkBit p₂ c₁ (intersect l₁ right) (intersect r₁ right)
| c₁ < c₂ && getPrefix p₁ c₂ == p₂ = checkBit p₁ c₂ (intersect left l₂) (intersect right r₂)
| otherwise = Empty
-- Utility functions
b :: Int -> IO ()
b i = printf "%b\n" i
|
silky/different-tries
|
src/BinaryTrie.hs
|
Haskell
|
bsd-3-clause
| 5,963
|
module B1.Data.Technicals.StockData
( StockData
, StockDataStatus(..)
, StockPriceData(..)
, newStockData
, createStockPriceData
, getStockDataStatus
, getStockPriceData
, getErrorMessage
, handleStockData
) where
import Control.Concurrent
import Control.Concurrent.MVar
import Data.Either
import Data.Maybe
import Data.Time.Calendar
import Data.Time.Clock
import Data.Time.LocalTime
import System.IO
import B1.Control.TaskManager
import B1.Data.Price
import B1.Data.Price.Google
import B1.Data.Symbol
import B1.Data.Technicals.MovingAverage
import B1.Data.Technicals.Stochastic
-- TODO: Rename to StockDataFactory
data StockData = StockData Symbol (MVar (Either StockPriceData String))
-- TODO: Rename to StockData
data StockPriceData = StockPriceData
{ prices :: [Price]
, stochastics :: [Stochastic]
, weeklyPrices :: [Price]
, weeklyStochastics :: [Stochastic]
, movingAverage25 :: [MovingAverage]
, movingAverage50 :: [MovingAverage]
, movingAverage200 :: [MovingAverage]
, numDailyElements :: Int
, numWeeklyElements :: Int
}
data StockDataStatus = Loading | Data | ErrorMessage deriving (Eq)
newStockData :: TaskManager -> Symbol -> IO StockData
newStockData taskManager symbol = do
priceDataMVar <- newEmptyMVar
addTask taskManager $ do
startDate <- getStartDate
endDate <- getEndDate
pricesOrError <- getGooglePrices startDate endDate symbol
putMVar priceDataMVar $
either (Left . createStockPriceData) Right pricesOrError
return $ StockData symbol priceDataMVar
getStartDate :: IO LocalTime
getStartDate = do
endDate <- getEndDate
let startDay = (addGregorianYearsClip (-2) . localDay) endDate
return endDate
{ localDay = startDay
, localTimeOfDay = midnight
}
getEndDate :: IO LocalTime
getEndDate = do
timeZone <- getCurrentTimeZone
time <- getCurrentTime
let localTime = utcToLocalTime timeZone time
return $ localTime { localTimeOfDay = midnight }
createStockPriceData :: [Price] -> StockPriceData
createStockPriceData prices =
StockPriceData
{ prices = prices
, stochastics = stochastics
, weeklyPrices = weeklyPrices
, weeklyStochastics = weeklyStochastics
, movingAverage25 = movingAverage25
, movingAverage50 = movingAverage50
, movingAverage200 = movingAverage200
, numDailyElements = numDailyElements
, numWeeklyElements = numWeeklyElements
}
where
stochasticsFunction = getStochastics 10 3
stochastics = stochasticsFunction prices
movingAverage25 = getMovingAverage 25 prices
movingAverage50 = getMovingAverage 50 prices
movingAverage200 = getMovingAverage 200 prices
weeklyPrices = getWeeklyPrices prices
weeklyStochastics = stochasticsFunction weeklyPrices
maxDailyElements = minimum
[ length prices
, length stochastics
]
weeksInYear = 52
maxWeeklyElements = minimum
[ length weeklyPrices
, length weeklyStochastics
, weeksInYear
]
earliestStartTime = (startTime
. last
. take maxWeeklyElements
) weeklyPrices
numDailyElements = (length
. takeWhile ((>= earliestStartTime) . startTime)
. take maxDailyElements
) prices
numWeeklyElements = (length
. takeWhile ((>= earliestStartTime) . startTime)
. take maxWeeklyElements
) weeklyPrices
getStockDataStatus :: StockData -> IO StockDataStatus
getStockDataStatus = handleStockData (ignore Data) (ignore ErrorMessage) Loading
getStockPriceData :: StockData -> IO (Maybe StockPriceData)
getStockPriceData = handleStockData (return . Just) (ignore Nothing) Nothing
getErrorMessage :: StockData -> IO (Maybe String)
getErrorMessage = handleStockData (ignore Nothing) (return . Just) Nothing
handleStockData :: (StockPriceData -> IO a) -> (String -> IO a) -> a
-> StockData -> IO a
handleStockData priceFunction errorFunction noValue
(StockData _ contentsVar) = do
maybeContents <- tryTakeMVar contentsVar
case maybeContents of
Just contents -> do
tryPutMVar contentsVar contents
either priceFunction errorFunction contents
_ ->
return noValue
ignore :: a -> b -> IO a
ignore value _ = return value
|
btmura/b1
|
src/B1/Data/Technicals/StockData.hs
|
Haskell
|
bsd-3-clause
| 4,249
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
-- | The commented code summarizes what will be auto-generated below
module Main where
import Control.Lens
-- import Test.QuickCheck (quickCheck)
data Bar a b c = Bar { _baz :: (a, b) }
makeLenses ''Bar
-- baz :: Lens (Bar a b c) (Bar a' b' c) (a,b) (a',b')
data Quux a b = Quux { _quaffle :: Int, _quartz :: Double }
makeLenses ''Quux
-- quaffle :: Lens (Quux a b) (Quux a' b') Int Int
-- quartz :: Lens (Quux a b) (Quux a' b') Double Double
data Quark a = Qualified { _gaffer :: a }
| Unqualified { _gaffer :: a, _tape :: a }
makeLenses ''Quark
-- gaffer :: Simple Lens (Quark a) a
-- tape :: Simple Traversal (Quark a) a
data Hadron a b = Science { _a1 :: a, _a2 :: a, _b :: b }
makeLenses ''Hadron
-- a1 :: Simple Lens (Hadron a b) a
-- a2 :: Simple Lens (Hadron a b) a
-- b :: Lens (Hadron a b) (Hadron a b') b b'
data Perambulation a b
= Mountains { _terrain :: a, _altitude :: b }
| Beaches { _terrain :: a, _dunes :: a }
makeLenses ''Perambulation
-- terrain :: Simple Lens (Perambulation a b) a
-- altitude :: Traversal (Perambulation a b) (Parambulation a b') b b'
-- dunes :: Simple Traversal (Perambulation a b) a
makeLensesFor [("_terrain", "allTerrain"), ("_dunes", "allTerrain")] ''Perambulation
-- allTerrain :: Traversal (Perambulation a b) (Perambulation a' b) a a'
data LensCrafted a = Still { _still :: a }
| Works { _still :: a }
makeLenses ''LensCrafted
-- still :: Lens (LensCrafted a) (LensCrafted b) a b
data Danger a = Zone { _highway :: a }
| Twilight
makeLensesWith (partialLenses .~ True $ buildTraversals .~ False $ lensRules) ''Danger
-- highway :: Lens (Danger a) (Danger a') a a'
data Task a = Task
{ taskOutput :: a -> IO ()
, taskState :: a
, taskStop :: IO ()
}
makeLensesFor [("taskOutput", "outputLens"), ("taskState", "stateLens"), ("taskStop", "stopLens")] ''Task
data Mono a = Mono { _monoFoo :: a, _monoBar :: Int }
makeClassy ''Mono
-- class HasMono t where
-- mono :: Simple Lens t Mono
-- instance HasMono Mono where
-- mono = id
-- monoFoo :: HasMono t => Simple Lens t Int
-- monoBar :: HasMono t => Simple Lens t Int
data Nucleosis = Nucleosis { _nuclear :: Mono Int }
makeClassy ''Nucleosis
-- class HasNucleosis t where
-- nucleosis :: Simple Lens t Nucleosis
-- instance HasNucleosis Nucleosis
-- nuclear :: HasNucleosis t => Simple Lens t Mono
instance HasMono Nucleosis Int where
mono = nuclear
-- Dodek's example
data Foo = Foo { _fooX, _fooY :: Int }
makeClassy ''Foo
main :: IO ()
main = putStrLn "test/templates.hs: ok"
|
np/lens
|
tests/templates.hs
|
Haskell
|
bsd-3-clause
| 2,743
|
module Idris.DeepSeq(module Idris.DeepSeq, module Idris.Core.DeepSeq) where
import Idris.Core.DeepSeq
import Idris.Core.TT
import Idris.AbsSyntaxTree
import Control.DeepSeq
-- All generated by 'derive'
instance NFData Forceability where
rnf Conditional = ()
rnf Unconditional = ()
instance NFData IntTy where
rnf (ITFixed x1) = rnf x1 `seq` ()
rnf ITNative = ()
rnf ITBig = ()
rnf ITChar = ()
rnf (ITVec x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
instance NFData NativeTy where
rnf IT8 = ()
rnf IT16 = ()
rnf IT32 = ()
rnf IT64 = ()
instance NFData ArithTy where
rnf (ATInt x1) = rnf x1 `seq` ()
rnf ATFloat = ()
instance NFData SizeChange where
rnf Smaller = ()
rnf Same = ()
rnf Bigger = ()
rnf Unknown = ()
instance NFData CGInfo where
rnf (CGInfo x1 x2 x3 x4 x5)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
instance NFData Fixity where
rnf (Infixl x1) = rnf x1 `seq` ()
rnf (Infixr x1) = rnf x1 `seq` ()
rnf (InfixN x1) = rnf x1 `seq` ()
rnf (PrefixN x1) = rnf x1 `seq` ()
instance NFData FixDecl where
rnf (Fix x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
instance NFData Static where
rnf Static = ()
rnf Dynamic = ()
instance NFData ArgOpt where
rnf _ = ()
instance NFData Plicity where
rnf (Imp x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (Exp x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (Constraint x1 x2 x3)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (TacImp x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
instance NFData FnOpt where
rnf Inlinable = ()
rnf TotalFn = ()
rnf PartialFn = ()
rnf Coinductive = ()
rnf AssertTotal = ()
rnf Dictionary = ()
rnf Implicit = ()
rnf (CExport x1) = rnf x1 `seq` ()
rnf Reflection = ()
rnf (Specialise x1) = rnf x1 `seq` ()
instance NFData DataOpt where
rnf Codata = ()
rnf DefaultEliminator = ()
instance (NFData t) => NFData (PDecl' t) where
rnf (PFix x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PTy x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
rnf (PPostulate x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
rnf (PClauses x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PCAF x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PData x1 x2 x3 x4 x5)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
rnf (PParams x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PNamespace x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PRecord x1 x2 x3 x4 x5 x6 x7 x8)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` ()
rnf (PClass x1 x2 x3 x4 x5 x6 x7)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` ()
rnf (PInstance x1 x2 x3 x4 x5 x6 x7 x8)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` ()
rnf (PDSL x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PSyntax x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PMutual x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PDirective x1) = ()
rnf (PProvider x1 x2 x3 x4 x5)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
rnf (PTransform x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
instance (NFData t) => NFData (PClause' t) where
rnf (PClause x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
rnf (PWith x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
rnf (PClauseR x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PWithR x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
instance (NFData t) => NFData (PData' t) where
rnf (PDatadecl x1 x2 x3)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PLaterdecl x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
instance NFData PTerm where
rnf (PQuote x1) = rnf x1 `seq` ()
rnf (PRef x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PInferRef x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PPatvar x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PLam x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PPi x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PLet x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PTyped x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PApp x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PAppBind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PMatchApp x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PCase x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PTrue x1) = rnf x1 `seq` ()
rnf (PFalse x1) = rnf x1 `seq` ()
rnf (PRefl x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PResolveTC x1) = rnf x1 `seq` ()
rnf (PEq x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PRewrite x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PPair x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PDPair x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PAlternative x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PHidden x1) = rnf x1 `seq` ()
rnf PType = ()
rnf (PGoal x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PConstant x1) = x1 `seq` ()
rnf Placeholder = ()
rnf (PDoBlock x1) = rnf x1 `seq` ()
rnf (PIdiom x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PReturn x1) = rnf x1 `seq` ()
rnf (PMetavar x1) = rnf x1 `seq` ()
rnf (PProof x1) = rnf x1 `seq` ()
rnf (PTactics x1) = rnf x1 `seq` ()
rnf (PElabError x1) = rnf x1 `seq` ()
rnf PImpossible = ()
rnf (PCoerced x1) = rnf x1 `seq` ()
rnf (PUnifyLog x1) = rnf x1 `seq` ()
rnf (PNoImplicits x1) = rnf x1 `seq` ()
instance (NFData t) => NFData (PTactic' t) where
rnf (Intro x1) = rnf x1 `seq` ()
rnf Intros = ()
rnf (Focus x1) = rnf x1 `seq` ()
rnf (Refine x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (Rewrite x1) = rnf x1 `seq` ()
rnf (Induction x1) = rnf x1 `seq` ()
rnf (Equiv x1) = rnf x1 `seq` ()
rnf (MatchRefine x1) = rnf x1 `seq` ()
rnf (LetTac x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (LetTacTy x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (Exact x1) = rnf x1 `seq` ()
rnf Compute = ()
rnf Trivial = ()
rnf (ProofSearch x1 x2 x3)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf Solve = ()
rnf Attack = ()
rnf ProofState = ()
rnf ProofTerm = ()
rnf Undo = ()
rnf (Try x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (TSeq x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (ApplyTactic x1) = rnf x1 `seq` ()
rnf (Reflect x1) = rnf x1 `seq` ()
rnf (Fill x1) = rnf x1 `seq` ()
rnf (GoalType x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf Qed = ()
rnf Abandon = ()
instance (NFData t) => NFData (PDo' t) where
rnf (DoExp x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (DoBind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (DoBindP x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (DoLet x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (DoLetP x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
instance (NFData t) => NFData (PArg' t) where
rnf (PImp x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
rnf (PExp x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PConstraint x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PTacImplicit x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
instance NFData ClassInfo where
rnf (CI x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
instance NFData OptInfo where
rnf (Optimise x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
instance NFData TypeInfo where
rnf (TI x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
instance (NFData t) => NFData (DSL' t) where
rnf (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` ()
instance NFData SynContext where
rnf PatternSyntax = ()
rnf TermSyntax = ()
rnf AnySyntax = ()
instance NFData Syntax where
rnf (Rule x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
instance NFData SSymbol where
rnf (Keyword x1) = rnf x1 `seq` ()
rnf (Symbol x1) = rnf x1 `seq` ()
rnf (Binding x1) = rnf x1 `seq` ()
rnf (Expr x1) = rnf x1 `seq` ()
rnf (SimpleExpr x1) = rnf x1 `seq` ()
instance NFData Using where
rnf (UImplicit x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (UConstraint x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
instance NFData SyntaxInfo where
rnf (Syn x1 x2 x3 x4 x5 x6 x7 x8)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` ()
|
ctford/Idris-Elba-dev
|
src/Idris/DeepSeq.hs
|
Haskell
|
bsd-3-clause
| 10,810
|
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -Wall #-}
module Main where
import Control.Concurrent
import Control.Exception as Ex
import Control.Monad
import Data.IORef
import System.Posix.CircularBuffer
import System.Environment
-- read Int's from the supplied buffer as fast as possible, and print the
-- number read after 10 seconds
main :: IO ()
main = do
args <- getArgs
counter <- newIORef (0::Int)
case args of
[nm,szStr] -> do
let sz = read szStr
Ex.bracket ((openBuffer nm nm sz 0o600 :: IO (ReadBuffer Int))) (removeBuffer) $ \rb -> do
tid <- forkIO $ forever $ do
xs <- getAvailable rb
if (null xs) then yield else writeIORef counter $ last xs
-- x <- getBuffer WaitYield rb
-- writeIORef counter x
threadDelay $ 10*1000000
killThread tid
print =<< readIORef counter
_ -> error "usage: reader NAME SZ"
|
smunix/shared-buffer
|
benchmarks/Reader.hs
|
Haskell
|
bsd-3-clause
| 989
|
{-| Implementation of the RAPI client interface.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
{-# LANGUAGE BangPatterns, CPP #-}
module Ganeti.HTools.Backend.Rapi
( loadData
, parseData
) where
import Control.Exception
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Network.Curl
import Network.Curl.Types ()
import Control.Monad
import Text.JSON (JSObject, fromJSObject, decodeStrict)
import Text.JSON.Types (JSValue(..))
import Text.Printf (printf)
import System.FilePath
import Ganeti.BasicTypes
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import Ganeti.JSON
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.Constants as C
{-# ANN module "HLint: ignore Eta reduce" #-}
-- | File method prefix.
filePrefix :: String
filePrefix = "file://"
-- | Read an URL via curl and return the body if successful.
getUrl :: (Monad m) => String -> IO (m String)
-- | Connection timeout (when using non-file methods).
connTimeout :: Long
connTimeout = 15
-- | The default timeout for queries (when using non-file methods).
queryTimeout :: Long
queryTimeout = 60
-- | The curl options we use.
curlOpts :: [CurlOption]
curlOpts = [ CurlSSLVerifyPeer False
, CurlSSLVerifyHost 0
, CurlTimeout queryTimeout
, CurlConnectTimeout connTimeout
]
getUrl url = do
(code, !body) <- curlGetString url curlOpts
return (case code of
CurlOK -> return body
_ -> fail $ printf "Curl error for '%s', error %s"
url (show code))
-- | Helper to convert I/O errors in 'Bad' values.
ioErrToResult :: IO a -> IO (Result a)
ioErrToResult ioaction =
Control.Exception.catch (liftM Ok ioaction)
(\e -> return . Bad . show $ (e::IOException))
-- | Append the default port if not passed in.
formatHost :: String -> String
formatHost master =
if ':' `elem` master
then master
else "https://" ++ master ++ ":" ++ show C.defaultRapiPort
-- | Parse a instance list in JSON format.
getInstances :: NameAssoc
-> String
-> Result [(String, Instance.Instance)]
getInstances ktn body =
loadJSArray "Parsing instance data" body >>=
mapM (parseInstance ktn . fromJSObject)
-- | Parse a node list in JSON format.
getNodes :: NameAssoc -> String -> Result [(String, Node.Node)]
getNodes ktg body = loadJSArray "Parsing node data" body >>=
mapM (parseNode ktg . fromJSObject)
-- | Parse a group list in JSON format.
getGroups :: String -> Result [(String, Group.Group)]
getGroups body = loadJSArray "Parsing group data" body >>=
mapM (parseGroup . fromJSObject)
-- | Construct an instance from a JSON object.
parseInstance :: NameAssoc
-> JSRecord
-> Result (String, Instance.Instance)
parseInstance ktn a = do
name <- tryFromObj "Parsing new instance" a "name"
let owner_name = "Instance '" ++ name ++ "', error while parsing data"
let extract s x = tryFromObj owner_name x s
disk <- extract "disk_usage" a
dsizes <- extract "disk.sizes" a
dspindles <- tryArrayMaybeFromObj owner_name a "disk.spindles"
beparams <- liftM fromJSObject (extract "beparams" a)
omem <- extract "oper_ram" a
mem <- case omem of
JSRational _ _ -> annotateResult owner_name (fromJVal omem)
_ -> extract "memory" beparams `mplus` extract "maxmem" beparams
vcpus <- extract "vcpus" beparams
pnode <- extract "pnode" a >>= lookupNode ktn name
snodes <- extract "snodes" a
snode <- case snodes of
[] -> return Node.noSecondary
x:_ -> readEitherString x >>= lookupNode ktn name
running <- extract "status" a
tags <- extract "tags" a
auto_balance <- extract "auto_balance" beparams
dt <- extract "disk_template" a
su <- extract "spindle_use" beparams
-- Not forthcoming by default.
forthcoming <- extract "forthcoming" a `orElse` Ok False
let disks = zipWith Instance.Disk dsizes dspindles
let inst = Instance.create name mem disk disks vcpus running tags
auto_balance pnode snode dt su [] forthcoming
return (name, inst)
-- | Construct a node from a JSON object.
parseNode :: NameAssoc -> JSRecord -> Result (String, Node.Node)
parseNode ktg a = do
name <- tryFromObj "Parsing new node" a "name"
let desc = "Node '" ++ name ++ "', error while parsing data"
extract key = tryFromObj desc a key
extractDef def key = fromObjWithDefault a key def
offline <- extract "offline"
drained <- extract "drained"
vm_cap <- annotateResult desc $ maybeFromObj a "vm_capable"
let vm_cap' = fromMaybe True vm_cap
ndparams <- extract "ndparams" >>= asJSObject
excl_stor <- tryFromObj desc (fromJSObject ndparams) "exclusive_storage"
guuid <- annotateResult desc $ maybeFromObj a "group.uuid"
guuid' <- lookupGroup ktg name (fromMaybe defaultGroupID guuid)
let live = not offline && vm_cap'
lvextract def = eitherLive live def . extract
lvextractDef def = eitherLive live def . extractDef def
sptotal <- if excl_stor
then lvextract 0 "sptotal"
else tryFromObj desc (fromJSObject ndparams) "spindle_count"
spfree <- lvextractDef 0 "spfree"
mtotal <- lvextract 0.0 "mtotal"
mnode <- lvextract 0 "mnode"
mfree <- lvextract 0 "mfree"
dtotal <- lvextractDef 0.0 "dtotal"
dfree <- lvextractDef 0 "dfree"
ctotal <- lvextract 0.0 "ctotal"
cnos <- lvextract 0 "cnos"
tags <- extract "tags"
let node = flip Node.setNodeTags tags $
Node.create name mtotal mnode mfree dtotal dfree ctotal cnos
(not live || drained) sptotal spfree guuid' excl_stor
return (name, node)
-- | Construct a group from a JSON object.
parseGroup :: JSRecord -> Result (String, Group.Group)
parseGroup a = do
name <- tryFromObj "Parsing new group" a "name"
let extract s = tryFromObj ("Group '" ++ name ++ "'") a s
uuid <- extract "uuid"
apol <- extract "alloc_policy"
ipol <- extract "ipolicy"
tags <- extract "tags"
-- TODO: parse networks to which this group is connected
return (uuid, Group.create name uuid apol [] ipol tags)
-- | Parse cluster data from the info resource.
parseCluster :: JSObject JSValue -> Result ([String], IPolicy, String)
parseCluster obj = do
let obj' = fromJSObject obj
extract s = tryFromObj "Parsing cluster data" obj' s
master <- extract "master"
tags <- extract "tags"
ipolicy <- extract "ipolicy"
return (tags, ipolicy, master)
-- | Loads the raw cluster data from an URL.
readDataHttp :: String -- ^ Cluster or URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readDataHttp master = do
let url = formatHost master
group_body <- getUrl $ printf "%s/2/groups?bulk=1" url
node_body <- getUrl $ printf "%s/2/nodes?bulk=1" url
inst_body <- getUrl $ printf "%s/2/instances?bulk=1" url
info_body <- getUrl $ printf "%s/2/info" url
return (group_body, node_body, inst_body, info_body)
-- | Loads the raw cluster data from the filesystem.
readDataFile:: String -- ^ Path to the directory containing the files
-> IO (Result String, Result String, Result String, Result String)
readDataFile path = do
group_body <- ioErrToResult . readFile $ path </> "groups.json"
node_body <- ioErrToResult . readFile $ path </> "nodes.json"
inst_body <- ioErrToResult . readFile $ path </> "instances.json"
info_body <- ioErrToResult . readFile $ path </> "info.json"
return (group_body, node_body, inst_body, info_body)
-- | Loads data via either 'readDataFile' or 'readDataHttp'.
readData :: String -- ^ URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readData url =
if filePrefix `isPrefixOf` url
then readDataFile (drop (length filePrefix) url)
else readDataHttp url
-- | Builds the cluster data from the raw Rapi content.
parseData :: (Result String, Result String, Result String, Result String)
-> Result ClusterData
parseData (group_body, node_body, inst_body, info_body) = do
group_data <- group_body >>= getGroups
let (group_names, group_idx) = assignIndices group_data
node_data <- node_body >>= getNodes group_names
let (node_names, node_idx) = assignIndices node_data
inst_data <- inst_body >>= getInstances node_names
let (_, inst_idx) = assignIndices inst_data
(tags, ipolicy, master) <-
info_body >>=
(fromJResult "Parsing cluster info" . decodeStrict) >>=
parseCluster
node_idx' <- setMaster node_names node_idx master
return (ClusterData group_idx node_idx' inst_idx tags ipolicy)
-- | Top level function for data loading.
loadData :: String -- ^ Cluster or URL to use as source
-> IO (Result ClusterData)
loadData = fmap parseData . readData
|
apyrgio/ganeti
|
src/Ganeti/HTools/Backend/Rapi.hs
|
Haskell
|
bsd-2-clause
| 10,150
|
-----------------------------------------------------------------------------
--
-- Machine-specific parts of the register allocator
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module PPC.RegInfo (
JumpDest( DestBlockId ), getJumpDestBlockId,
canShortcut,
shortcutJump,
shortcutStatics
)
where
#include "nativeGen/NCG.h"
#include "HsVersions.h"
import PPC.Instr
import BlockId
import Cmm
import CLabel
import Unique
data JumpDest = DestBlockId BlockId
getJumpDestBlockId :: JumpDest -> Maybe BlockId
getJumpDestBlockId (DestBlockId bid) = Just bid
canShortcut :: Instr -> Maybe JumpDest
canShortcut _ = Nothing
shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr
shortcutJump _ other = other
-- Here because it knows about JumpDest
shortcutStatics :: (BlockId -> Maybe JumpDest) -> CmmStatics -> CmmStatics
shortcutStatics fn (Statics lbl statics)
= Statics lbl $ map (shortcutStatic fn) statics
-- we need to get the jump tables, so apply the mapping to the entries
-- of a CmmData too.
shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel
shortcutLabel fn lab
| Just uq <- maybeAsmTemp lab = shortBlockId fn (mkBlockId uq)
| otherwise = lab
shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic
shortcutStatic fn (CmmStaticLit (CmmLabel lab))
= CmmStaticLit (CmmLabel (shortcutLabel fn lab))
shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off))
= CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off)
-- slightly dodgy, we're ignoring the second label, but this
-- works with the way we use CmmLabelDiffOff for jump tables now.
shortcutStatic _ other_static
= other_static
shortBlockId
:: (BlockId -> Maybe JumpDest)
-> BlockId
-> CLabel
shortBlockId fn blockid =
case fn blockid of
Nothing -> mkAsmTempLabel uq
Just (DestBlockId blockid') -> shortBlockId fn blockid'
where uq = getUnique blockid
|
lukexi/ghc-7.8-arm64
|
compiler/nativeGen/PPC/RegInfo.hs
|
Haskell
|
bsd-3-clause
| 2,380
|
{-# Language PatternGuards #-}
module Blub
( blub
, foo
, bar
) where
import Ugah.Foo ( a
, b
)
import Control.Applicative
import Ugah.Blub
f :: Int -> Int
f = (+ 3)
g :: Int -> Int
g =
where
|
jystic/hsimport
|
tests/inputFiles/ModuleTest28.hs
|
Haskell
|
bsd-3-clause
| 240
|
-- FrontEnd.Tc.Type should be imported instead of this.
module FrontEnd.Representation(
Type(..),
Tyvar(..),
tyvar,
Tycon(..),
fn,
Pred(..),
Qual(..),
Class,
tForAll,
tExists,
MetaVarType(..),
prettyPrintType,
fromTAp,
fromTArrow,
tassocToAp,
MetaVar(..),
tTTuple,
tTTuple',
tList,
tArrow,
tAp
)where
import Control.Monad.Identity
import Data.IORef
import Data.Binary
import Doc.DocLike
import Doc.PPrint
import FrontEnd.Tc.Kind
import Name.Names
import Name.VConsts
import Support.CanType
import Support.Unparse
import Util.VarName
-- Types
data MetaVarType = Tau | Rho | Sigma
deriving(Eq,Ord)
{-! derive: Binary !-}
data Type = TVar { typeVar :: !Tyvar }
| TCon { typeCon :: !Tycon }
| TAp Type Type
| TArrow Type Type
| TForAll { typeArgs :: [Tyvar], typeBody :: (Qual Type) }
| TExists { typeArgs :: [Tyvar], typeBody :: (Qual Type) }
| TMetaVar { metaVar :: MetaVar }
| TAssoc { typeCon :: !Tycon, typeClassArgs :: [Type], typeExtraArgs :: [Type] }
deriving(Ord,Show)
{-! derive: Binary !-}
-- | metavars are used in type checking
data MetaVar = MetaVar {
metaUniq :: {-# UNPACK #-} !Int,
metaKind :: Kind,
metaRef :: {-# UNPACK #-} !(IORef (Maybe Type)),
metaType :: !MetaVarType
}
{-! derive: Binary !-}
instance Eq MetaVar where
a == b = metaUniq a == metaUniq b
instance Ord MetaVar where
compare a b = compare (metaUniq a) (metaUniq b)
instance TypeNames Type where
tBool = TCon (Tycon tc_Bool kindStar)
tString = TAp tList tChar
tChar = TCon (Tycon tc_Char kindStar)
tUnit = TCon (Tycon tc_Unit kindStar)
tCharzh = TCon (Tycon tc_Char_ kindHash)
instance Ord (IORef a)
instance Binary (IORef a) where
put = error "Binary.put: not impl."
get = error "Binary.get: not impl."
tList :: Type
tList = TCon (Tycon tc_List (Kfun kindStar kindStar))
-- | The @(->)@ type constructor. Invariant: @tArrow@ shall not be fully applied. To this end, see 'tAp'.
tArrow :: Type
tArrow = TCon (Tycon tc_Arrow (kindArg `Kfun` (kindFunRet `Kfun` kindStar)))
-- | Type application, enforcing the invariant that there be no fully-applied 'tArrow's
tAp :: Type -> Type -> Type
tAp (TAp c@TCon{} a) b | c == tArrow = TArrow a b
tAp a b = TAp a b
instance Eq Type where
(TVar a) == (TVar b) = a == b
(TMetaVar a) == (TMetaVar b) = a == b
(TCon a) == (TCon b) = a == b
(TAp a' a) == (TAp b' b) = a' == b' && b == a
(TArrow a' a) == (TArrow b' b) = a' == b' && b == a
_ == _ = False
tassocToAp TAssoc { typeCon = con, typeClassArgs = cas, typeExtraArgs = eas } = foldl tAp (TCon con) (cas ++ eas)
tassocToAp _ = error "Representation.tassocToAp: bad."
-- Unquantified type variables
data Tyvar = Tyvar { tyvarName :: {-# UNPACK #-} !Name, tyvarKind :: Kind }
{- derive: Binary -}
instance Show Tyvar where
showsPrec _ Tyvar { tyvarName = hn, tyvarKind = k } = shows hn . ("::" ++) . shows k
tForAll [] ([] :=> t) = t
tForAll vs (ps :=> TForAll vs' (ps' :=> t)) = tForAll (vs ++ vs') ((ps ++ ps') :=> t)
tForAll x y = TForAll x y
tExists [] ([] :=> t) = t
tExists vs (ps :=> TExists vs' (ps' :=> t)) = tExists (vs ++ vs') ((ps ++ ps') :=> t)
tExists x y = TExists x y
tyvar n k = Tyvar n k
instance Eq Tyvar where
Tyvar { tyvarName = x } == Tyvar { tyvarName = y } = x == y
Tyvar { tyvarName = x } /= Tyvar { tyvarName = y } = x /= y
instance Ord Tyvar where
compare (Tyvar { tyvarName = x }) (Tyvar { tyvarName = y }) = compare x y
(Tyvar { tyvarName = x }) <= (Tyvar { tyvarName = y }) = x <= y
(Tyvar { tyvarName = x }) >= (Tyvar { tyvarName = y }) = x >= y
(Tyvar { tyvarName = x }) < (Tyvar { tyvarName = y }) = x < y
(Tyvar { tyvarName = x }) > (Tyvar { tyvarName = y }) = x > y
-- Type constructors
data Tycon = Tycon { tyconName :: Name, tyconKind :: Kind }
deriving(Eq, Show,Ord)
{-! derive: Binary !-}
instance ToTuple Tycon where
--toTuple n = Tycon (nameTuple TypeConstructor n) (foldr Kfun kindStar $ replicate n kindStar)
toTuple n = Tycon (name_TupleConstructor typeLevel n) (foldr Kfun kindStar $ replicate n kindStar)
instance ToTuple Type where
toTuple n = TCon $ toTuple n
instance DocLike d => PPrint d Tycon where
pprint (Tycon i _) = pprint i
infixr 4 `fn`
fn :: Type -> Type -> Type
a `fn` b = TArrow a b
--------------------------------------------------------------------------------
-- Predicates
data Pred = IsIn Class Type | IsEq Type Type
deriving(Show, Eq,Ord)
{-! derive: Binary !-}
-- Qualified entities
data Qual t = [Pred] :=> t
deriving(Show, Eq,Ord)
{-! derive: Binary !-}
instance (DocLike d,PPrint d t) => PPrint d (Qual t) where
pprint ([] :=> r) = pprint r
pprint ([x] :=> r) = pprint x <+> text "=>" <+> pprint r
pprint (xs :=> r) = tupled (map pprint xs) <+> text "=>" <+> pprint r
instance DocLike d => PPrint d Tyvar where
pprint tv = tshow (tyvarName tv)
instance Binary Tyvar where
put (Tyvar aa ab) = do
put aa
put ab
get = do
aa <- get
ab <- get
return (Tyvar aa ab)
instance DocLike d => PPrint d Module where
pprint s = tshow s
withNewNames ts action = subVarName $ do
ts' <- mapM newTyvarName ts
action ts'
newTyvarName t = case tyvarKind t of
x@(KBase Star) -> newLookupName (map (:[]) ['a' ..]) x t
y@(KBase Star `Kfun` KBase Star) -> newLookupName (map (('f':) . show) [0 :: Int ..]) y t
z@(KBase KUTuple) -> newLookupName (map (('u':) . show) [0 :: Int ..]) z t
z@(KBase KQuest) -> newLookupName (map (('q':) . show) [0 :: Int ..]) z t
z@(KBase KQuestQuest) -> newLookupName (map (('q':) . ('q':) . show) [0 :: Int ..]) z t
z -> newLookupName (map (('t':) . show) [0 :: Int ..]) z t
prettyPrintType :: DocLike d => Type -> d
prettyPrintType = pprint
instance DocLike d => PPrint d Type where
pprintAssoc _ n t = prettyPrintTypePrec n t
prettyPrintTypePrec :: DocLike d => Int -> Type -> d
prettyPrintTypePrec n t = unparse $ zup (runIdentity (runVarNameT (f t))) where
zup = if n >= 10 then pop empty else id
arr = bop (R,0) (space <> text "->" <> space)
app = bop (L,100) (text " ")
fp (IsIn cn t) = do
t' <- f t
return (atom (text $ show cn) `app` t')
fp (IsEq t1 t2) = do
t1' <- f t1
t2' <- f t2
return (atom (parens $ unparse t1' <+> text "=" <+> unparse t2'))
f (TForAll [] ([] :=> t)) = f t
f (TForAll vs (ps :=> t)) = do
withNewNames vs $ \ts' -> do
t' <- f t
ps' <- mapM fp ps
return $ case ps' of
[] -> fixitize (N,-3) $ pop (text "forall" <+> hsep (map text ts') <+> text ". ") (atomize t')
[p] -> fixitize (N,-3) $ pop (text "forall" <+> hsep (map text ts') <+> text "." <+> unparse p <+> text "=> ") (atomize t')
ps -> fixitize (N,-3) $ pop (text "forall" <+> hsep (map text ts') <+> text "." <+> tupled (map unparse ps) <+> text "=> ") (atomize t')
f (TExists [] ([] :=> t)) = f t
f (TExists vs (ps :=> t)) = do
withNewNames vs $ \ts' -> do
t' <- f t
ps' <- mapM fp ps
return $ case ps' of
[] -> fixitize (N,-3) $ pop (text "exists" <+> hsep (map text ts') <+> text ". ") (atomize t')
[p] -> fixitize (N,-3) $ pop (text "exists" <+> hsep (map text ts') <+> text "." <+> unparse p <+> text "=> ") (atomize t')
ps -> fixitize (N,-3) $ pop (text "exists" <+> hsep (map text ts') <+> text "." <+> tupled (map unparse ps) <+> text "=> ") (atomize t')
f (TCon tycon) = return $ atom (pprint tycon)
f (TVar tyvar) = do
vo <- maybeLookupName tyvar
case vo of
Just c -> return $ atom $ text c
Nothing -> return $ atom $ tshow (tyvarName tyvar)
f (TAp (TCon (Tycon n _)) x) | n == tc_List = do
x <- f x
return $ atom (char '[' <> unparse x <> char ']')
f TAssoc { typeCon = con, typeClassArgs = cas, typeExtraArgs = eas } = do
let x = atom (pprint con)
xs <- mapM f (cas ++ eas)
return $ foldl app x xs
f ta@(TAp {}) | (TCon (Tycon c _),xs) <- fromTAp ta, Just _ <- fromTupname c = do
xs <- mapM f xs
return $ atom (tupled (map unparse xs))
f (TAp t1 t2) = do
t1 <- f t1
t2 <- f t2
return $ t1 `app` t2
f (TArrow t1 t2) = do
t1 <- f t1
t2 <- f t2
return $ t1 `arr` t2
f (TMetaVar mv) = return $ atom $ pprint mv
--f tv = return $ atom $ parens $ text ("FrontEnd.Tc.Type.pp: " ++ show tv)
instance DocLike d => PPrint d MetaVarType where
pprint t = case t of
Tau -> char 't'
Rho -> char 'r'
Sigma -> char 's'
instance DocLike d => PPrint d Pred where
pprint (IsIn c t) = tshow c <+> pprintParen t
pprint (IsEq t1 t2) = parens $ prettyPrintType t1 <+> text "=" <+> prettyPrintType t2
instance DocLike d => PPrint d MetaVar where
pprint MetaVar { metaUniq = u, metaKind = k, metaType = t }
| KBase Star <- k = pprint t <> tshow u
| otherwise = parens $ pprint t <> tshow u <> text " :: " <> pprint k
instance Show MetaVarType where
show mv = pprint mv
instance Show MetaVar where
show mv = pprint mv
fromTAp t = f t [] where
f (TArrow a b) rs = f (TAp (TAp tArrow a) b) rs
f (TAp a b) rs = f a (b:rs)
f t rs = (t,rs)
fromTArrow t = f t [] where
f (TArrow a b) rs = f b (a:rs)
f t rs = (reverse rs,t)
instance CanType MetaVar where
type TypeOf MetaVar = Kind
getType mv = metaKind mv
instance CanType Tycon where
type TypeOf Tycon = Kind
getType (Tycon _ k) = k
instance CanType Tyvar where
type TypeOf Tyvar = Kind
getType = tyvarKind
instance CanType Type where
type TypeOf Type = Kind
getType (TCon tc) = getType tc
getType (TVar u) = getType u
getType typ@(TAp t _) = case (getType t) of
(Kfun _ k) -> k
x -> error $ "Representation.getType: kind error in: " ++ (show typ)
getType (TArrow _l _r) = kindStar
getType (TForAll _ (_ :=> t)) = getType t
getType (TExists _ (_ :=> t)) = getType t
getType (TMetaVar mv) = getType mv
getType ta@TAssoc {} = getType (tassocToAp ta)
tTTuple [] = tUnit
tTTuple [_] = error "tTTuple"
tTTuple ts = foldl TAp (toTuple (length ts)) ts
tTTuple' ts = foldl TAp (TCon $ Tycon (name_UnboxedTupleConstructor typeLevel n) (foldr Kfun kindUTuple $ replicate n kindStar)) ts where
n = length ts
|
hvr/jhc
|
src/FrontEnd/Representation.hs
|
Haskell
|
mit
| 10,748
|
{-# LANGUAGE BangPatterns, CPP #-}
module RegAlloc.Graph.TrivColorable (
trivColorable,
)
where
#include "HsVersions.h"
import RegClass
import Reg
import GraphBase
import UniqFM
import FastTypes
import Platform
import Panic
-- trivColorable ---------------------------------------------------------------
-- trivColorable function for the graph coloring allocator
--
-- This gets hammered by scanGraph during register allocation,
-- so needs to be fairly efficient.
--
-- NOTE: This only works for arcitectures with just RcInteger and RcDouble
-- (which are disjoint) ie. x86, x86_64 and ppc
--
-- The number of allocatable regs is hard coded in here so we can do
-- a fast comparison in trivColorable.
--
-- It's ok if these numbers are _less_ than the actual number of free
-- regs, but they can't be more or the register conflict
-- graph won't color.
--
-- If the graph doesn't color then the allocator will panic, but it won't
-- generate bad object code or anything nasty like that.
--
-- There is an allocatableRegsInClass :: RegClass -> Int, but doing
-- the unboxing is too slow for us here.
-- TODO: Is that still true? Could we use allocatableRegsInClass
-- without losing performance now?
--
-- Look at includes/stg/MachRegs.h to get the numbers.
--
-- Disjoint registers ----------------------------------------------------------
--
-- The definition has been unfolded into individual cases for speed.
-- Each architecture has a different register setup, so we use a
-- different regSqueeze function for each.
--
accSqueeze
:: FastInt
-> FastInt
-> (reg -> FastInt)
-> UniqFM reg
-> FastInt
accSqueeze count maxCount squeeze ufm = acc count (eltsUFM ufm)
where acc count [] = count
acc count _ | count >=# maxCount = count
acc count (r:rs) = acc (count +# squeeze r) rs
{- Note [accSqueeze]
~~~~~~~~~~~~~~~~~~~~
BL 2007/09
Doing a nice fold over the UniqSet makes trivColorable use
32% of total compile time and 42% of total alloc when compiling SHA1.hs from darcs.
Therefore the UniqFM is made non-abstract and we use custom fold.
MS 2010/04
When converting UniqFM to use Data.IntMap, the fold cannot use UniqFM internal
representation any more. But it is imperative that the assSqueeze stops
the folding if the count gets greater or equal to maxCount. We thus convert
UniqFM to a (lazy) list, do the fold and stops if necessary, which was
the most efficient variant tried. Benchmark compiling 10-times SHA1.hs follows.
(original = previous implementation, folding = fold of the whole UFM,
lazyFold = the current implementation,
hackFold = using internal representation of Data.IntMap)
original folding hackFold lazyFold
-O -fasm (used everywhere) 31.509s 30.387s 30.791s 30.603s
100.00% 96.44% 97.72% 97.12%
-fregs-graph 67.938s 74.875s 62.673s 64.679s
100.00% 110.21% 92.25% 95.20%
-fregs-iterative 89.761s 143.913s 81.075s 86.912s
100.00% 160.33% 90.32% 96.83%
-fnew-codegen 38.225s 37.142s 37.551s 37.119s
100.00% 97.17% 98.24% 97.11%
-fnew-codegen -fregs-graph 91.786s 91.51s 87.368s 86.88s
100.00% 99.70% 95.19% 94.65%
-fnew-codegen -fregs-iterative 206.72s 343.632s 194.694s 208.677s
100.00% 166.23% 94.18% 100.95%
-}
trivColorable
:: Platform
-> (RegClass -> VirtualReg -> FastInt)
-> (RegClass -> RealReg -> FastInt)
-> Triv VirtualReg RegClass RealReg
trivColorable platform virtualRegSqueeze realRegSqueeze RcInteger conflicts exclusions
| let !cALLOCATABLE_REGS_INTEGER
= iUnbox (case platformArch platform of
ArchX86 -> 3
ArchX86_64 -> 5
ArchPPC -> 16
ArchSPARC -> 14
ArchPPC_64 -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_INTEGER
(virtualRegSqueeze RcInteger)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_INTEGER
(realRegSqueeze RcInteger)
exclusions
= count3 <# cALLOCATABLE_REGS_INTEGER
trivColorable platform virtualRegSqueeze realRegSqueeze RcFloat conflicts exclusions
| let !cALLOCATABLE_REGS_FLOAT
= iUnbox (case platformArch platform of
ArchX86 -> 0
ArchX86_64 -> 0
ArchPPC -> 0
ArchSPARC -> 22
ArchPPC_64 -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_FLOAT
(virtualRegSqueeze RcFloat)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_FLOAT
(realRegSqueeze RcFloat)
exclusions
= count3 <# cALLOCATABLE_REGS_FLOAT
trivColorable platform virtualRegSqueeze realRegSqueeze RcDouble conflicts exclusions
| let !cALLOCATABLE_REGS_DOUBLE
= iUnbox (case platformArch platform of
ArchX86 -> 6
ArchX86_64 -> 0
ArchPPC -> 26
ArchSPARC -> 11
ArchPPC_64 -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_DOUBLE
(virtualRegSqueeze RcDouble)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_DOUBLE
(realRegSqueeze RcDouble)
exclusions
= count3 <# cALLOCATABLE_REGS_DOUBLE
trivColorable platform virtualRegSqueeze realRegSqueeze RcDoubleSSE conflicts exclusions
| let !cALLOCATABLE_REGS_SSE
= iUnbox (case platformArch platform of
ArchX86 -> 8
ArchX86_64 -> 10
ArchPPC -> 0
ArchSPARC -> 0
ArchPPC_64 -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_SSE
(virtualRegSqueeze RcDoubleSSE)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_SSE
(realRegSqueeze RcDoubleSSE)
exclusions
= count3 <# cALLOCATABLE_REGS_SSE
-- Specification Code ----------------------------------------------------------
--
-- The trivColorable function for each particular architecture should
-- implement the following function, but faster.
--
{-
trivColorable :: RegClass -> UniqSet Reg -> UniqSet Reg -> Bool
trivColorable classN conflicts exclusions
= let
acc :: Reg -> (Int, Int) -> (Int, Int)
acc r (cd, cf)
= case regClass r of
RcInteger -> (cd+1, cf)
RcFloat -> (cd, cf+1)
_ -> panic "Regs.trivColorable: reg class not handled"
tmp = foldUniqSet acc (0, 0) conflicts
(countInt, countFloat) = foldUniqSet acc tmp exclusions
squeese = worst countInt classN RcInteger
+ worst countFloat classN RcFloat
in squeese < allocatableRegsInClass classN
-- | Worst case displacement
-- node N of classN has n neighbors of class C.
--
-- We currently only have RcInteger and RcDouble, which don't conflict at all.
-- This is a bit boring compared to what's in RegArchX86.
--
worst :: Int -> RegClass -> RegClass -> Int
worst n classN classC
= case classN of
RcInteger
-> case classC of
RcInteger -> min n (allocatableRegsInClass RcInteger)
RcFloat -> 0
RcDouble
-> case classC of
RcFloat -> min n (allocatableRegsInClass RcFloat)
RcInteger -> 0
-- allocatableRegs is allMachRegNos with the fixed-use regs removed.
-- i.e., these are the regs for which we are prepared to allow the
-- register allocator to attempt to map VRegs to.
allocatableRegs :: [RegNo]
allocatableRegs
= let isFree i = isFastTrue (freeReg i)
in filter isFree allMachRegNos
-- | The number of regs in each class.
-- We go via top level CAFs to ensure that we're not recomputing
-- the length of these lists each time the fn is called.
allocatableRegsInClass :: RegClass -> Int
allocatableRegsInClass cls
= case cls of
RcInteger -> allocatableRegsInteger
RcFloat -> allocatableRegsDouble
allocatableRegsInteger :: Int
allocatableRegsInteger
= length $ filter (\r -> regClass r == RcInteger)
$ map RealReg allocatableRegs
allocatableRegsFloat :: Int
allocatableRegsFloat
= length $ filter (\r -> regClass r == RcFloat
$ map RealReg allocatableRegs
-}
|
christiaanb/ghc
|
compiler/nativeGen/RegAlloc/Graph/TrivColorable.hs
|
Haskell
|
bsd-3-clause
| 12,047
|
{-# LANGUAGE TypeFamilies, FlexibleInstances, FlexibleContexts, UndecidableInstances,
MultiParamTypeClasses, FunctionalDependencies #-}
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
module T10139 where
import Data.Monoid
import Data.Kind
import Data.Coerce
class Monoid v => Measured v a | a -> v where
_measure :: v -> a
data FingerTree v a = Dummy v a
singleton :: Measured v a => a -> FingerTree v a
singleton = undefined
class DOps a where
plus :: a -> D a -> a
type family D a :: Type
type instance D (FingerTree (Size Int, v) (Sized a)) = [Diff (Normal a)]
type family Normal a :: Type
data Diff a = Add Int a
newtype Sized a = Sized a
newtype Size a = Size a
-- This works:
{-
instance (Measured (Size Int, v) (Sized a), Coercible (Normal a) (Sized a)) => DOps (FingerTree (Size Int, v) (Sized a)) where
plus = foldr (\(Add index val) seq -> singleton ((coerce) val))
-}
-- This hangs:
instance (Measured (Size Int, v) (Sized a), Coercible (Normal a) (Sized a)) => DOps (FingerTree (Size Int, v) (Sized a)) where
plus = foldr (flip f)
where f _seq x = case x of
Add _index val -> singleton ((coerce) val)
|
sdiehl/ghc
|
testsuite/tests/indexed-types/should_compile/T10139.hs
|
Haskell
|
bsd-3-clause
| 1,165
|
{-# OPTIONS_GHC -fcontext-stack=1000 #-}
{-# LANGUAGE
FlexibleContexts, FlexibleInstances, FunctionalDependencies,
MultiParamTypeClasses, OverlappingInstances, TypeSynonymInstances,
TypeOperators, UndecidableInstances, TypeFamilies #-}
module T5321Fun where
-- As the below code demonstrates, the same issues demonstrated with
-- Functional Dependencies also appear with Type Families, although less
--horribly, as their code-path seems more optimized in the current
-- constraint solver:
-- Our running example, for simplicity's sake, is a type-level map of a
-- single function. For reference, here is the code for a simple
-- value-level map of a single function.
-- > vfoo = id
-- > mapfoo (x : xs) = vfoo x : mapfoo xs
-- > mapfoo [] = []
-- Because Haskell is a lazy language, this runs in O(n) time and constant stack.
-- We now lift map to the type level, to operate over HLists.
-- First, the basic HList types
infixr 3 :*
data x :* xs = x :* xs deriving Show
data HNil = HNil deriving Show
-- Next, a large boring HList
-- Adds ten cells
addData x = i :* i :* d :* d :* s :*
i :* i :* d :* d :* s :*
x
where i = 1 :: Int
d = 1 :: Double
s = ""
-- Has 70 cells.
sampleData = addData $ addData $ addData $ addData $ addData $
addData $ addData $
HNil
class TFoo x where
type TFooFun x
tfoo :: x -> TFooFun x
tfoo = undefined
instance TFoo Int where
type TFooFun Int = Double
instance TFoo Double where
type TFooFun Double = Int
instance TFoo String where
type TFooFun String = String
class THMapFoo1 as where
type THMapFoo1Res as
thMapFoo1 :: as -> THMapFoo1Res as
instance (TFoo a, THMapFoo1 as) => THMapFoo1 (a :* as) where
type THMapFoo1Res (a :* as) = TFooFun a :* THMapFoo1Res as
thMapFoo1 (x :* xs) = tfoo x :* thMapFoo1 xs
instance THMapFoo1 HNil where
type THMapFoo1Res HNil = HNil
thMapFoo1 _ = HNil
-- The following, when enabled, takes ~3.5s. This demonstrates that slowdown occurs with type families as well.
testTHMapFoo1 = thMapFoo1 sampleData
class THMapFoo2 acc as where
type THMapFoo2Res acc as
thMapFoo2 :: acc -> as -> THMapFoo2Res acc as
instance (TFoo a, THMapFoo2 (TFooFun a :* acc) as) => THMapFoo2 acc (a :* as) where
type THMapFoo2Res acc (a :* as) = THMapFoo2Res (TFooFun a :* acc) as
thMapFoo2 acc (x :* xs) = thMapFoo2 (tfoo x :* acc) xs
instance THMapFoo2 acc HNil where
type THMapFoo2Res acc HNil = acc
thMapFoo2 acc _ = acc
-- The following, when enabled, takes ~0.6s. This demonstrates that the
-- tail recursive transform fixes the slowdown with type families just as
-- with fundeps.
testTHMapFoo2 = thMapFoo2 HNil sampleData
class THMapFoo3 acc as where
type THMapFoo3Res acc as
thMapFoo3 :: acc -> as -> THMapFoo3Res acc as
instance (THMapFoo3 (TFooFun a :* acc) as, TFoo a) => THMapFoo3 acc (a :* as) where
type THMapFoo3Res acc (a :* as) = THMapFoo3Res (TFooFun a :* acc) as
thMapFoo3 acc (x :* xs) = thMapFoo3 (tfoo x :* acc) xs
instance THMapFoo3 acc HNil where
type THMapFoo3Res acc HNil = acc
thMapFoo3 acc _ = acc
-- The following, when enabled, also takes ~0.6s. This demonstrates that,
-- unlike the fundep case, the order of type class constraints does not,
-- in this instance, affect the performance of type families.
testTHMapFoo3 = thMapFoo3 HNil sampleData
|
frantisekfarka/ghc-dsi
|
testsuite/tests/perf/compiler/T5321Fun.hs
|
Haskell
|
bsd-3-clause
| 3,485
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.ForeignPtr.Safe
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- The 'ForeignPtr' type and operations. This module is part of the
-- Foreign Function Interface (FFI) and will usually be imported via
-- the "Foreign" module.
--
-- Safe API Only.
--
-----------------------------------------------------------------------------
module Foreign.ForeignPtr.Safe (
-- * Finalised data pointers
ForeignPtr
, FinalizerPtr
, FinalizerEnvPtr
-- ** Basic operations
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
, withForeignPtr
, finalizeForeignPtr
-- ** Low-level operations
, touchForeignPtr
, castForeignPtr
-- ** Allocating managed memory
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
) where
import Foreign.ForeignPtr.Imp
|
ryantm/ghc
|
libraries/base/Foreign/ForeignPtr/Safe.hs
|
Haskell
|
bsd-3-clause
| 1,340
|
{-# LANGUAGE TypeFamilies #-}
module Hadrian.Oracles.ArgsHash (
TrackArgument, trackAllArguments, trackArgsHash, argsHashOracle
) where
import Control.Monad
import Development.Shake
import Development.Shake.Classes
import Hadrian.Expression hiding (inputs, outputs)
import Hadrian.Target
-- | 'TrackArgument' is used to specify the arguments that should be tracked by
-- the @ArgsHash@ oracle. The safest option is to track all arguments, but some
-- arguments, such as @-jN@, do not change the build results, hence there is no
-- need to initiate unnecessary rebuild if they are added to or removed from a
-- command line. If all arguments should be tracked, use 'trackAllArguments'.
type TrackArgument c b = Target c b -> String -> Bool
-- | Returns 'True' for all targets and arguments, hence can be used a safe
-- default for 'argsHashOracle'.
trackAllArguments :: TrackArgument c b
trackAllArguments _ _ = True
-- | Given a 'Target' this 'Action' determines the corresponding argument list
-- and computes its hash. The resulting value is tracked in a Shake oracle,
-- hence initiating rebuilds when the hash changes (a hash change indicates
-- changes in the build command for the given target).
-- Note: for efficiency we replace the list of input files with its hash to
-- avoid storing long lists of source files passed to some builders (e.g. ar)
-- in the Shake database. This optimisation is normally harmless, because
-- argument list constructors are assumed not to examine target sources, but
-- only append them to argument lists where appropriate.
trackArgsHash :: (ShakeValue c, ShakeValue b) => Target c b -> Action ()
trackArgsHash t = do
let hashedInputs = [ show $ hash (inputs t) ]
hashedTarget = target (context t) (builder t) hashedInputs (outputs t)
void (askOracle $ ArgsHash hashedTarget :: Action Int)
newtype ArgsHash c b = ArgsHash (Target c b)
deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
type instance RuleResult (ArgsHash c b) = Int
-- | This oracle stores per-target argument list hashes in the Shake database,
-- allowing the user to track them between builds using 'trackArgsHash' queries.
argsHashOracle :: (ShakeValue c, ShakeValue b) => TrackArgument c b -> Args c b -> Rules ()
argsHashOracle trackArgument args = void $
addOracle $ \(ArgsHash target) -> do
argList <- interpret target args
let trackedArgList = filter (trackArgument target) argList
return $ hash trackedArgList
|
snowleopard/shaking-up-ghc
|
src/Hadrian/Oracles/ArgsHash.hs
|
Haskell
|
bsd-3-clause
| 2,494
|
module NegativeIn1 where
f x y = x + y
|
kmate/HaRe
|
old/testing/introCase/NegativeIn1_TokOut.hs
|
Haskell
|
bsd-3-clause
| 42
|
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, UndecidableInstances #-}
module Tc173a where
class FormValue value where
isFormValue :: value -> ()
isFormValue _ = ()
class FormTextField value
instance FormTextField String
instance {-# OVERLAPPABLE #-} FormTextField value => FormTextFieldIO value
class FormTextFieldIO value
instance FormTextFieldIO value => FormValue value
instance {-# OVERLAPPING #-} FormTextFieldIO value => FormTextFieldIO (Maybe value)
|
christiaanb/ghc
|
testsuite/tests/typecheck/should_compile/Tc173a.hs
|
Haskell
|
bsd-3-clause
| 533
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
module Text.Regex.Applicative.Types where
import Control.Applicative
import Control.Monad ((<=<))
import Data.Filtrable (Filtrable (..))
import Data.Functor.Identity (Identity (..))
import Data.String
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup
#endif
newtype ThreadId = ThreadId Int
-- | A thread either is a result or corresponds to a symbol in the regular
-- expression, which is expected by that thread.
data Thread s r
= Thread
{ threadId_ :: ThreadId
, _threadCont :: s -> [Thread s r]
}
| Accept r
-- | Returns thread identifier. This will be 'Just' for ordinary threads and
-- 'Nothing' for results.
threadId :: Thread s r -> Maybe ThreadId
threadId Thread { threadId_ = i } = Just i
threadId _ = Nothing
data Greediness = Greedy | NonGreedy
deriving (Show, Read, Eq, Ord, Enum)
-- | Type of regular expressions that recognize symbols of type @s@ and
-- produce a result of type @a@.
--
-- Regular expressions can be built using 'Functor', 'Applicative',
-- 'Alternative', and 'Filtrable' instances in the following natural way:
--
-- * @f@ '<$>' @ra@ matches iff @ra@ matches, and its return value is the result
-- of applying @f@ to the return value of @ra@.
--
-- * 'pure' @x@ matches the empty string (i.e. it does not consume any symbols),
-- and its return value is @x@
--
-- * @rf@ '<*>' @ra@ matches a string iff it is a concatenation of two
-- strings: one matched by @rf@ and the other matched by @ra@. The return value
-- is @f a@, where @f@ and @a@ are the return values of @rf@ and @ra@
-- respectively.
--
-- * @ra@ '<|>' @rb@ matches a string which is accepted by either @ra@ or @rb@.
-- It is left-biased, so if both can match, the result of @ra@ is used.
--
-- * 'empty' is a regular expression which does not match any string.
--
-- * 'many' @ra@ matches concatenation of zero or more strings matched by @ra@
-- and returns the list of @ra@'s return values on those strings.
--
-- * 'some' @ra@ matches concatenation of one or more strings matched by @ra@
-- and returns the list of @ra@'s return values on those strings.
--
-- * 'catMaybes' @ram@ matches iff @ram@ matches and produces 'Just _'.
--
-- * @ra@ '<>' @rb@ matches @ra@ followed by @rb@. The return value is @a <> b@,
-- where @a@ and @b@ are the return values of @ra@ and @rb@ respectively.
-- (See <https://github.com/feuerbach/regex-applicative/issues/37#issue-499781703>
-- for an example usage.)
--
-- * 'mempty' matches the empty string (i.e. it does not consume any symbols),
-- and its return value is the 'mempty' value of type @a@.
data RE s a where
Eps :: RE s ()
Symbol :: ThreadId -> (s -> Maybe a) -> RE s a
Alt :: RE s a -> RE s a -> RE s a
App :: RE s (a -> b) -> RE s a -> RE s b
Fmap :: (a -> b) -> RE s a -> RE s b
CatMaybes :: RE s (Maybe a) -> RE s a
Fail :: RE s a
Rep :: Greediness -- repetition may be greedy or not
-> (b -> a -> b) -- folding function (like in foldl)
-> b -- the value for zero matches, and also the initial value
-- for the folding function
-> RE s a
-> RE s b
Void :: RE s a -> RE s ()
-- | Traverse each (reflexive, transitive) subexpression of a 'RE', depth-first and post-order.
traversePostorder :: forall s a m . Monad m => (forall a . RE s a -> m (RE s a)) -> RE s a -> m (RE s a)
traversePostorder f = go
where
go :: forall a . RE s a -> m (RE s a)
go = f <=< \ case
Eps -> pure Eps
Symbol i p -> pure (Symbol i p)
Alt a b -> Alt <$> go a <*> go b
App a b -> App <$> go a <*> go b
Fmap g a -> Fmap g <$> go a
CatMaybes a -> CatMaybes <$> go a
Fail -> pure Fail
Rep greed g b a -> Rep greed g b <$> go a
Void a -> Void <$> go a
-- | Fold each (reflexive, transitive) subexpression of a 'RE', depth-first and post-order.
foldMapPostorder :: Monoid b => (forall a . RE s a -> b) -> RE s a -> b
foldMapPostorder f = fst . traversePostorder ((,) <$> f <*> id)
-- | Map each (reflexive, transitive) subexpression of a 'RE'.
mapRE :: (forall a . RE s a -> RE s a) -> RE s a -> RE s a
mapRE f = runIdentity . traversePostorder (Identity . f)
instance Functor (RE s) where
fmap f x = Fmap f x
f <$ x = pure f <* x
instance Applicative (RE s) where
pure x = const x <$> Eps
a1 <*> a2 = App a1 a2
a *> b = pure (const id) <*> Void a <*> b
a <* b = pure const <*> a <*> Void b
instance Alternative (RE s) where
a1 <|> a2 = Alt a1 a2
empty = Fail
many a = reverse <$> Rep Greedy (flip (:)) [] a
some a = (:) <$> a <*> many a
-- | @since 0.3.4
instance Filtrable (RE s) where
catMaybes = CatMaybes
instance (char ~ Char, string ~ String) => IsString (RE char string) where
fromString = string
-- | @since 0.3.4
instance Semigroup a => Semigroup (RE s a) where
x <> y = (<>) <$> x <*> y
-- | @since 0.3.4
instance Monoid a => Monoid (RE s a) where
mempty = pure mempty
-- | Match and return the given sequence of symbols.
--
-- Note that there is an 'IsString' instance for regular expression, so
-- if you enable the @OverloadedStrings@ language extension, you can write
-- @string \"foo\"@ simply as @\"foo\"@.
--
-- Example:
--
-- >{-# LANGUAGE OverloadedStrings #-}
-- >import Text.Regex.Applicative
-- >
-- >number = "one" *> pure 1 <|> "two" *> pure 2
-- >
-- >main = print $ "two" =~ number
string :: Eq a => [a] -> RE a [a]
string = traverse sym
-- | Match and return a single symbol which satisfies the predicate
psym :: (s -> Bool) -> RE s s
psym p = msym (\s -> if p s then Just s else Nothing)
-- | Like 'psym', but allows to return a computed value instead of the
-- original symbol
msym :: (s -> Maybe a) -> RE s a
msym p = Symbol (error "Not numbered symbol") p
-- | Match and return the given symbol
sym :: Eq s => s -> RE s s
sym s = psym (s ==)
|
feuerbach/regex-applicative
|
Text/Regex/Applicative/Types.hs
|
Haskell
|
mit
| 6,009
|
module Rocketfuel.Grid (
generateRandomGrid,
afterMove,
applySwap,
getFallingTiles,
hasMoves
) where
import Data.Array
import Data.List
import Data.List.Split (chunksOf)
import Data.Maybe
import Data.Natural
import Control.Monad.Writer
import Control.Monad.Random
import Rocketfuel.Types
-- These lines allow us to run random and randomR on an enum
getRandomR' :: (MonadRandom m, Enum a, Bounded a) => (a,a) -> m a
getRandomR' (a, b) = uniform [a..b]
generateRandomCell :: (MonadRandom r) => r Cell
generateRandomCell = getRandomR'(Fuel, Navigate)
generateRandomLine :: (MonadRandom r) => r Line
generateRandomLine = replicateM 8 (liftM Just generateRandomCell)
generateRandomGrid :: (MonadRandom r) => r GameGrid
generateRandomGrid = replicateM 8 generateRandomLine
emptyAndLogIfAboveThree :: Line -> Writer [Effect] Line
emptyAndLogIfAboveThree line
| length line' >= 3 = let effect = [Effect (head line') (length line')] in
tell effect
>> mapM (\_ -> return Nothing) line
| otherwise = return line
where line' = catMaybes line
emptyRepeted :: Line -> Writer [Effect] Line
emptyRepeted l = do groups <- return . group $ l
result <- mapM emptyAndLogIfAboveThree groups
return . concat $ result
-- | Basic utility to get a clockwise 90° rotation on the grid,
-- useful to handle columns as if they were lines.
--
-- >>> rotateGrid [[Just Fuel,Just Repair,Just Trade],[Just Fuel,Just Shoot,Just Navigate],[Just Fuel,Just Trade,Just Trade]]
-- [[Just Fuel,Just Fuel,Just Fuel],[Just Repair,Just Shoot,Just Trade],[Just Trade,Just Navigate,Just Trade]]
rotateGrid :: Grid a -> Grid a
rotateGrid = transpose
-- | Basic utility to get a 90° counterclockwise 90° rotation on the grid.
-- >>> rotateGrid [[Just Fuel,Just Fuel,Just Fuel],[Just Repair,Just Shoot,Just Trade],[Just Trade,Just Navigate,Nothing]]
-- [[Just Fuel,Just Repair,Just Trade],[Just Fuel,Just Shoot,Just Navigate],[Just Fuel,Just Trade,Nothing]]
unrotateGrid :: Grid a -> Grid a
unrotateGrid = transpose . transpose . transpose
-- | The main matching function that will look for matches in lines and columns,
-- and log each matches.
emptyGrid :: GameGrid -> Writer [Effect] GameGrid
emptyGrid g = emptyLines g >>= emptyColumns
where emptyLines :: GameGrid -> Writer [Effect] GameGrid
emptyLines = mapM emptyRepeted
emptyColumns :: GameGrid -> Writer [Effect] GameGrid
emptyColumns g' = do let rotated = rotateGrid g'
columnsEmptied <- emptyLines rotated
return $ unrotateGrid columnsEmptied
-- |Find the index of the LAST element of a list
-- matching a predicate.
-- >>> findLastIndex (==2) [2,2,2,2]
-- Just (Natural 3)
-- >>> findLastIndex (==2) []
-- Nothing
-- >>> findLastIndex (==2) [1,3,5]
-- Nothing
-- >>> findLastIndex (=='z') "zoning zoning"
-- Just (Natural 7)
findLastIndex :: (a -> Bool) -> [a] -> Maybe Natural
findLastIndex p xs = fmap reverseIndex (findIndex p . reverse $ xs)
where maxIndex = length xs - 1
reverseIndex :: Int -> Natural
reverseIndex = natural . fromIntegral . (-) maxIndex
getFallingTiles :: GameGrid -> Moves
getFallingTiles = map gravityColumn . rotateGrid
where gravityColumn :: Line -> Maybe Natural
gravityColumn = findLastIndex isNothing
-- >>> gravity [[Just Fuel,Just Fuel,Just Repair,Just Shoot],[Nothing,Nothing,Nothing,Nothing],[Just Fuel,Nothing,Just Trade,Nothing]]
-- [[Nothing,Nothing,Nothing,Nothing],[Just Fuel,Nothing,Just Repair,Nothing],[Just Fuel,Just Fuel,Just Trade,Just Shoot]]
gravity :: GameGrid -> GameGrid
gravity = tail . unrotateGrid . map gravityColumn . rotateGrid
where
gravityColumn :: Line -> Line
gravityColumn = until filledAtBottom falling
filledAtBottom :: Line -> Bool
filledAtBottom = anyNull . break isNothing
falling :: Line -> Line
falling (x:Nothing:ys) = Nothing:falling (x:ys)
falling (x:y:ys) = x:falling (y:ys)
falling ys = ys
anyNull (f, s) = null f || null s
-- |Used before calling gravity.
prependGrid :: (MonadRandom r) => GameGrid -> r GameGrid
prependGrid ls = do newLine <- generateRandomLine
return $ newLine:ls
containsEmptyCells :: GameGrid -> Bool
-- |Check if a grill contains any empty cell.
-- >>> containsEmptyCells [[Just Fuel, Just Fuel], [Nothing, Just Shoot]]
-- True
-- >>> containsEmptyCells [[Just Fuel, Just Fuel], [Just Shoot, Just Shoot]]
-- False
containsEmptyCells = any isNothing . concat
-- | Call gravity till there is no empty cell left in the grid
gravityLoop :: (MonadRandom r) => GameGrid -> r GameGrid
gravityLoop g
| containsEmptyCells g = liftM gravity (prependGrid g) >>= gravityLoop
| otherwise = return g
-- | After a given move, we must :
-- - Check for matchs.
-- - If matches were made, apply gravity and loop.
-- - If no matches were made, return the grid and the effects.
afterMove :: (MonadRandom r) => GameGrid -> r (GameGrid, [Effect])
afterMove = afterMove' []
where
afterMove' :: (MonadRandom r) => [Effect] -> GameGrid -> r (GameGrid, [Effect])
afterMove' eff g = case runWriter (emptyGrid g) of
(g', []) -> return (g', eff)
(g', e) -> do afterGravity <- gravityLoop g'
afterMove' (eff ++ e) afterGravity
-- | Applying a swap means :
-- 1°) Transform the grid into a single array to allow for easier
-- manipulation
-- 2°) Swap the position in the single array
-- 3°) Transform the array back into a list
--
applySwap :: Swap -> GameGrid -> GameGrid
applySwap (Swap p1 p2) g = rebuild . elems $ toArray // [(oneIdx, twoValue), (twoIdx, oneValue)]
where
toArray :: Array Integer Cell
toArray = listArray (0, 63) . concatMap catMaybes $ g
idx2Dto1D :: Position -> Integer
idx2Dto1D (x, y) = y*8 + x
oneIdx = idx2Dto1D p1
twoIdx = idx2Dto1D p2
oneValue = toArray ! oneIdx
twoValue = toArray ! twoIdx
rebuild = map (map Just) . chunksOf 8
-- |Given a list of moves, check if there is any current move.
-- This simply means checking that the list of Moves (one per column in the grid)
-- is only made out of Nothing.
--
-- >>> hasMoves [Nothing, Nothing, Nothing]
-- False
-- >>> hasMoves [Nothing, Nothing, Just 3]
-- True
hasMoves :: Moves -> Bool
hasMoves = any (isJust)
|
Raveline/Rocketfuel
|
src/Rocketfuel/Grid.hs
|
Haskell
|
mit
| 6,579
|
{-# LANGUAGE PatternGuards #-}
module Tarefa3_2017li1g180 where
import LI11718
import Tarefa2_2017li1g180
import Test.QuickCheck.Gen
import Data.List
import Data.Maybe
import Safe
testesT3 :: [(Tabuleiro,Tempo,Carro)]
testesT3 = unitTests
randomizeCarro :: Tabuleiro -> Double -> Carro -> Gen Carro
randomizeCarro tab delta c = do
suchThat genC (validaCarro tab)
where
(x,y) = posicao c
genC = do
dx <- choose (0,delta)
dy <- choose (0,delta)
let x' = x + dx
let y' = y + dy
return c { posicao = (x',y') }
ranksT3 :: [(Tabuleiro,Tempo,Carro)]
ranksT3 = unitTests
-- Nuno/Hugo's simpler version
-- ranksT3Nuno :: [(Tabuleiro,Tempo,Carro)]
-- ranksT3Nuno = [(tab1,5,carro1)]
-- where
-- tab1 = [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
-- ,[Peca Lava altLava, Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2, Peca Lava altLava]
-- ,[Peca Lava altLava, Peca Recta 2,Peca Lava altLava,Peca Recta 2, Peca Lava altLava]
-- ,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2, Peca Lava altLava]
-- ,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
-- ]
-- carro1 = Carro (3,3) 30 (2,1.5)
solutionsT3 :: [((Tabuleiro,Tempo,Carro),Maybe Carro)]
solutionsT3 = zip ranksT3 (map aux ranksT3)
where
aux x@(tab,tempo,carro) = movimenta tab tempo carro
compareT3Solutions :: Double -> Maybe Carro -> Maybe Carro -> Double
compareT3Solutions distance Nothing Nothing = 100
compareT3Solutions distance Nothing (Just y) = 0
compareT3Solutions distance (Just x) Nothing = 0
compareT3Solutions distance (Just x) (Just y) = (pos+dir+vel) / 3
where
pos = if distance == 0 then 100 else (1 - dist (posicao x) (posicao y) / distance) * 100
dir = (1 - (normAngulo (abs (direcao x - direcao y))) / 360) * 100
vel = if distance == 0 then 100 else (1 - dist (velocidade x) (velocidade y) / distance) * 100
normAngulo x = if x >= 360 then normAngulo (x - 360) else x
genTempo :: Gen Tempo
genTempo = choose (0,30)
validaCarro :: Tabuleiro -> Carro -> Bool
validaCarro tab carro = validaPonto (posicao carro) tab && (not $ derrete tab (posicao carro))
derrete :: Tabuleiro -> Ponto -> Bool
derrete t p = derrete' tp a
where
(i,j) = ponto2Pos p
a = denorm p (i,j)
Peca tp _ = (atNote "derrete" (atNote "derrete" t j) i)
derrete' :: Tipo -> Ponto -> Bool
derrete' Lava _ = True
-- hpacheco: mudei para incluir parede
derrete' (Curva Norte) (x,y) = x < (1-y)
derrete' (Curva Este) (x,y) = x > y
derrete' (Curva Sul) (x,y) = x > (1-y)
derrete' (Curva Oeste) (x,y) = x < y
derrete' _ _ = False
movimenta :: Tabuleiro -> Tempo -> Carro -> Maybe Carro
movimenta m t c = case (colideLocal m v (a,b) i) of
Nothing -> Nothing
Just (p',v') -> Just $ c { posicao = p', velocidade = v' }
where a = posicao c
v = velocidade c
b = a .+. (t .*. v)
i = ponto2Pos a
bounce :: (Double,Double) -> (Double,Double) -> (Double,Double)
bounce (d,a1) (1,a2) = componentsToArrow $ (arrowToComponents (d,a1)) .+. (-x,-y)
where dp = 2 * (arrowToComponents (d,a1) .$. arrowToComponents (1,a2))
(x,y) = dp .*. (arrowToComponents (1,a2))
colideLocal :: Tabuleiro -> Velocidade -> (Ponto,Ponto) -> Posicao -> Maybe (Ponto,Velocidade)
colideLocal e v ab ij = case colideLocalAcc [] e v ab ij of
(l,Just v) -> Just (last l,v)
(_,Nothing) -> Nothing
colideLocalAcc :: [Ponto] -> Tabuleiro -> Velocidade -> (Ponto,Ponto) -> Posicao -> ([Ponto],Maybe Velocidade)
colideLocalAcc ps m v (a,b) (i,j) | morto = (ps++[a,b],Nothing)
| colideInterno = colideLocalAcc (ps++[a]) m iVel iPos (i,j) -- se houverem colisões internas (diagonais), da prioridade e volta a aplicar novo vector
| dentroPeca (a,b) (i,j) g = (ps++[a,b],Just v) -- caso contrario, se estiver dentro da peça pode parar
| colideExterno = colideLocalAcc (ps++[a]) m eVel ePos (i,j) -- se passar para fora da peça mas houver parede, colide na parede e volta a aplicar novo vector
| otherwise = colideLocalAcc (ps++[a]) m v (aPos,b) ij' -- se passar para fora da peça mas não houver parede, chama na peça seguinte
where (_,g) = componentsToArrow (b.-.a)
morto = (isJust int && isNothing (fromJust int)) || (colideExterno && not (fromJust $ temParede m (i,j) (fromJust ext)))
int = colisaoInterna (atNote "colideLocalAcc" (atNote "colideLocalAcc" m j) i) (i,j) (a,b)
colideInterno = isJust int && isJust (fromJust int) && colisaoRelevante (a,b) (fromJust (fromJust int))
(iPos,iVel) = inv v (a,b) (fromJust int)
ext = atravessaOnde (i,j) (a,b)
colideExterno = isJust ext && (isJust . temParede m (i,j)) (fromJust ext)
(ePos,eVel) = inv v (a,b) (Just (norm (fst (fromJust ext)) (i,j),snd (fromJust ext)))
(aPos,aVel) = (norm (fst (fromJust ext)) (i,j), snd (fromJust ext))
ij' = atravessa aVel (i,j)
norm (x,y) (i,j) = (x+toEnum i,y+toEnum j)
denorm (x,y) (i,j) = (x-toEnum i,y-toEnum j)
-- dada uma velocidade e um deslocamento, inverte ambos dada uma colisão
inv :: Velocidade -> (Ponto,Ponto) -> Maybe (Ponto,Double) -> ((Ponto,Ponto),Velocidade)
inv v ab Nothing = (ab,v)
inv v ab (Just (c,g)) = ((c,d),arrowToComponents (vd,v'))
where (_,d,v') = inverte ab c g
(vd,_) = componentsToArrow v
inverte :: (Ponto,Ponto) -> Ponto -> Double -> (Ponto,Ponto,Double)
inverte (a,b) c g = (c,d,v')
where (z,v') = bounce (componentsToArrow (b .-. c)) (1,g)
d = c .+. arrowToComponents (z,v')
-- dada uma peça e um segmento (relativo à peça), detecta colisoes e devolve angulo da normal
-- colisões internas apenas acontecem em diagonais e no maximo uma
colisaoInterna :: Peca -> Posicao -> (Ponto,Ponto) -> Maybe (Maybe (Ponto,Double))
colisaoInterna (Peca (Curva d) al) ij (a,b) | d == Norte || d == Sul = f (intersecta ab ((1,0),(0,1))) (135 + dlt)
| otherwise = f (intersecta ab ((0,0),(1,1))) (45 + dlt)
where f :: Maybe Ponto -> Double -> Maybe (Maybe (Ponto,Double))
f Nothing _ = Nothing
f (Just a) b | al < altLava = Just $ Just (norm a ij,b)
| otherwise = Just Nothing
dlt = if d == Norte || d == Este then 180 else 0
ab = (denorm a ij, denorm b ij)
colisaoInterna _ _ _ = Nothing
-- se o movimento mantem-se dentro da peça
dentroPeca :: (Ponto,Ponto) -> Posicao -> Double -> Bool
dentroPeca (a,b) (i,j) g = belongs b
where belongs (x,y) = (x == toEnum i+1 || floor x == i) && (floor y == j || y == toEnum j+1)
-- dado um segmento (relativo à peça), calcula pontos de interceção e angulos das normais
-- entre 0 e 2 no caso extremo (segmento que começa em cima da linha e atravessa outra)
atravessaOnde :: Posicao -> (Ponto,Ponto) -> Maybe (Ponto, Double)
atravessaOnde ij (x,y) | null rel = Nothing
| length rel == 1 = Just (head rel)
| otherwise = Just (last rel) --error $ "Duas travessias: "++(show rel)
where rel = filter (colisaoRelevante (x,y)) $ normalize $ zip is [0,270,90,180]
is = [intersecta xy ((i,i),(toEnum j,toEnum $ (j+1)`mod`2)) | i <- [0,1], j <- [0,1]]
normalize = catMaybes . map (\(a,b) -> if (isJust a) then Just (fromJust a,b) else Nothing)
xy = (denorm x ij, denorm y ij)
-- para uma peça e uma aresta, testa se vai haver colisão
temParede :: Tabuleiro -> Posicao -> (Ponto,Double) -> Maybe Bool
temParede m (i,j) c | t == Lava = Just (a1 < altLava)
| snd c == 270 && (t == Curva Sul || t == Curva Oeste) = Just (a1 < altLava)
| snd c == 180 && (t == Curva Norte || t == Curva Oeste) = Just (a1 < altLava)
| snd c == 90 && (t == Curva Norte || t == Curva Este) = Just (a1 < altLava)
| snd c == 0 && (t == Curva Sul || t == Curva Este) = Just (a1 < altLava)
| middle && mwall t0 (fst c) && aa > aa' = Just True
| middle && mfall t0 (fst c) && aa < aa' = Just False
| a2 > a1 = Just True
| a2 < a1 = Just False
| otherwise = Nothing
where (i',j') = atravessa (snd c) (i,j)
Peca t aa = atNote "temParede" (atNote "temParede" m j') i'
Peca t0 aa' = atNote "temParede" (atNote "temParede" m j) i
isR (Rampa _) = True
isR _ = False
(a1,a2) = normAlturas (atNote "temParede" (atNote "temParede" m j) i) (atNote "temParede" (atNote "temParede" m j') i')
middle = case t of (Rampa x) -> t0 == (Rampa (toEnum (((fromEnum x) + 2) `mod` 4))) && (abs $ aa-aa') == 1
otherwise -> False
mwall (Rampa Oeste) (x,y) = x >= 0.5
mwall (Rampa Este) (x,y) = x <= 0.5
mwall (Rampa Norte) (x,y) = y >= 0.5
mwall (Rampa Sul) (x,y) = y <= 0.5
mfall r p = not $ mwall r p
normAlturas :: Peca -> Peca -> (Altura,Altura)
normAlturas (Peca (Rampa _) a1) p@(Peca _ a2) | a2 > a1 = normAlturas (Peca Recta (a1+1)) p
| otherwise = normAlturas (Peca Recta a1) p
normAlturas p@(Peca _ a1) (Peca (Rampa _) a2) | a2 < a1 = normAlturas p (Peca Recta (a2+1))
| otherwise = normAlturas p (Peca Recta a2)
normAlturas (Peca _ a1) (Peca _ a2) = (a1,a2)
-- dado o angulo de travessia, da a nova posiçao
atravessa :: Double -> Posicao -> Posicao
atravessa 270 (i,j) = (i,j-1)
atravessa 90 (i,j) = (i,j+1)
atravessa 0 (i,j) = (i-1,j)
atravessa 180 (i,j) = (i+1,j)
-- dado o deslocamento e o ponto de colisão com o angulo da normal, testa de é relevante
-- é relevante se a diferença de angulos > 90º
colisaoRelevante :: (Ponto,Ponto) -> (Ponto,Double) -> Bool
colisaoRelevante ((a1,a2),(b1,b2)) ((x,y),a) = diff > 90 && diff < 270
where (_,a') = componentsToArrow (b1-a1,b2-a2)
diff = f (a-a')
f x | x < 0 = f (x+360)
| x > 360 = f (x-360)
| otherwise = x
-- geometry
-- copiado do Gloss para Double
intersecta :: (Ponto,Ponto) -> (Ponto,Ponto) -> Maybe Ponto
intersecta (p1,p2) (p3,p4) | Just p0 <- intersectaL p1 p2 p3 p4
, t12 <- closestPontoOnL p1 p2 p0
, t23 <- closestPontoOnL p3 p4 p0
, t12 >= 0 && t12 <= 1
, t23 >= 0 && t23 <= 1
= Just p0
| otherwise
= Nothing
-- copiado do Gloss para Double
intersectaL :: Ponto -> Ponto -> Ponto -> Ponto -> Maybe Ponto
intersectaL (x1, y1) (x2, y2) (x3, y3) (x4, y4)
= let dx12 = x1 - x2
dx34 = x3 - x4
dy12 = y1 - y2
dy34 = y3 - y4
den = dx12 * dy34 - dy12 * dx34
in if den == 0
then Nothing
else let det12 = x1*y2 - y1*x2
det34 = x3*y4 - y3*x4
numx = det12 * dx34 - dx12 * det34
numy = det12 * dy34 - dy12 * det34
in Just (numx / den, numy / den)
-- copiado do Gloss para Double
closestPontoOnL :: Ponto -> Ponto -> Ponto -> Double
closestPontoOnL p1 p2 p3 = (p3 .-. p1) .$. (p2 .-. p1) / (p2 .-. p1) .$. (p2 .-. p1)
(.*.) :: Double -> (Double,Double) -> (Double,Double)
(.*.) x (a,b) = ((x*a),(x*b))
(.+.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.+.) (x,y) (a,b) = ((x+a),(y+b))
(.-.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.-.) (x,y) (a,b) = ((x-a),(y-b))
-- the dot product between two (Double,Double)s
(.$.) :: (Double,Double) -> (Double,Double) -> Double
(.$.) (d1,a1) (d2,a2) = (x1*x2) + (y1*y2)
where (x1,y1) = (d1,a1)
(x2,y2) = (d2,a2)
radians th = th * (pi/180)
degrees th = th * (180/pi)
arrowToComponents :: (Double,Double) -> Ponto
arrowToComponents (v,th) = (getX v th,getY v th)
where getX v th = v * cos (radians (th))
getY v th = v * sin (radians (-th))
componentsToArrow :: Ponto -> (Double,Double)
componentsToArrow (x,0) | x >= 0 = (x,0)
componentsToArrow (x,0) | x < 0 = (abs x,180)
componentsToArrow (0,y) | y >= 0 = (y,-90)
componentsToArrow (0,y) | y < 0 = (abs y,90)
componentsToArrow (x,y) = (hyp,dir angle)
where
dir o = case (x >= 0, y >= 0) of
(True,True) -> -o
(True,False) -> o
(False,False) -> 180 - o
(False,True) -> 180 + o
hyp = sqrt ((abs x)^2 + (abs y)^2)
angle = degrees $ atan (abs y / abs x)
dist :: Ponto -> Ponto -> Double
dist (x1,y1) (x2,y2) = sqrt ((x2-x1)^2+(y2-y1)^2)
--------------
testeMapa =
[[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0
,Peca Lava 0,Peca Lava 0,Peca Lava 0]
,[Peca Lava 0,Peca (Curva Norte) 0,Peca (Rampa Este) 0,Peca Recta 1,Peca (Rampa Oeste) 0,Peca Recta 0,Peca Recta 0,Peca (Rampa Oeste) (-1),Peca Recta (-1)
,Peca (Rampa Este) (-1),Peca (Rampa Este) 0,Peca (Rampa Oeste) 0,Peca (Rampa Oeste) (-1),Peca (Curva Este) (-1),Peca Lava 0]
,[Peca Lava 0,Peca (Curva Oeste) 0,Peca (Rampa Este) 0,Peca (Rampa Oeste) 0,Peca (Rampa Este) 0,Peca Recta 1,Peca (Rampa Oeste) 0,Peca (Rampa Oeste) (-1)
,Peca Recta (-1),Peca (Rampa Oeste) (-2),Peca (Rampa Oeste) (-3),Peca (Rampa Este) (-3),Peca (Rampa Este) (-2),Peca (Curva Sul) (-1),Peca Lava 0]
,[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0
,Peca Lava 0,Peca Lava 0,Peca Lava 0]]
-- 00011110000009999001100999
-- ..//>>[]<<[][]<<[]>>>><<<<\\..
-- ..\\>><<>>[]<<<<[]<<<<>>>>//..
-- 00011001111009999887788999
testeCurvas =
[[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0]
,[Peca Lava 0,Peca (Curva Norte) 0,Peca (Rampa Oeste) (-1),Peca (Curva Este) (-1),Peca Lava 0,Peca (Curva Norte) 0,Peca (Curva Este) 0
,Peca Lava 0,Peca (Curva Norte) 1,Peca (Curva Este) 1,Peca Lava 0]
,[Peca Lava 0,Peca (Rampa Sul) 0,Peca Lava 0,Peca (Curva Oeste) (-1),Peca (Rampa Este) (-1),Peca (Curva Sul) 0,Peca (Curva Oeste) 0
,Peca (Rampa Este) 0,Peca (Curva Sul) 1,Peca Recta 1,Peca Lava 0]
,[Peca Lava 0,Peca (Curva Oeste) 1,Peca (Rampa Oeste) 0,Peca Recta 0,Peca (Rampa Oeste) (-1),Peca Recta (-1),Peca (Rampa Este) (-1)
,Peca (Rampa Este) 0,Peca Recta 1,Peca (Curva Sul) 1,Peca Lava 0]
,[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0]]
-- ..//<<\\..//\\..//\\..
-- ..\/..\\>>//\\>>//[]..
-- ..\\<<[]<<[]>>>>[]//..
unitTests :: [(Tabuleiro,Tempo,Carro)]
unitTests = [
--- apenas um passo recursivo
-- rectas: passa percurso
(testeMapa , 1.2, Carro (5.5,1.5) 0 (0.9,0.1))
-- rectas: cai adjacente
, (testeMapa , 1.2, Carro (5.5,2.5) 0 (0.1,-0.9))
-- rectas: passa adjacente
, (testeMapa , 1.2, Carro (8.5,1.5) 0 (0.1,0.9))
-- rectas: choca adjacente
, (testeMapa , 1.2, Carro (5.5,1.5) 0 (0.1,0.9))
-- rectas: cai lava
, (testeMapa , 1.2, Carro (3.5,1.5) 0 (0.1,-0.9))
-- rectas: passa lava (mesma altura)
, (testeMapa , 1.2, Carro (5.5,1.5) 0 (0.1,-0.9))
-- rectas: choca lava
, (testeMapa , 1.2, Carro (8.5,1.5) 0 (0.1,-0.9))
-- curva: choca lava
, (testeMapa , 1.2, Carro (13.4,1.5) 0 (0.3,-0.1))
-- curva: cai lava (mesma altura)
, (testeMapa , 1.2, Carro (1.6,1.5) 0 (-0.3,-0.1))
-- recta->curva: cai
, (testeCurvas , 1.2, Carro (8.5,3.5) 0 (0.1,-0.9))
-- recta->curva: lava
, (testeCurvas , 1.2, Carro (5.5,3.5) 0 (0.1,-0.9))
-- recta->curva: choca
, (testeCurvas , 1.2, Carro (3.5,3.5) 0 (0.1,-0.9))
--- dois+ passos recursivos
-- rectas: passa percurso 2
, (testeMapa , 1.2, Carro (3.6,1.5) 0 (-1.6,0.1))
-- rectas: passa percurso 3
, (testeMapa , 1.2, Carro (4.6,1.5) 0 (-2.6,0.1))
-- curvas: cai lava (mesma altura) 3
, (testeMapa , 1.2, Carro (3.6,1.5) 0 (-2.6,0.1))
-- rectas: adjacente + cai lava (mesma altura) 10
, (testeMapa , 5.5, Carro (12.5,1.2) 0 (-2.1,0.1))
-- rectas: adjacente + choca lava 2
, (testeMapa , 1.2, Carro (8.5,1.5) 0 (0.1,1.9))
-- rectas: choca lava + adjacente 2
, (testeMapa , 1.2, Carro (8.5,2.5) 0 (0.1,1.9))
-- rectas: choca lava + adjacente + choca lava 3
, (testeMapa , 1.2, Carro (8.5,2.5) 0 (0.1,2.3))
-- rectas: choca lava + adjacente + choca lava + adjacente 4
, (testeMapa , 1.2, Carro (8.5,2.5) 0 (0.1,3.3))
-- rectas: choca adjacente + cai lava (mesma altura) 2
, (testeMapa , 1.2, Carro (5.5,1.5) 0 (0.1,1.9))
-- curvas: adjacente + choca lava 3
, (testeMapa , 1.2, Carro (11.6,1.5) 0 (2.1,0.1))
-- curva: adjacente + cai lava 2
, (testeMapa , 1.2, Carro (1.6,2.5) 0 (-0.1,-1.1))
-- curva: choca lava 2
, (testeMapa , 1.2, Carro (12.5,1.5) 0 (2.8,-0.1))
-- curva: cai 2 (passa a lava) -- @nmm nao percebo a particularidade deste teste!
, (testeMapa , 1.2, Carro (1.6,2.5) 0 (-0.3,-0.1))
----- PLANO NOVO (cai se queda >= 1, choca se degrau >= 1, passa se diff. entre 1 e -1)
-- rampas: cai
, (testeMapa , 1.2, Carro (10.5,1.5) 0 (-0.1,0.9))
-- rampas: choca
, (testeMapa , 1.2, Carro (10.5,2.5) 0 (0.1,-0.9))
-- rampas: passa (igual)
, (testeMapa , 1.2, Carro (2.5,1.5) 0 (0.1,0.9))
-- rampas x2: passa (um pouco maior)
, (testeMapa , 1.2, Carro (4.5,1.5) 0 (0.1,0.9))
-- rampas x2: passa (um pouco menor)
, (testeMapa , 1.2, Carro (4.5,1.5) 0 (-0.1,0.9))
---- casos difíceis (sobe/desce Bom Jesus)!
-- rampas: choca (tricky)
, (testeMapa , 1.2, Carro (9.5,2.5) 0 (0.1,-0.9))
-- rampas: não choca (tricky)
, (testeMapa , 1.2, Carro (9.5,2.5) 0 (-0.1,-0.9))
-- rampas: passa (tricky)
, (testeMapa , 1.2, Carro (9.5,1.5) 0 (0.1,0.9))
-- rampas: não passa (tricky)
, (testeMapa , 1.2, Carro (9.5,1.5) 0 (-0.1,0.9))
-- rampas: choca rés-vés (tricky x2)
, (testeMapa , 1.2, Carro (9.5,2.5) 0 (0,-0.9))
-- rampas: choca lava
, (testeMapa , 1.2, Carro (9.5,2.5) 0 (0.1,0.9))
-- rampas: cai lava
, (testeMapa , 1.2, Carro (9.5,1.5) 0 (0.1,-0.9))
------
----- PLANO ANTIGO (cai se altura maior, choca se menor, passa se igual)
-- -- rampas: cai
-- , (testeMapa , 1.2, Carro (6.5,2.5) 0 (0.1,-0.9)) -- oracle: (6.6,1.4), got Noth
-- -- rampas: passa
-- , (testeMapa , 1.2, Carro (2.5,1.5) 0 (0.1,0.9))
-- -- rampas: choca
-- , (testeMapa , 1.2, Carro (3.5,2.5) 0 (0.1,-0.9)) -- oracle: (_.1.5), got (_,2.6)
-- -- rampas x2: choca
-- , (testeMapa , 1.2, Carro (4.5,1.5) 0 (0.1,0.9)) -- oracle (_.2.5), got (_,1.4)
-- -- rampas x2: cai
-- , (testeMapa , 1.2, Carro (4.5,1.5) 0 (-0.1,0.9)) -- oracle (4.4,2.6), got Noth
-- -- rampas x2: bónus - passa?
-- , (testeMapa , 1.2, Carro (4.5,1.5) 0 (0,0.9))
-------------
]
|
hpacheco/HAAP
|
examples/plab/svn/2017li1g180/src/Tarefa3_2017li1g180.hs
|
Haskell
|
mit
| 19,467
|
newtype Stack a = Stk [a] deriving(Show)
-- The follwing Functions are supposed declared in the exams' question (just to make it work)
-- Start top/pop/push/empty
top :: Stack a -> a
top (Stk []) = error "Stack is empty, can't call top function on it!"
top (Stk (x:_)) = x
pop :: Stack a -> Stack a
pop (Stk []) = error "Stack is empty, can't call pop function on it!"
pop (Stk (x:xs)) = Stk xs
push :: a -> Stack a -> Stack a
push x (Stk xs) = Stk (x:xs)
empty :: Stack a -> Bool
empty (Stk []) = True
empty _ = False
-- End top/pop/push/empty
-- 1) cvider
cvider :: Stack a -> [a]
cvider s | empty s = []
| otherwise = (top s):(cvider (pop s))
-- 2) vider
vider :: Stack a -> (a -> Bool) -> [a] -> ([a], Stack a)
vider (Stk []) _ _ = ([], (Stk []))
vider s p ys | p $ top s = (ys,pop s)
| otherwise = let (k,l) = vider (pop s) p ys in ((top s):k, l)
-- 3) transform
-- Algo: http://csis.pace.edu/~wolf/CS122/infix-postfix.htm (the last part; summary)
prio :: Char -> Int
prio '+' = 1
prio '*' = 2
prio '(' = 0
isOperand :: Char -> Bool
isOperand x | x == '+' || x == '*' || x == '(' || x == ')' = False
| otherwise = True
transform :: [Char] -> [Char]
transform xs = tr' xs (Stk [])
tr' :: [Char] -> Stack Char -> [Char]
tr' [] s = cvider s
tr' (x:xs) s@(Stk []) | isOperand x = x:(tr' xs s)
| otherwise = tr' xs (push x s)
tr' (x:xs) s | isOperand x = x:(tr' xs s)
| x == ')' = let (ys,t) = vider s (== '(') [] in ys ++ (tr' xs t)
| x == '(' = tr' xs (push '(' s)
| (prio x) > (prio ts) = tr' xs (push x s)
| otherwise = ts:(tr' (x:xs) (pop s))
where ts = top s
-- 4) pe2st (postfix expression to a syntaxic tree)
data AS = E | Node Char AS AS
pe2st :: [Char] -> AS
pe2st = pe2st' . (foldl (flip push) (Stk []))
pe2st' :: Stack Char -> AS
pe2st' s | isOperand ts = Node ts E E
| otherwise = let (fstST, sndST, _) = squeeze (pop s) in Node ts fstST sndST
where ts = top s
squeeze :: Stack Char -> (AS, AS, Stack Char) -- Left Squeezed, Right Squeezed, The rest after the squeezing is DONE! // Fuck this function in particular
squeeze s | isOperand ts && isOperand tss = (Node ts E E, Node tss E E, pss)
| isOperand ts = (Node ts E E, pe2st' ps, Stk [])
| otherwise = (Node ts sqzFst sqzSnd, pe2st' sqzRest, Stk [])
where ts = top s
tss = top ps
ps = pop s -- no ts
pss = pop ps -- no ts && no tss
(sqzFst, sqzSnd, sqzRest) = squeeze ps
-- Debugging the correctness of the tree
instance Show AS where
show E = "E"
show (Node c s t) = "(" ++ [c] ++ " " ++ show s ++ ", " ++ show t ++ ")"
-- Tests:
-- Test 1) cvider (Stk [1..5]) => [1,2,3,4,5]
-- Test 2) vider (Stk [1,3,5,4,8,7,10,9]) even [] => ([1,3,5], Stack [8,7,10,9])
-- Test 3) transform "a*(b+c)+d*f" => "abc+*df*+"
-- Test 4) pe2st (transform "a*(b+c)+d*f") => Should give u the correct tree xZ
|
NMouad21/HaskellSamples
|
HaskellFinalExV.hs
|
Haskell
|
mit
| 3,112
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DefaultSignatures #-}
module Solar.Utility.NoCache where
import Data.Typeable
import Data.Generics as D
import GHC.Generics as G
import Data.Monoid
-- | The "No Cache" data type, use 'kvNoCache' to provide a typed 'Nothing'
data KVNoCache n r c = KVNoCache
deriving (Show, Read, Typeable, Eq, Ord, Data, G.Generic)
-- | Gives a typed 'Nothing' of 'KVNoCache'
kvNoCache :: (Maybe (KVNoCache n r c))
kvNoCache = Nothing
instance Monoid (KVNoCache n r c) where
mempty = KVNoCache
mappend a _ = a
|
Cordite-Studios/solar
|
solar-shared/Solar/Utility/NoCache.hs
|
Haskell
|
mit
| 589
|
module HistogramTest where
import Control.Concurrent.Async
import Data.Metrics.Histogram.Internal
import Data.Metrics.Snapshot
import Data.Metrics.Types
import System.Random.MWC
import System.Posix.Time
import Test.QuickCheck
histogramTests :: [Test]
histogramTests =
[ testUniformSampleMin
, testUniformSampleMax
, testUniformSampleMean
, testUniformSampleMeanThreaded
, testUniformSample2000
-- , testUniformSample2000Threaded
, testUniformSampleSnapshot
, testUniformSampleSnapshotThreaded
, testExponentialSampleMin
, testExponentialSampleMax
, testExponentialSampleMean
, testExponentialSampleMeanThreaded
, testExponentialSample2000
--, testExponentialSample2000Threaded
, testExponentialSampleSnapshot
, testExponentialSampleSnapshotThreaded
-- , testExponentialSampleLongIdle
]
withUniform :: (Histogram IO -> IO a) -> IO a
withUniform f = do
seed <- withSystemRandom (asGenIO save)
h <- uniformHistogram seed
f h
withExponential :: (Histogram IO -> IO a) -> IO a
withExponential f = do
seed <- withSystemRandom (asGenIO save)
t <- epochTime
h <- exponentiallyDecayingHistogram t seed
f h
uniformTest :: Assertable a => String -> (Histogram IO -> IO a) -> Test
uniformTest d f = d ~: test $ assert $ withUniform f
exponentialTest :: Assertable a => String -> (Histogram IO -> IO a) -> Test
exponentialTest d f = d ~: test $ assert $ withExponential f
testUniformSampleMin :: Test
testUniformSampleMin = uniformTest "uniform min value" $ \h -> do
update h 5
update h 10
x <- minVal h
assertEqual "min" 5 x
testUniformSampleMax :: Test
testUniformSampleMax = uniformTest "uniform max value" $ \h -> do
update h 5
update h 10
x <- maxVal h
assertEqual "max" 10 x
testUniformSampleMean :: Test
testUniformSampleMean = uniformTest "uniform mean value" $ \h -> do
update h 5
update h 10
x <- mean h
assertEqual "mean" 7.5 x
testUniformSampleMeanThreaded :: Test
testUniformSampleMeanThreaded = uniformTest "async uniform mean value" $ \h -> do
let task = update h 5 >> update h 10
asyncs <- sequence $ replicate 10 (async $ task)
mapM_ wait asyncs
x <- mean h
assert $ x == 7.5
testUniformSample2000 :: Test
testUniformSample2000 = uniformTest "uniform sample 2000" $ \h -> do
mapM_ (update h $) [0..1999]
x <- maxVal h
assert $ x == 1999
--testUniformSample2000Threaded :: Test
--testUniformSample2000Threaded ="" ~: test $ do
-- x <- with
testUniformSampleSnapshot :: Test
testUniformSampleSnapshot = uniformTest "uniform snapshot" $ \h -> do
mapM_ (update h $) [0..99]
s <- snapshot h
assert $ median s == 49.5
testUniformSampleSnapshotThreaded :: Test
testUniformSampleSnapshotThreaded = uniformTest "async uniform snapshot" $ \h -> do
let task = mapM_ (update h $) [0..99]
asyncs <- sequence $ replicate 10 (async $ task)
mapM_ wait asyncs
s <- snapshot h
assertEqual "median" 49.5 $ median s
testExponentialSampleMin :: Test
testExponentialSampleMin = exponentialTest "minVal" $ \h -> do
update h 5
update h 10
x <- minVal h
assertEqual "min" 5 x
testExponentialSampleMax :: Test
testExponentialSampleMax = exponentialTest "maxVal" $ \h -> do
update h 5
update h 10
x <- maxVal h
assertEqual "max" 10 x
testExponentialSampleMean :: Test
testExponentialSampleMean = exponentialTest "mean" $ \h -> do
update h 5
update h 10
x <- mean h
assertEqual "mean" 7.5 x
testExponentialSampleMeanThreaded :: Test
testExponentialSampleMeanThreaded = exponentialTest "mean threaded" $ \h -> do
let task = update h 5 >> update h 10
asyncs <- sequence $ replicate 10 (async $ task)
mapM_ wait asyncs
x <- mean h
assertEqual "mean" 7.5 x
testExponentialSample2000 :: Test
testExponentialSample2000 = exponentialTest "sample 2000" $ \h -> do
mapM_ (update h $) [0..1999]
x <- maxVal h
assertEqual "max" 1999 x
--testExponentialSample2000Threaded :: Test
--testExponentialSample2000Threaded = exponentialTest "async sample 2000" $ \h -> do
-- x <- with
testExponentialSampleSnapshot :: Test
testExponentialSampleSnapshot = exponentialTest "snapshot" $ \h -> do
mapM_ (update h $) [0..99]
s <- snapshot h
assertEqual "median" 49.5 $ median s
testExponentialSampleSnapshotThreaded :: Test
testExponentialSampleSnapshotThreaded = exponentialTest "async snapshot" $ \h -> do
let task = mapM_ (update h $) [0..99]
asyncs <- sequence $ replicate 10 (async $ task)
mapM_ wait asyncs
s <- snapshot h
assertEqual "median" 49.5 $ median s
--testExponentialSampleLongIdle :: Test
--testExponentialSampleLongIdle ="" ~: test $ do
-- x <- with
|
graydon/metrics
|
tests/HistogramTest.hs
|
Haskell
|
mit
| 4,609
|
{-# LANGUAGE TypeOperators, OverloadedStrings, FlexibleContexts, ScopedTypeVariables #-}
module Wf.Control.Eff.Run.Session
( runSession
, getRequestSessionId
, genSessionId
) where
import Control.Eff (Eff, (:>), Member, freeMap, handleRelay)
import Control.Eff.Reader.Strict (Reader, ask)
import Wf.Control.Eff.Session (Session(..))
import Control.Monad (when)
import qualified Data.ByteString as B (ByteString, append)
import qualified Data.ByteString.Char8 as B (pack)
import qualified Data.List as L (lookup)
import qualified Data.HashMap.Strict as HM (lookup, insert)
import qualified Blaze.ByteString.Builder as Blaze (toByteString)
import qualified Network.Wai as Wai (Request, requestHeaders, isSecure)
import qualified Web.Cookie as Cookie (parseCookies, renderSetCookie, def, setCookieName, setCookieValue, setCookieExpires, setCookieSecure, setCookieHttpOnly, setCookieDomain, setCookiePath)
import Wf.Session.Types (SessionState(..), SessionData(..), SessionSettings(..), SetCookieSettings(..), SessionHandler(..), defaultSessionState)
import qualified Wf.Application.Time as T (Time, formatTime, addSeconds)
import Wf.Application.Random (randomByteString)
runSession
:: Member (Reader Wai.Request) r
=> SessionHandler (Eff r)
-> SessionSettings
-> T.Time
-> Eff (Session :> r) a
-> Eff r a
runSession handler sessionSettings current eff = do
requestSessionId <- fmap (getRequestSessionId sname) ask
s <- loadSession requestSessionId
(r, s') <- loop s eff
when (s' /= s) $ saveSession s'
return r
where
sname = sessionName sessionSettings
scSettings = sessionSetCookieSettings sessionSettings
loop s = freeMap (\a -> return (a, s)) $
\u -> handleRelay u (loop s) (handle s)
newSession = sessionHandlerNew handler sessionSettings current
loadSession = sessionHandlerLoad handler current
saveSession = sessionHandlerSave handler current
sessionDestroy = sessionHandlerDestroy handler
handle s (SessionGet decode k c) = do
let m = HM.lookup k . sessionValue . sessionData $ s
loop s . c $ decode =<< m
handle s (SessionPut encode k v c) = do
s' <- if sessionId s == ""
then newSession
else return s
loop (f s') c
where
f ses @ (SessionState _ d @ (SessionData m _ _) _) = ses { sessionData = d { sessionValue = HM.insert k (encode v) m } }
handle s (SessionTtl ttl' c) = loop (f s) c
where
expire = T.addSeconds current ttl'
f ses @ (SessionState _ d _) = ses { sessionData = d { sessionExpireDate = expire } }
handle s (SessionDestroy c) = do
when (sid /= "") (sessionDestroy sid)
loop defaultSessionState c
where
sid = sessionId s
handle s (GetSessionId c) =
loop s . c . sessionId $ s
handle s (RenderSetCookie c) = do
requestIsSecure <- fmap Wai.isSecure ask
loop s . c $ ("Set-Cookie", Blaze.toByteString . Cookie.renderSetCookie $ setCookie requestIsSecure)
where
sid = sessionId s
expires = if addExpires scSettings
then Just . sessionExpireDate . sessionData $ s
else Nothing
setCookie requestIsSecure = Cookie.def
{ Cookie.setCookieName = sname
, Cookie.setCookieValue = sid
, Cookie.setCookieExpires = expires
, Cookie.setCookieSecure = requestIsSecure && addSecureIfHttps scSettings
, Cookie.setCookieHttpOnly = isHttpOnly scSettings
, Cookie.setCookieDomain = cookieDomain scSettings
, Cookie.setCookiePath = cookiePath scSettings
}
getRequestSessionId :: B.ByteString -> Wai.Request -> Maybe B.ByteString
getRequestSessionId name = (L.lookup name =<<) . fmap Cookie.parseCookies . L.lookup "Cookie" . Wai.requestHeaders
genSessionId :: B.ByteString -> T.Time -> Int -> IO B.ByteString
genSessionId sname t len = do
let dateStr = B.pack $ T.formatTime ":%Y%m%d:" t
randomStr <- randomByteString len
return $ sname `B.append` dateStr `B.append` randomStr
|
bigsleep/Wf
|
wf-session/src/Wf/Control/Eff/Run/Session.hs
|
Haskell
|
mit
| 4,197
|
main :: IO ()
main = error "undefined"
|
mlitchard/cosmos
|
executable/old.hs
|
Haskell
|
mit
| 40
|
{-# LANGUAGE OverloadedStrings #-}
module Bce.BlockChainSerialization where
import Bce.Hash
import Bce.Crypto
import qualified Bce.BlockChain as BlockChain
import Bce.BlockChainHash
import qualified Data.Binary as Bin
import GHC.Generics (Generic)
import qualified Data.Binary.Get as BinGet
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import qualified Data.Text.Encoding as TextEncoding
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as B16
instance Bin.Binary Hash
instance Bin.Binary PubKey
instance Bin.Binary PrivKey
instance Bin.Binary KeyPair
instance Bin.Binary BlockChain.TxOutputRef
instance Bin.Binary BlockChain.TxOutput
instance Bin.Binary BlockChain.TxInput
instance Bin.Binary BlockChain.Transaction
instance Bin.Binary BlockChain.BlockHeader
instance Bin.Binary BlockChain.Block
instance Aeson.ToJSON BS.ByteString where
toJSON bs = Aeson.toJSON (TextEncoding.decodeUtf8 $ B16.encode bs)
instance Aeson.FromJSON BS.ByteString where
parseJSON (Aeson.String txt) = return $ fst $ B16.decode $ TextEncoding.encodeUtf8 txt
instance Aeson.FromJSON Hash
instance Aeson.FromJSON PubKey
instance Aeson.FromJSON PrivKey
instance Aeson.FromJSON BlockChain.TxOutputRef
instance Aeson.FromJSON BlockChain.TxOutput
instance Aeson.FromJSON BlockChain.TxInput
instance Aeson.FromJSON BlockChain.Transaction
instance Aeson.FromJSON BlockChain.BlockHeader
instance Aeson.FromJSON BlockChain.Block
instance Aeson.ToJSON Hash
instance Aeson.ToJSON PubKey
instance Aeson.ToJSON PrivKey
instance Aeson.ToJSON BlockChain.TxOutputRef
instance Aeson.ToJSON BlockChain.TxOutput
instance Aeson.ToJSON BlockChain.TxInput
instance Aeson.ToJSON BlockChain.Transaction
instance Aeson.ToJSON BlockChain.BlockHeader
instance Aeson.ToJSON BlockChain.Block
|
dehun/bce
|
src/Bce/BlockChainSerialization.hs
|
Haskell
|
mit
| 2,013
|
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Data.Word.Compat"
-- from a globally unique namespace.
module Data.Word.Compat.Repl.Batteries (
module Data.Word.Compat
) where
import "this" Data.Word.Compat
|
haskell-compat/base-compat
|
base-compat-batteries/src/Data/Word/Compat/Repl/Batteries.hs
|
Haskell
|
mit
| 278
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.